1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| import os import cv2 import numpy as np import matplotlib.pyplot as plt
def invert(img): y,x=img.shape left=[[[] right=[[[] for i in range(y): left.append(img[[i,0[]) right.append(img[[i,x-1[]) blackPoints=list(img[[0[]).count(0)+list(img[[y-1[]).count(0)+left.count(0)+right.count(0) blackRate=float(blackPoints/(x[*2+y[*2-4)) if blackRate<0.5: for i in range(y): for j in range(x): img[[i,j[] = 255 - img[[i,j[] return img
path='D:[[[[Desktop[[[[2022[_03[_08[_15[_04[_37[[[[' files=os.listdir(path) for i in range(40): img=cv2.imdecode(np.fromfile(path+files[[i[], dtype=np.uint8),-1)
img=cv2.cvtColor(img,cv2.COLOR[_BGR2GRAY) img=cv2.equalizeHist(img) r,img=cv2.threshold(img,127,255,cv2.THRESH[_BINARY) img=invert(img) plt.subplot(5,8,i+1) plt.imshow(img,cmap='gray') plt.axis('off') plt.savefig('均衡化+二值化+白字[_灰度图.jpg',dpi=800) plt.show()
|