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

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

OpenCV is an open-source library that provides tools for image processing in Python. It can be used to read, write, and modify digital images. In this article, we will learn how to access and modify the pixel values of an image using OpenCV in Python.

Understanding Pixel Values

Before diving into the code, it is essential to understand what pixel values are. In an image, a pixel represents a single point on the image grid. Every pixel has a value, which is determined by its brightness and color. In grayscale images, the pixel value is a single value representing the intensity between 0 and 255, where 0 represents black, and 255 represents white. In color images, the pixel value consists of three values representing the intensity of red, green, and blue (RGB) channels. The combination of these three channels creates the color of the pixel.

Reading and Displaying an Image

To access and modify the pixel values of an image, we first need to read and display the image. To do this, we can use the cv2.imread() and cv2.imshow() functions, respectively. The following code reads and displays an image:

import cv2

# Read image
img = cv2.imread('image.jpg')

# Display image
cv2.imshow('Image', img)
cv2.waitKey(0)

In this code, the cv2.imread() function reads the image named “image.jpg,” which is stored in the same directory as the script. After reading the image, we display it using the cv2.imshow() function. The first argument of this function is the window name, which can be any string. The second argument is the image we want to display. Finally, we wait for a key to be pressed using the cv2.waitKey() function. When any key is pressed, the window is destroyed.

Accessing Pixel Values

Now that we have displayed the image, we can access its pixel values. We can access the pixel values of an image using its coordinates. Every pixel in the image has an x-coordinate and a y-coordinate, which represents its position on the image grid. The pixel values can be accessed using the img[x,y] notation, where x and y are the pixel coordinates. The following code accesses and prints the pixel value of a single pixel in the image:

import cv2

# Read image
img = cv2.imread('image.jpg')

# Access pixel value
pixel_value = img[100, 100]

# Print pixel value
print(pixel_value)

In this code, we first read the image using the cv2.imread() function. Then, we access the pixel value of the pixel with coordinates (100, 100) using the img[100, 100] notation. Finally, we print the pixel value to the console.

Modifying Pixel Values

Now that we know how to access pixel values, we can modify them to change the image. We can change the value of a pixel using the img[x,y] = value notation, where value is the new pixel value. The following code modifies the pixel value of a single pixel in the image:

import cv2

# Read image
img = cv2.imread('image.jpg')

# Modify pixel value
img[100, 100] = [255, 255, 255]

# Display modified image
cv2.imshow('Image', img)
cv2.waitKey(0)

In this code, we first read the image using the cv2.imread() function. Then, we modify the pixel value of the pixel with coordinates (100, 100) to white using the img[100, 100] = [255, 255, 255] notation. Finally, we display the modified image using the cv2.imshow() function.

We can also modify the values of a range of pixels using slicing. Slicing allows us to access a range of pixels in an image using their coordinates. The following code modifies the value of a rectangular region of the image:

import cv2

# Read image
img = cv2.imread('image.jpg')

# Modify region of pixels
img[100:150, 100:150] = [255, 255, 255]

# Display modified image
cv2.imshow('Image', img)
cv2.waitKey(0)

In this code, we modify the values of the rectangular region of the image with the top-left corner at (100, 100) and the bottom-right corner at (150, 150). In this case, the values of all the pixels in this region are set to white, represented by the [255, 255, 255]array.

We can also use loops to modify the pixel values of an entire image. The following code modifies each pixel in the image by reducing the intensity of the red channel:

import cv2

# Read image
img = cv2.imread('image.jpg')

# Get image shape
height, width, channels = img.shape

# Loop over all pixels
for y in range(height):
    for x in range(width):
        # Reduce red channel
        img[y, x, 2] /= 2

# Display modified image
cv2.imshow('Image', img)
cv2.waitKey(0)

In this code, we first read the image using the cv2.imread() function. Then, we get the shape of the image using the img.shape attribute. The height, width, and channels variables hold the height, width, and number of channels of the image, respectively. We then use two loops to iterate over all pixels in the image. For each pixel, we reduce the intensity of the red channel by dividing its value by 2. Finally, we display the modified image using the cv2.imshow() function.

Conclusion

OpenCV provides a powerful set of tools for accessing and modifying pixel values in digital images. In this article, we learned how to read and display an image using OpenCV in Python, as well as how to access and modify its pixel values using coordinates and slicing. We also covered how to use loops to modify the pixel values of an entire image. With this knowledge, you can now start exploring the vast world of image processing and computer vision using OpenCV in Python.

Like(0)

Related

Python OpenCV
Color Identification in Images using Python and OpenCVColor quantization in an image using K-means in OpenCV PythonDetecting corners using Harris corner detector in Python OpenCVHow to Access and Modify Pixel Value in an Image Using OpenCV PythonHow to access image properties in OpenCV using Python?How to Apply Affine Transformation on an Image in OpenCV Python?How to Apply Custom Filters to Images (2D Convolution) Using OpenCV Python?How to apply Perspective Transformations on an image using OpenCV Python?How to Approximate a Contour Shape in an Image Using OpenCV PythonHow to Blend Images Using Image Pyramids in OpenCV Python?How to Blur Faces in an Image using OpenCV Python?How to Change the Contrast and Brightness of an Image Using OpenCV in PythonHow to check if an image contour is convex or not in OpenCV Python?How to Compare Histograms of Two Images Using OpenCV Python?How to compare two images in OpenCV Python?How to Compute and Plot 2D Histograms of an Image in OpenCV Python?How to Compute Hu-Moments of an Image in OpenCV Python?How to Compute Image Moments in OpenCV Python?How to Compute the Area and Perimeter of an Image Contour using OpenCV Python?How to Compute the Aspect Ratio of an Object in an Image using OpenCV Python?How to Compute the Extent of an Object in an Image using OpenCV Python?How to Compute the Morphological Gradient of an Image Using OpenCV in Python?How to Convert a Colored Image to HLS in OpenCV using Python?How to convert an RGB image to HSV image using OpenCV Python?How to create a black image and a white image using OpenCV Python?How to Create a Depth Map from Stereo Images in OpenCV Python?How to Create a Trackbar as the HSV Color Palette using OpenCV Python?How to create a trackbar as the RGB color palette using OpenCV Python?How to Create a Watermark on an Image Using OpenCV Python?How to Crop and Save Detected Faces in OpenCV Python?How to detect a face and draw a bounding box around it using OpenCV Python?Detecting Rectangles and Squares in Images with OpenCV and PythonHow to detect a triangle in an image using OpenCV Python?How to Detect and Draw FAST Feature Points in OpenCV Python?How to detect cat faces in an image in OpenCV using Python?How to detect eyes in an image using OpenCV Python?How to Detect Humans in an Image in OpenCV Python?How to Detect License Plates Using OpenCV Python?How to detect polygons in image using OpenCV Python?How to Draw an Arrowed Line on an Image in OpenCV PythonHow to Draw Filled Ellipses in OpenCV using PythonHow to draw polylines on an image in OpenCV using Python?How to Extract the Foreground of an Image Using OpenCV Python?How to find and draw Convex Hull of an image contour in OpenCV Python?How to Find Discrete Cosine Transform of an Image Using OpenCV PythonHow to Find Gaussian Pyramids for an Image Using OpenCV in Python?How to Find Image Gradients using the Scharr Operator in OpenCV Python?How to Find Laplassian Pyramids for an Image Using OpenCV in Python?How to find patterns in a chessboard using OpenCV Python?How to find the bounding rectangle of an image contour in OpenCV Python?How to find the Fourier Transform of an image using OpenCV Python?How to find the Fourier Transforms of Gaussian and Laplacian filters in OpenCV Python?How to Find the HSV values of a Color Using OpenCV Python?How to find the image gradients using Sobel and Laplacian derivatives in OpenCV Python?How to Find the Minimum Enclosing Circle of an Object in OpenCV Python?How to find the solidity and equivalent diameter of an object in an image using OpenCV Python?How to fit the ellipse to an object in an image using OpenCV Python?How to flip an image in OpenCV Python?How to Implement FLANN Based Feature Matching in OpenCV PythonHow to Implement ORB Feature Detectors in OpenCV Python?How to implement probabilistic Hough Transform in OpenCV Python?How to join two images horizontally and vertically using OpenCV Python?How to Mask an Image in OpenCV Python?How to Match Image Shapes in OpenCV Python?How to Normalize an Image in OpenCV Python?How to Perform Adaptive Mean and Gaussian Thresholding of an Image using Python OpenCV?How to Perform Bilateral Filter Operation on an Image in OpenCV using Python?How to Perform Bitwise AND Operation on Two Images in OpenCV Python?How to Perform Bitwise OR Operation on Two Images in OpenCV PythonHow to Perform Bitwise XOR Operation on Images in OpenCV Python?How to Perform Different Simple Thresholding of an Image Using Python OpenCV?How to Perform Distance Transformation on a Given Image in OpenCV Python?How to Perform Image Rotation in OpenCV using PythonHow to Perform Image Translation Using OpenCV in Python?How to Perform Image Transpose Using OpenCV Python?How to Perform Matrix Transformation in OpenCV Python?How to perform Otsu's thresholding on an image using Python OpenCV?How to Plot Histograms of Different Colors of an Image in OpenCV Python?How to Resize an Image in OpenCV Using Python?How to Rotate an Image in OpenCV Python?How to Split an Image into Different Color Channels in OpenCV Python?Implementing k-Nearest Neighbor in OpenCV PythonImplementing Shi-Tomasi Corner Detector in OpenCV PythonOpenCV Python ŌĆō How to add borders to an image?OpenCV Python ŌĆō How to compute and plot the histogram of a region of an image?OpenCV Python ŌĆō How to Convert a Colored Image to a Binary Image?OpenCV Python – How to detect and draw keypoints in an image using SIFT?Opencv Python – How to display the coordinates of points clicked on an image?OpenCV Python ŌĆō How to draw a rectangle using Mouse Events?OpenCV Python ŌĆō How to Draw Circles Using Mouse Events?OpenCV Python ŌĆō How to draw curves using Mouse Events?OpenCV Python ŌĆō How to find and draw extreme points of an object on an image?OpenCV Python ŌĆō How to find the shortest distance between a point in the image and a contour?OpenCV Python ŌĆō How to perform bitwise NOT operation on an image?OpenCV Python ŌĆō How to Perform SQRBox Filter Operation on An ImageOpenCV Python – Implementing feature matching between two images using SIFTOpenCV Python – Matching the key points of two images using ORB and BFmatcherSmile Detection using Haar Cascade in OpenCV using Python