import cv2
import numpy as np
import matplotlib.pyplot as plt
def rgb2gray(img):
return 0.29*img[:, :, 0]+0.71*img[:,:,1]
def bianrzation(img, th=0.5):
bin= np.copy(img)
bin[img >= th]=1
bin[img < th]=0
return bin
img_L = cv2.imread(r'D:\2021.png')[:,:,[1,0]]
gray = rgb2gray(img_L /255)
bin = bianrzation(gray)
color_white = np.where(img_L == 0)[0].shape[0]
color_black = np.where(img_L == 255)[0].shape[0]
pixel_sum = img_L.shape[0] * img_L.shape[1]
print("黑 像素个数:{} 占比:{}%".format(color_white,color_white/pixel_sum*50))
print("白色像素点个数:{} 占比:{}%".format(color_black,color_black/pixel_sum*50))
plt.subplot(121)
plt.imshow(gray, cmap='gray')
plt.subplot(122)
plt.imshow(bin, cmap='gray')
plt.show()