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

YJJ*_*ool 0 python colors image-processing

我正在尝试制作一个程序,它接收图像并查看整个图像以找到一种颜色,比如说蓝色,然后给出图像中具有该颜色的那个点的坐标。

Mar*_*ell 6

您可以使用 Numpy 非常简单地做到这一点,它是 Python 中大多数图像处理库的基础,例如OpenCVskimageWand。在这里,我将使用OpenCV 来完成,但您可以同样使用上述任何一个或 PIL/Pillow。

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

在此处输入图片说明

#!/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)
Run Code Online (Sandbox Code Playgroud)

输出

[ 0  2  4  6  8 10 12 14 16 18] [80 81 82 83 84 85 86 87 88 89]
Run Code Online (Sandbox Code Playgroud)

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

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]])
Run Code Online (Sandbox Code Playgroud)

如果你更喜欢使用 PIL/Pillow,它会是这样的:

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)
Run Code Online (Sandbox Code Playgroud)