gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:28:55 25 4
gpt4 key购买 nike

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

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

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

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

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

导入系统

np.set_printoptions(threshold=sys.maxsize)

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

最佳答案

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

的 channel

将此输入图像与 threshold_level = 20 一起使用

我们将低于此阈值水平的所有像素着色为蓝色

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

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

关于python - 使用python查找图像中黑色/灰色像素的所有坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58398300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com