How to Access and Modify Pixel Value of an Image using OpenCV in Python

Accessing and modifying pixel values in an image using OpenCV in Python can be done using array indexing.

Here’s a step-by-step guide on how to do it:

  1. Read the image: First, load the image using OpenCV’s cv2.imread() function.
  2. Accessing a pixel value: Pixel values can be accessed and modified using the row and column coordinates. In OpenCV, images are read into a NumPy array. The pixel value can be accessed using array notation.
  3. Modify a pixel value: Similarly, you can modify a pixel value by assigning a new value using the array notation.

Before accessing and modifying pixel values, our image looks like this:

Before accessing and modifying pixel values of an image - Krunal Lathiya

Let’s write a code to access and modify the pixels.

import cv2

# Load an image in color (the default flag)
image = cv2.imread('Avatar.png')

# access pixel values using indexing
print("pixel value at [200,150]:", image[200, 150])
print("pixel value blue channel at [200,150]:", image[200, 150][0])
print("pixel value green channel at [200,150]:", image[200, 150][1])
print("pixel value red channel at[200,150]:", image[200, 150][2])

# Draw a red circle around the pixel at [400, 400]
cv2.circle(image, (400, 400), 50, (0, 0, 255), -1)

# Save the modified image
cv2.imwrite('Avatar Modified.png', image)

# Display the modified image
cv2.imshow('Modified Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Modified image using OpenCV

We drew a solid red circle with a radius of 50 pixels centered at the pixel location (150, 200) on the image.

The cv2.circle() function takes the image, the center of the circle (x, y coordinates), the radius of the circle, the color of the circle in BGR format (in this case, red), and the thickness (where -1 suggests a filled circle).

1 thought on “How to Access and Modify Pixel Value of an Image using OpenCV in Python”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.