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))
答案 0 :(得分:0)
白色rgb是(255, 255, 255)
而不是(255, 255, 255, 255)
也尝试:
countNonZero(pixel == 255)
(从这里开始:count number of black pixels in an image in Python with OpenCV)
答案 1 :(得分:0)
上面的代码存在一些格式问题。因此,我在这里发布该代码的更正版本。对其他人可能会有帮助。
#***convert image to no pixels per shade output
import cv2
import numpy as np
from collections import defaultdict
img = cv2.imread('/Users/monjoysaha/Downloads/generated_images/gen_1.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('/Users/monjoysaha/Downloads/generated_images/gen_1.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))