最近,莫名其妙实验要写机器学习入门——简单图片验证码识别,一头雾水,网上搜了一些资料总算实现了,记录下我的历程叭~
(主要沿用了TensorFlow里面的算法源码)
先说下实验要求吧:
- 1.给了一张图片num01.jpg作为训练样本
- 2.从num02.jpg,num03.jpg中提取单个数字进行识别,并记录识别率
第一步:用OpenCV图像处理
1. 所使用的库:
pip3 install opencv-python
pip3 install numpy
2. 图片处理—对图片进行降噪、二值化处理:
(1)先读入样本图片,转为灰度图
im = cv2.imread(img_file)
im_gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
cv2.imshow('im_gray', im_gray)
cv2.waitKey(0)
(2) 二值化(像素值大于200被置成了0,小于200的被置成了255)
- 这里像素值是如何确定的呢?
鼠标点击即可查看图片中各点的像素,便于在二值化以及接下来的操作中设置阈值。
# 查看灰度值(以200为界)
def mouse_click(event, x, y, flags, para):
if event == cv2.EVENT_LBUTTONDOWN: # 左边鼠标点击
print('PIX:', x, y)
print("BGR:", im[y, x])
print("GRAY:", im_gray[y, x])
if __name__ == '__main__':
# 查看像素值,灰度值
'''
cv2.namedWindow("img")
cv2.setMouseCallback("img", mouse_click)
while True:
cv2.imshow('img', im_inv)
if cv2.waitKey() == ord('q'):
break
cv2.destroyAllWindows()
ret,im_inv = cv2.threshold(im_gray,235,255,cv2.THRESH_BINARY_INV)
cv2.imshow('inv',im_inv)
cv2.waitKey(0)
cv2.destroyAllWindows()
(3)降噪(应用高斯模糊对图片进行降噪),降噪后再一轮二值化
可以看到,降噪后一些颗粒化的噪声变得平滑了
但是事实上我最后测出来降噪后错误率反而比没降噪的高…
kernel = 1/16*np.array([[1,2,1], [2,4,2], [1,2,1]])
im_blur = cv2.filter2D(im_inv,-1,kernel)
ret, im_res = cv2.threshold(im_blur,127,255,cv2.THRESH_BINARY)
3. 切割——opencv最小外接矩阵形函数法
contours, hierarchy = cv2.findContours(im_inv, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(im_inv,contours,-1,(200,200,0),5)
# cv2.imshow("im2", im_inv)
# cv2.waitKey(0)
flag = 1
for cnt in contours:
# 最小外接矩阵
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(im_inv, (x,y), (x+w,y+h), (0,100,