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.
问题:
回答1:
In order to do so, you need a few pieces of information, including the height and width of the image in pixels, as well as the colormap of the image. I have done something similar to this before, and I used PIL (Pillow) to extract the color values of each individual pixel. Using this method, you should be able to reformat the pixel colour values into a two-dimensional array (array[x][y], where x is the x-coordinate and y is the y-coordinate, for easy comparison) and compare the individual pixel values with a specified RGB value.
If you have an image of unknown height and width, you could do the following to obtain the image height and width:
from PIL import Image
image = Image.open('path/to/file.jpg')
width, height = image.size
After this, you can use the following to get the pixel color values in RGB format in a list:
pixval = list(image.getdata())
temp = []
hexcolpix = []
for row in range(0, height, 1):
for col in range(0, width, 1):
index = row*width + col
temp.append(pixval[index])
hexcolpix.append(temp)
temp = []
You can then do a comparison to find pixels that match your specified colour
回答2:
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:
#!/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
X,Y = np.where(np.all(im==blue,axis=2))
print(X,Y)
Output
[ 0 2 4 6 8 10 12 14 16 18] [80 81 82 83 84 85 86 87 88 89]
Or, if you want them zipped into a single array:
zipped = np.column_stack((X,Y))
array([[ 0, 80],
[ 2, 81],
[ 4, 82],
[ 6, 83],
[ 8, 84],
[10, 85],
[12, 86],
[14, 87],
[16, 88],
[18, 89]])
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
X,Y = np.where(np.all(im==blue,axis=2))
print(X,Y)