How To Get Pixel Coordinates Of An Image In Python

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:

Step 2: Import Required Libraries

After installation, let’s import both modules and load the image using the Image module from the PIL library:

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:

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:

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.


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.