Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the coordinates in an image where a specified colour is detected

I'm trying to make a program which takes in an image and looks throughout the image to find a colour, lets say blue, and give out the coordinates of that point in the image which has that colour.

like image 448
YJJcoolcool Avatar asked Oct 23 '25 22:10

YJJcoolcool


1 Answers

You can do that very simply with Numpy which is what underpins most image processing libraries in Python, such as OpenCV, or skimage, or Wand. Here I'll do it with OpenCV, but you could equally use any of the above or PIL/Pillow.

Using this image which has a blue line on the right side:

enter image description here

#!/usr/bin/env python3

import cv2
import numpy as np

# Load image
im = cv2.imread('image.png')

# Define the blue colour we want to find - remember OpenCV uses BGR ordering
blue = [255,0,0]

# Get X and Y coordinates of all blue pixels
Y, X = np.where(np.all(im==blue,axis=2))

print(X,Y)

Or, if you want them zipped into a single array:

zipped = np.column_stack((X,Y))

If you prefer to use PIL/Pillow, it would go like this:

from PIL import Image
import numpy as np

# Load image, ensure not palettised, and make into Numpy array
pim = Image.open('image.png').convert('RGB')
im  = np.array(pim)

# Define the blue colour we want to find - PIL uses RGB ordering
blue = [0,0,255]

# Get X and Y coordinates of all blue pixels
Y, X = np.where(np.all(im==blue,axis=2))

print(X,Y)
like image 198
Mark Setchell Avatar answered Oct 26 '25 12:10

Mark Setchell