Numpy 不能正确计算图像中的像素
Numpy doesn't count pixels in image correctly
我正在尝试使用 Numpy 和 OpenCV 计算图像中的黑白像素。但是,最终计数与实际值不匹配。通过使用下图 (4x4):
在下面的代码中:
# importing libraries
import cv2
import numpy as np
from math import *
path = "pictures/test.png"
# reading the image data from desired directory
img = cv2.imread(path)
cv2.imshow('Image', img)
height, width, color = img.shape
# counting the number of pixels
number_of_white_pix = np.sum(img == 255)
number_of_black_pix = np.sum(img == 0)
def phase():
white = number_of_white_pix
black = number_of_black_pix
phaseper = white/(white+black)
print(white)
print(black)
return phaseper
print(phase())
我得到以下输出:
9
36
0.2
Process finished with exit code 0
这意味着它统计了9个白色像素和36个黑色像素,这显然是错误的,从图像中可以看出正确的数字是3个白色和13个像素(总共4x4 = 16个像素) .由于代码没有给出任何错误并且似乎没有错误,我不知道发生了什么。
使用 print(img)
转储 original image 的数据得到
[[[ 0 0 0]
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]
[[ 0 0 0]
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]
[[255 255 255]
[255 255 255]
[255 255 255]
[ 0 0 0]]
[[ 1 1 1]
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]]
这与您的代码结果一致:我们有 9 个 255
和 36 个 0
。如您所见,其中一个像素不是很黑,而是非常深的灰色。
每个值出现三次的原因是因为它被编码为RGB。如果您只关心处理灰度图像,您可以告诉 opencv
将图像加载为灰度图像:
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
"""
print(img) now gives
[[ 0 0 0 0]
[ 0 0 0 0]
[255 255 255 0]
[ 1 0 0 0]]
"""
我正在尝试使用 Numpy 和 OpenCV 计算图像中的黑白像素。但是,最终计数与实际值不匹配。通过使用下图 (4x4):
在下面的代码中:
# importing libraries
import cv2
import numpy as np
from math import *
path = "pictures/test.png"
# reading the image data from desired directory
img = cv2.imread(path)
cv2.imshow('Image', img)
height, width, color = img.shape
# counting the number of pixels
number_of_white_pix = np.sum(img == 255)
number_of_black_pix = np.sum(img == 0)
def phase():
white = number_of_white_pix
black = number_of_black_pix
phaseper = white/(white+black)
print(white)
print(black)
return phaseper
print(phase())
我得到以下输出:
9
36
0.2
Process finished with exit code 0
这意味着它统计了9个白色像素和36个黑色像素,这显然是错误的,从图像中可以看出正确的数字是3个白色和13个像素(总共4x4 = 16个像素) .由于代码没有给出任何错误并且似乎没有错误,我不知道发生了什么。
使用 print(img)
转储 original image 的数据得到
[[[ 0 0 0]
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]
[[ 0 0 0]
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]
[[255 255 255]
[255 255 255]
[255 255 255]
[ 0 0 0]]
[[ 1 1 1]
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]]
这与您的代码结果一致:我们有 9 个 255
和 36 个 0
。如您所见,其中一个像素不是很黑,而是非常深的灰色。
每个值出现三次的原因是因为它被编码为RGB。如果您只关心处理灰度图像,您可以告诉 opencv
将图像加载为灰度图像:
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
"""
print(img) now gives
[[ 0 0 0 0]
[ 0 0 0 0]
[255 255 255 0]
[ 1 0 0 0]]
"""