[英]Find all coordinates of black / grey pixels in image using python
我試圖找到一種方法來讀取任何.png
、 .jpg
或.tiff
,並返回該圖像中所有黑色或灰色像素的坐標。
我正在考慮使用某個閾值灰色,並寫出比該顏色更暗的每個像素的坐標。 但是,我不確定如何管理讀取圖像的方面。 我的目標是讓我的結果是圖像中所有黑色像素的列表,例如:
[x 坐標,y 坐標,黑色]
我已經研究過使用cv.imread
來讀出像素的坐標,但據我所知,它的工作方式與我想要的完全相反——它將坐標作為參數,並返回RGB 值。 有沒有人有使這項工作的提示/方法?
對於任何有類似問題的人,我使用下面的答案解決了這個問題,然后我使用np.ndarray.tolist()
將 numpy-array 變成了一個列表。 此外,由於我只得到了結果的截斷版本,因此我使用了:
import sys
np.set_printoptions(threshold=sys.maxsize)
現在使用索引打印列表中的任何元素都很簡單。
您可以使用np.column_stack()
+ np.where()
。 這個想法是將圖像轉換為灰度,然后找到低於某個閾值的所有像素的坐標。 注意在灰度中,圖像有一個像素值為[0... 255]
的通道
將此輸入圖像與threshold_level = 20
一起使用
我們將低於此閾值水平的所有像素着色為藍色
所有像素坐標都可以使用 np.where() 從掩碼中確定,並使用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]]
使用 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 的回答,感謝您的代碼!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.