我正在尝试找到一种方法来读取任何.png
,.jpg
或.tiff
,并返回该图像中所有黑色或灰色像素的坐标。
我正在考虑具有某种阈值灰色,并写出每个比其暗的像素的坐标。但是,我不确定如何管理读取图像的方面。我的目标是使结果成为图像中所有黑色像素的列表,如下所示:
[x坐标,y坐标,黑色]
我已经研究过使用cv.imread
来读取像素的坐标,但是据我所知,它的工作方式与我想要的方式完全相反-它以坐标为参数,并返回RGB值。有人有做这项工作的技巧/方法吗?
对于有类似问题的任何人,我都使用下面的答案解决了这个问题,然后使用将numpy-array变成了一个列表np.ndarray.tolist()
。另外,由于我只得到结果的截断版本,因此我使用了:
import sys
np.set_printoptions(threshold=sys.maxsize)
现在,很容易使用索引打印列表中的任何元素。
您可以使用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]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句