我想從影像中計算特定顏色的像素總數,女巫將擁有該特定顏色的所有 Sade,例如藍色,它將檢查所有藍色陰影并回傳藍色像素的總數
輸入了什么,但它檢查藍色而不是藍色陰影
from PIL import Image
im = Image.open('rin_test/Images33.png')
black = 0
red = 0
for pixel in im.getdata():
if pixel == (30,144,255): # if your image is RGB (if RGBA, (0, 0, 0, 255) or so
blue = 1
print('blue=' str(blue))
藍色的示例影像

uj5u.com熱心網友回復:
您可以使用:
blue = sum(np.all(np.array(im.getdata()) == np.array([30,144,255]), axis=1))
請注意,藍色值更可能為零,因為影像有一個精確的行等于[30,144,255]
uj5u.com熱心網友回復:
如果您想要不同的藍色陰影,則必須指定要添加到變數中的 rgb 值范圍(相當于不同的藍色陰影)
例如 :-
# If you want an array of the shades
blue = []
values = [<shades of blue>]
for pixel in im.getdata():
for value in values:
if pixel == value:
blue.append(value)
print('blue=' str(blue))
# If you just want to add the number of times your shades appear
blue = 0
values = [<shades of blue>]
for pixel in im.getdata():
for value in values:
if pixel == value:
blue = 1
print('blue=' str(blue))
uj5u.com熱心網友回復:
我建議在 Python/OpenCV 的 HSV 顏色空間中使用一系列色調來獲得蒙版。然后計算掩碼中非零值的數量。
輸入:

import cv2
import numpy as np
# load image
img = cv2.imread('blue_bag.png')
# convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)
# create mask for blue color in hsv
# blue is 240 in range 0 to 360, so for opencv it would be 120
lower = (100,100,100)
upper = (160,255,255)
mask = cv2.inRange(hsv, lower, upper)
# count non-zero pixels in mask
count=np.count_nonzero(mask)
print('count:', count)
# save output
cv2.imwrite('blue_bag_mask.png', mask)
# Display various images to see the steps
cv2.imshow('mask',mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
面具:

count: 34231
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/443678.html
標籤:Python 图片 opencv 图像处理 python成像库
上一篇:LNK1104:當boost_python版本為1.72時,無法打開檔案“libboost_python27-vc142-mt-x64-1_71.lib”
