对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))
白色rgb是(255, 255, 255)
而不是(255, 255, 255, 255)
也可以尝试:
countNonZero(pixel == 255)
(从这里开始:使用OpenCV在Python中计算图像中的黑色像素数(
上面的代码有一些格式问题。因此,我在这里发布了该代码的更正版本。这可能对其他人有帮助。
#***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))