pic=cv2.resize(img,(96,80),interpolation=cv2.INTER_CUBIC) #改变大小,同截图的比例缩
pic = cv2.cvtColor(pic,cv2.COLOR_BGR2GRAY) #灰度化
for index,i in enumerate(pic): #将图像像素二值化,黑白区分为下面图片分割准备
for indey,j in enumerate(i):
if (j>200):
pic[index][indey] = 0
else:
pic[index][indey] = 240
#以行切割
row_nz = []
for row in pic.tolist():
row_nz.append(len(row) - row.count(0))
upper_y = 0
for i,x in enumerate(row_nz):
if x >= 2: #这里2可以改为其他值
upper_y = i
break
lower_y = 0
for i,x in enumerate(row_nz[::-1]):
if x>=2:
lower_y = len(row_nz) - i
break
sliced_y_img = pic[upper_y:lower_y,:]
#以列切割
col_nz = []
for col in sliced_y_img.T.tolist():
col_nz.append(len(col) - col.count(0))
column_boundary_list = []
record = False
for i,x in enumerate(col_nz[:-1]):
if (col_nz <= 2 and col_nz[i+1] > 2) or col_nz > 2 and col_nz[i+1] <= 2:
column_boundary_list.append(i+1)
#存储分割后的图片
img_list = []
xl = [ column_boundary_list[i:i+2] for i in range(0,len(column_boundary_list),2) ]
print('xl is:',xl)
for x in xl:
img_list.append(sliced_y_img[:,x[0]:x[1]] )
img_list = [ x for x in img_list if x.shape[1] > 5 ]