首页 > 解决方案 > 计算图像中的白色像素

问题描述

对python非常陌生。我使用了指南等中的代码来尝试抓取图像中的白色像素但卡住了。可能超级简单,但我选择白色的 if 语句不是在打球。任何人都可以帮忙吗?

#***convert image to no pixels per shade output
import cv2
import numpy as np
from collections import defaultdict 
img = cv2.imread('..\\Snapshots\\Me.png')
pixels = img.reshape(-1,3)
counts = defaultdict(int)
for pixel in pixels:
if pixel[0] == pixel[1] == pixel[2]:
    counts[pixel[0]] += 1
for pv in sorted(counts.keys()):
print("(%d,%d,%d): %d pixels" % (pv, pv, pv, counts[pv]))



#***count white pixels
from PIL import Image  
im = Image.open('..\\snapshots\\Me.png')
white = 0
other = 0
for pixel in im.getdata():
if pixel == (255, 255, 255, 255): # if your image is RGB (if RGBA, (0, 0,     0, 255) or so
    white += 1
else:
    other += 1
print('white=' + str(white)+', Other='+str(other))

标签: python-3.x

解决方案


白色 rgb(255, 255, 255)不是(255, 255, 255, 255)

也试试:

countNonZero(pixel == 255)  

(从这里:使用 OpenCV 计算 Python 中图像中黑色像素的数量


推荐阅读