您提供的type 1 图像是灰度图像,并非完全黑白图像。然而最后一个阈值输出图像是黑白的。
根据您的问题,我的理解是这两个都应归类为 type 1,而 type 2 图像示例应归类为类型 2。
如果类型 1 始终是黑白的,您可以计算图像中 0 和 1 的数量,并检查它们的总和是否等于图像的总像素数。
这里的一个选项是在不修改图像的情况下对两种类型的图像进行分类,即使用图像直方图的黑白像素百分比。
代码
import cv2
import numpy as np
from matplotlib import pyplot as plt
from skimage import exposure
#img_path = r'hist_imgs/1.png'
#img_path = r'hist_imgs/2.png'
img_path = r'hist_imgs/3.png'
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
cv2.imshow('Image', img)
img_pixel_count = img.shape[0] * img.shape[1]
print(img.shape)
print(img_pixel_count)
h = np.array(exposure.histogram(img, nbins=256))
bw_count = h[0][0] + h[0][255]
other_count = img_pixel_count - bw_count
print('BW PIXEL COUNT: ', bw_count)
print('OTHER PIXEL COUNT: ', other_count)
bw_percentage = (bw_count * 100.0) / img_pixel_count
other_percentage = (other_count * 100.0) / img_pixel_count
print('BW PIXEL PERCENTAGE: ', bw_percentage)
print('OTHER PIXEL PERCENTAGE: ', other_percentage)
differentiate_threshold = 3.0
if other_percentage > differentiate_threshold:
print('TYPE 2: GRAYSCALE')
else:
print('TYPE 1: BLACK AND WHITE')
plt.hist(img.ravel(), 256, [0, 256])
plt.title('Histogram')
plt.show()
输入图像
图片 1:
图 2:
图 3:
代码输出
图片 1:
(154, 74)
11396
BW PIXEL COUNT: 11079
OTHER PIXEL COUNT: 317
BW PIXEL PERCENTAGE: 97.21832221832221
OTHER PIXEL PERCENTAGE: 2.781677781677782
TYPE 1: BLACK AND WHITE
图 2:
(38, 79)
3002
BW PIXEL COUNT: 1543
OTHER PIXEL COUNT: 1459
BW PIXEL PERCENTAGE: 51.39906728847435
OTHER PIXEL PERCENTAGE: 48.60093271152565
TYPE 2: GRAYSCALE
图 3:
(38, 79)
3002
BW PIXEL COUNT: 3002
OTHER PIXEL COUNT: 0
BW PIXEL PERCENTAGE: 100.0
OTHER PIXEL PERCENTAGE: 0.0
TYPE 1: BLACK AND WHITE