使用python查找图像中黑色/灰色像素的所有坐标

时间:2019-10-15 15:38:53

标签: python image numpy opencv image-processing

我试图找到一种方法来读取任何.png.jpg.tiff,并返回该图像中所有黑色或灰色像素的坐标。

我正在考虑具有某种阈值灰色,并写出每个比其暗的像素的坐标。但是,我不确定如何管理读取图像的方面。我的目标是使结果成为图像中所有黑色像素的列表,如下所示:

[x坐标,y坐标,黑色]

我已经研究过使用cv.imread来读取像素的坐标,但是据我所知,它的工作方式与我想要的方式完全相反-将坐标作为参数,并返回RGB值。 有人有做这项工作的技巧/方法吗?

对于有类似问题的任何人,我都使用下面的答案解决了这个问题,然后使用np.ndarray.tolist()将numpy-array变成了一个列表。此外,由于我只得到了结果的截断版本,因此我使用了:

import sys

np.set_printoptions(threshold=sys.maxsize)

现在很容易使用索引打印列表中的任何元素。

2 个答案:

答案 0 :(得分:2)

您可以使用np.column_stack() + np.where()。想法是将图像转换为灰度,然后找到低于特定阈值的所有像素的坐标。请注意,在灰度级下,图像具有一个像素值为[0 ... 255]

的通道

将此输入图像与threshold_level = 20

一起使用

我们将低于此阈值水平的所有像素都涂成蓝色

可以使用np.where()从掩模确定所有像素坐标,并使用(x, y)将其堆叠成np.column_stack()格式。这是低于阈值的所有像素坐标

coords = np.column_stack(np.where(gray < threshold_level))
[[ 88 378]
 [ 89 378]
 [ 90 378]
 ...
 [474 479]
 [474 480]
 [474 481]]

使用threshold_level = 50

[[ 21 375]
 [ 22 375]
 [ 23 376]
 ...
 [474 681]
 [474 682]
 [474 683]]

代码

import cv2
import numpy as np

image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Set threshold level
threshold_level = 50

# Find coordinates of all pixels below threshold
coords = np.column_stack(np.where(gray < threshold_level))

print(coords)

# Create mask of all pixels lower than threshold level
mask = gray < threshold_level

# Color the pixels in the mask
image[mask] = (204, 119, 0)

cv2.imshow('image', image)
cv2.waitKey()

输入图片和threshold_level = 10

[[  59  857]
 [  59  858]
 [  59  859]
 ...
 [1557  859]
 [1557  860]
 [1557  861]]

答案 1 :(得分:0)

使用 PIL 库的版本

import numpy as np
from PIL import Image 

image = Image.open("1.png").convert('L')
pixels = np.asarray(image)

# Set threshold level
threshold_level = 50

# Find coordinates of all pixels below threshold
coords = np.column_stack(np.where(pixels < threshold_level))

基于@nathancy 的回答,感谢您提供代码!