How to Edit a Pixel Value using OpenCV
Last Updated :
06 Jan, 2025
Let's understand steps to edit and modify pixel values using OpenCV:
- Step 1: Import Necessary Libraries: OpenCV (
cv2
) is the primary library for handling images. - Step 2: Read the Image: Use
cv2.imread()
to load the image into a NumPy array. Each pixel is represented as an element in the array. - Step 3: Access Pixel Values: Use NumPy indexing to access the pixel values. The format depends on the image type (e.g., grayscale or color).
- Step 4: Modify the Pixel: Assign a new value to the desired pixel location.
- Step 5: Save or Display the Image: After editing, save the image using
cv2.imwrite()
or display it using cv2.imshow()
.
Now, we will edit a pixel values using OpenCV by following practical examples:
1. Changing a Single Pixel Value
Python
import cv2
import matplotlib.pyplot as plt
import requests
from PIL import Image
from io import BytesIO
# Image URL
image_url = "https://media.geeksforgeeks.org/wp-content/uploads/20210228231058/gfg.png"
response = requests.get(image_url)
img_data = response.content
img = Image.open(BytesIO(img_data))
image = np.array(img)
image_shape = image.shape
print(f"Image dimensions (height, width, channels): {image_shape}")
modified_image = image.copy()
coord1 = (150, 200)
coord2 = (100, 150)
def is_valid_coordinate(image, coord):
return 0 <= coord[0] < image.shape[0] and 0 <= coord[1] < image.shape[1]
if is_valid_coordinate(image, coord2):
print(f"Pixel value at {coord2}: {image[coord2]} (BGR)")
modified_image[coord2] = [0, 0, 0]
print(f"After modifying, pixel value at {coord2}: {modified_image[coord2]} (BGR)")
else:
print(f"Coordinate {coord2} is out of bounds.")
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(modified_image, cv2.COLOR_BGR2RGB))
plt.title('Modified Image')
plt.axis('off')
plt.show()
Output:
Modified image with change of pixel value Image dimensions (height, width, channels): (400, 400, 3)
Pixel value at (100, 150): [ 48 141 70] (BGR)
After modifying, pixel value at (100, 150): [0 0 0] (BGR)
Here we change pixel value of coordinate (100,250) to pixel value [0,0,0] i.e pure black. Changing the value of a single pixel allows us to highlight or isolate a specific point in a image.
2. Changing Pixels of a single Row
Python
import cv2
import matplotlib.pyplot as plt
import requests
from PIL import Image
from io import BytesIO
import numpy as np
image_url = "https://media.geeksforgeeks.org/wp-content/uploads/20210228231058/gfg.png"
response = requests.get(image_url)
img_data = response.content
img = Image.open(BytesIO(img_data))
image = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
image_shape = image.shape
modified_image = image.copy()
row_to_modify = 170
if 0 <= row_to_modify < image_shape[0]:
modified_image[row_to_modify, :] = [255, 0, 0]
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(modified_image, cv2.COLOR_BGR2RGB))
plt.title('Modified Image with a Row')
plt.axis('off')
plt.show()
Output:
Modified image with single row of pixelsHere we added a blue line i.e [255,0,0] at coordinate Y=100. Modifying an entire row of pixels helps creating visual effects and can be used for horizontal segmentation of an image. This approach is helpful for tasks that require row-wise transformations in images.
3. Changing Pixels in a particular Region
Python
import cv2
import matplotlib.pyplot as plt
import requests
from PIL import Image
from io import BytesIO
import numpy as np
image_url = "https://media.geeksforgeeks.org/wp-content/uploads/20210228231058/gfg.png"
response = requests.get(image_url)
img_data = response.content
img = Image.open(BytesIO(img_data))
image = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
image_shape = image.shape
modified_image = image.copy()
region_top_left = (50, 50)
region_bottom_right = (150, 150)
if (0 <= region_top_left[0] < image_shape[0] and 0 <= region_top_left[1] < image_shape[1] and
0 <= region_bottom_right[0] < image_shape[0] and 0 <= region_bottom_right[1] < image_shape[1]):
modified_image[region_top_left[0]:region_bottom_right[0], region_top_left[1]:region_bottom_right[1]] = [0, 0, 255]
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(modified_image, cv2.COLOR_BGR2RGB))
plt.title('Modified Image with Modified Region')
plt.axis('off')
plt.show()
Output:
Modified image with Modified region of pixelsThe region covers a area starting from coordinates (50, 50)
and ending at coordinates (150, 150)
with this new region changed to
red i.e [0,0,255]
.
This technique can be applied for various uses for Masking sensitive areas of an image like faces in government ID's and Highlighting specific regions to draw attention.
Similar Reads
Image Resizing using OpenCV | Python Image resizing refers to the scaling of images. Scaling comes in handy in many image processing as well as machine learning applications. It helps in reducing the number of pixels from an image and that has several advantages e.g. It can reduce the time of training of a neural network as the more th
3 min read
OpenCV Tutorial in Python OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning library. It allows us to process images and videos, detect objects, faces and even handwriting. This tutorial will guide us through image and video processing from the basics to advanced topics using
5 min read
Image Enhancement Techniques using OpenCV - Python Image enhancement is the process of improving the quality and appearance of an image. It can be used to correct flaws or defects in an image, or to simply make an image more visually appealing. Image enhancement techniques can be applied to a wide range of images, including photographs, scans, and d
15+ min read
Normalize an Image in OpenCV Python Normalization involves adjusting the range of pixel intensity values in an image. Normalization can be beneficial for various purposes, such as improving the contrast or making the image more suitable for processing by other algorithms. In this article, we will explore how to normalize images using
2 min read
Python OpenCV | cv2.imshow() method OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.imshow() method is used to display an image in a window. The window automatically fits the image size. Syntax: cv2.imshow(window_name, image)Parameters: window_name: A string representing the name of the wi
3 min read
How to convert a grayscale image to RGB in OpenCV In image processing, images can be categorized into grayscale and RGB formats. Grayscale images contain varying shades of gray, representing intensity levels, while RGB images use red, green, and blue channels to depict a wider range of colors. Converting grayscale images to RGB is crucial for appli
5 min read