PyCosmed数字识别程序回顾与优化。
图像预处理
首先要将截取的图片转为灰度图像,然后绘制灰度直方图,确定二值化阈值150
,然后进行二值化:
# 获取图像
def get_img(index):
img = Image.open("E:\\Python\\PyCosmed\\v3.0\DIGIT2\\"+str(index)+".png")
plt.subplot(221)
plt.imshow(img)
return img
# 分析灰度直方图,从而选择合适的二值化阈值
def gray_hist(img):
img_arr = np.array(img.convert('L')) # convert - 转换图像格式 L - 八位黑白像素
# array - image格式转为array数组
plt.subplot(223)
plt.imshow(img_arr)
img_arr = img_arr.flatten() # flatten - 转化为一维数组
plt.subplot(222)
plt.hist(img_arr,bins=256) # hist - 绘制直方图 bins - 条形数
plt.ylim((0,50))
# 图像二值化
def binarize(img, threshold=threshold):
"""二值化"""
img = img.convert('L')
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
bin_img = img.point(table, '1')
plt.subplot(222)
plt.imshow(bin_img)
return bin_img
图像分割
加入分割宽度机制,避免数字相连情况:
分割后的图像集:
def vertical_cut(img):
"""纵向切割"""
px = list(np.sum(np.a