在检测到指定颜色的图像中查找坐标

2024-03-29 05:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图制作一个程序,它接收一幅图像,并在整个图像中寻找一种颜色,比如说蓝色,并给出图像中具有该颜色的点的坐标


Tags: 图像程序颜色蓝色正试图
3条回答

只是注意到马克·塞切尔回答的一个问题。 X和Y坐标以相反的方式返回,因此 X,Y = np.where(np.all(im==blue,axis=2))更改为 Y,X = np.where(np.all(im==blue,axis=2)),这可能只是我遇到的一个小问题

为此,您需要一些信息,包括图像的高度和宽度(以像素为单位),以及图像的颜色贴图。我以前也做过类似的事情,我使用PIL(枕头)提取每个像素的颜色值。使用此方法,您应该能够将像素颜色值重新格式化为二维数组(数组[x][y],其中x为x坐标,y为y坐标,便于比较),并将单个像素值与指定的RGB值进行比较

如果图像的高度和宽度未知,可以执行以下操作以获取图像的高度和宽度:

from PIL import Image

image = Image.open('path/to/file.jpg')
width, height = image.size

在此之后,您可以使用以下命令在列表中获取RGB格式的像素颜色值:

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 = []

然后可以进行比较,以找到与指定颜色匹配的像素

您可以非常简单地使用Numpy来实现这一点,Numpy是Python中大多数图像处理库的基础,例如OpenCV,或skimage,或Wand。在这里,我将使用OpenCVOpenCV,但您同样可以使用上述任何一种或PIL/枕头

使用右侧有一条蓝线的图像:

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
X,Y = np.where(np.all(im==blue,axis=2))

print(X,Y)

输出

[ 0  2  4  6  8 10 12 14 16 18] [80 81 82 83 84 85 86 87 88 89]

或者,如果希望将它们压缩到单个数组中:

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]])

如果您喜欢使用PIL/枕头,它将如下所示:

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)

相关问题 更多 >