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:
- Read the image: First, load the image using OpenCV’s cv2.imread() function.
- 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.
- 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:
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
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).
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Thank you! Literally, it was all I needed for many years.