Open In App

How to Edit a Pixel Value using OpenCV

Last Updated : 06 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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:

download
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:

downloa
Modified image with single row of pixels

Here 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:

download
Modified image with Modified region of pixels

The 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.


Article Tags :

Similar Reads