我使用Python,opencv和PIL。
image = cv2.imread('image.jpg')
color = (235, 187, 7)
如果我知道像素颜色,如何获得像素坐标(x,y)?
答案 0 :(得分:1)
尝试类似的东西:
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}!")
但是getpixel can be slow,所以请考虑使用pixel access objects。
还请注意,返回的值可能取决于图像类型。例如,由于GIF像素引用了GIF调色板中的256个值之一,因此pix[1, 1]
返回了一个值。
另请参见此SO帖子:Python and PIL pixel values different for GIF and JPEG,此PIL Reference page包含有关convert()
函数的更多信息。
顺便说一句,您的代码可以很好地处理.jpg
张图片。
答案 1 :(得分:1)
这是一个numpythonic解决方案。 Numpy库尽可能地加快了操作速度。
color = (235, 187, 7)
indices = np.where(img == color)
现在indices
返回如下内容:
(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()
方法来完成。 unique_coordinates = list(set(list(coordinates)))
答案 2 :(得分:1)
您可以使用以下内容:
import numpy as np
# for color image
color = (75, 75, 75)
pixels = np.argwhere(img == color)
输出(重复相同的坐标三次(颜色数)):
[[ 0 28 0]
[ 0 28 1]
[ 0 28 2]
[ 0 54 0]
[ 0 54 1]
[ 0 54 2]
................]
为避免这种情况,请执行以下操作(对代码可读性感到抱歉):
pixels = pixels[::3][:, [0, 1]]
输出:
[[ 0 28]
[ 0 54]
...........]
对于灰度图像,它看起来更好:
color = (75)
pixels = np.argwhere(img == color)
输出:
[[ 0 28]
[ 0 54]
...........]
答案 3 :(得分:1)
import PIL #The reason I use PIL and not opencv is that I find pillow
#(which is imported with 'PIL') a very useful library for image editing.
image = PIL.Image.open('Name_image') #the image is opened and named image
f = image.load() #I'm not sure what the load() operation exactly does, but it
# is necesarry.
color = (235, 187, 7) # the Red Green Blue values that you want to find the
#coordinates of
PixelCoordinates = [] # List in which all pixel coordinates that match
#requirements will be added.
#The lines of code below check for each pixel in the image if the RGB-values
# are equal to (235, 187, 7)
for x in image.size[0]:
for y in image.size[1]:
if f[x,y] == color:
PixelCoordinates.append([x,y])
答案 4 :(得分:0)
这是仅使用cv2库的解决方案
import cv2
blue = int(input("Enter blue value: "))
green = int(input("Enter green value: "))
red = int(input("Enter red value: "))
path = str(input("Enter image path with image extension:"))
img = cv2.imread(path)
img= cv2.resize(img,(150,150))
x,y,z = img.shape
for i in range(x):
for j in range(y):
if img[i,j,0]==blue & img[i,j,1]==green & img[i,j,1]==red:
print("Found color at ",i,j)