![](/img/trans.png)
[英]How to count number of pixels for specific color from Image Using python
[英]Count the pixels of specific color intensity in an image
我想計算圖像中[150,150,150]
的顏色強度的像素,已經確定了圖像的形狀,並制作了一個循環來逐像素掃描圖像,但是我遇到了這個錯誤,我不知道為什么會這樣出現了。
但我收到以下錯誤:
File "D:/My work/MASTERS WORK/FUNCTIONS.py", line 78, in <module>
if img[x,y] == [150,150,150]:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
碼:
img = cv2.imread('imj.jpg')
h ,w =img.shape[:2]
m= 0
for y in range(h):
for x in range(w):
if img[x,y] == [150,150,150]:
m+=1
print('No. of points = ' , m)
不應使用for
循環,而應使用Numpy對處理進行向量化。 要計算顏色強度[150,150,150]
的像素數,可以使用np.count_nonzero()
count = np.count_nonzero((image == [150, 150, 150]).all(axis = 2))
這是一個例子。 我們創建尺寸為[400,400]
的黑色圖像,並將左下角的顏色設置為[150,150,150]
import numpy as np
# Create black image
image = np.zeros((400,400,3), dtype=np.uint8)
image[300:400,300:400] = (150,150,150)
然后,我們計算此強度下的像素數
# Count number of pixels of specific color intensity
count = np.count_nonzero((image == [150, 150, 150]).all(axis = 2))
print(count)
10000
最后,如果要更改該強度的像素,我們可以找到所有所需的像素並使用蒙版。 在這種情況下,我們將像素變為綠色
# Find pixels of desired color intensity and draw onto mask
mask = (image == [150.,150.,150.]).all(axis=2)
# Apply the mask to change the pixels
image[mask] = [36,255,12]
完整代碼
import numpy as np
# Create black image
image = np.zeros((400,400,3), dtype=np.uint8)
image[300:400,300:400] = (150,150,150)
# Count number of pixels of specific color intensity
count = np.count_nonzero((image == [150, 150, 150]).all(axis = 2))
print(count)
# Find pixels of desired color intensity and draw onto mask
mask = (image == [150.,150.,150.]).all(axis=2)
# Apply the mask to change the pixels
image[mask] = [36,255,12]
這不是建議的方法來計算具有給定值的像素,但是對於上面的情況( r
, g
和b
相同值),仍然可以使用以下代碼:
for x in range(h):
for y in range(w):
if np.all(img[x, y]==150, axis=-1): # (img[x, y]==150).all(axis=-1)
m+=1
如果要計算r
, g
和b
不同值的像素,請使用np.all(img[x, y]==[b_value, g_value, r_value], axis=-1)
,因為OpenCV
遵循bgr
順序。
或者,您可以使用np.count_nonzero(np.all(img==[b_value, g_value, r_value],axis=-1))
或簡單地使用np.count_nonzero(np.all(img==150, axis=-1))
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.