I use Python, opencv and PIL.
image = cv2.imread('image.jpg')
color = (235, 187, 7)
How can I get pixel coordinates(x, y) if I know pixels color?
Retrieving the pixel contents (ARGB values) of an image −Get the pixel value at every point using the getRGB() method. Instantiate the Color object by passing the pixel value as a parameter. Get the Red, Green, Blue values using the getRed(), getGreen() and getBlue() methods respectively.
In terms of coordinates, a pixel can be identified by a pair of integers giving the column number and the row number. For example, the pixel with coordinates (3,5) would lie in column number 3 and row number 5. Conventionally, columns are numbered from left to right, starting with zero.
Use the ColorSync Utility calculator to get the color values of a pixel on your screen. In the ColorSync Utility app on your Mac, click Calculator in the toolbar of the ColorSync Utility window. Click the magnifying glass , then move the pointer over an area on the screen that you want to examine.
For example, assume the value (intensity) of red, green, and blue can each take on 256 values (0 through 255) for a pixel. An RGB value of (255, 0, 0) would imply a red pixel, an RGB value of (0, 255, 0) would be green, and an RGB value of (0, 0, 255) would be blue.
Here is a numpythonic solution. Numpy library speeds up operations wherever possible.
color = (235, 187, 7)
indices = np.where(img == color)
Now indices
returns something like the following:
(array([ 81, 81, 81, ..., 304, 304, 304], dtype=int64),
array([317, 317, 317, ..., 520, 520, 520], dtype=int64),
array([0, 1, 2, ..., 0, 1, 2], dtype=int64))
coordinates = zip(indices[0], indices[1])
set()
method.unique_coordinates = list(set(list(coordinates)))
Try something like:
color = (235, 187, 7)
im = Image.open('image.gif')
rgb_im = im.convert('RGB')
for x in range(rgb_im.size()[0]):
for y in range(rgb_im.size()[1]):
r, g, b = rgb_im.getpixel((x, y))
if (r,g,b) == colour:
print(f"Found {colour} at {x},{y}!")
But getpixel can be slow, so look at using pixel access objects.
Also note that the value returned can depend on the image type. For example, a single value is returned with pix[1, 1]
because GIF pixels refer to one of the 256 values in the GIF color palette.
See also this SO post: Python and PIL pixel values different for GIF and JPEG and this PIL Reference page contains more information on the convert()
function.
By the way, your code would work just fine for .jpg
images.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With