In this tutorial, we will learn how to get the pixel coordinates of an image in Python using the Python Imaging Library (PIL) and the popular image processing library, OpenCV.
With just a few lines of code, we can access the pixels in an image and retrieve the values of their x and y coordinates.
Step 1: Install Required Libraries
First, we need to install the required libraries, Pillow and OpenCV. You can install them using pip:
1 |
pip install pillow opencv-python-headless |
Step 2: Import Required Libraries
After installation, let’s import both modules and load the image using the Image
module from the PIL
library:
1 2 3 4 5 |
from PIL import Image import cv2 # Load the image using the PIL library image = Image.open("image.jpg") |
Replace image.jpg
with the path to your desired image file.
Step 3: Get the Pixel Coordinates
Now, we can access the pixel coordinates using the load
method of the Image
object. We’ll create a loop to iterate through all the pixels in the image:
1 2 3 4 5 6 7 8 9 10 11 |
# Access the pixel data pixeldata = image.load() # Iterate through the pixels in the image for y in range(image.size[1]): # loop through height for x in range(image.size[0]): # loop through width # Get the pixel value at (x, y) coordinates pixel_value = pixeldata[x, y] # Print the coordinates and pixel value print(f"Pixel coordinates (x, y) = ({x}, {y}), Pixel value = {pixel_value}") |
In the code above, we have used the range()
function to loop through the width and height of the image, and we have accessed each pixel’s value using the pixeldata
object.
Step 4: Alternative Approach with OpenCV
We can also use the OpenCV library to achieve the same result. The following code demonstrates how to get the pixel coordinates using OpenCV:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import cv2 # Load the image using OpenCV image = cv2.imread("image.jpg") height, width, channels = image.shape # Iterate through the pixels in the image for y in range(height): for x in range(width): # Get the pixel value at (x, y) coordinates pixel_value = image[y, x] # Print the coordinates and pixel value print(f"Pixel coordinates (x, y) = ({x}, {y}), Pixel value = {pixel_value}") |
In the OpenCV approach, we have used the imread
function to load the image, and we have accessed the pixel values using the image
object.
Conclusion
In this tutorial, we have learned how to get the pixel coordinates and their values in an image using Python with the help of Pillow (Python Imaging Library) and OpenCV. These libraries are powerful tools for image processing and can easily handle more advanced tasks related to image manipulation and analysis.