OpenCV中的验证码识别
ocr环境搭建没有说明,如读者有兴趣可以单独出一章。
代码实现:
import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
from PIL import Image
import pytesseract as tess
#验证码识别
img = cv2.imread('yzm4.png')
# x,y = img.shape[:2]
# img = cv2.resize(img,(int(2*y),int(2*x)))
cv2.imshow('yzm',img)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,binary = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV|cv2.THRESH_TRIANGLE)
kernel1 = cv2.getStructuringElement(cv2.MORPH_RECT,(6,6))
kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT,(4,4))
open1 = cv2.erode(binary,kernel=kernel1)
open2 = cv2.morphologyEx(open1,cv2.MORPH_OPEN,kernel=kernel2)
cv2.imshow('detect',open2)
cv2.bitwise_not(open2,open2)
textimg = Image.fromarray(open2)
text = tess.image_to_string(textimg)
print("验证码为:%s"%text)
cv2.waitKey()
运行结果: