from PIL import Image
import matplotlib.pyplot as plt
import pytesseract
import cv2
def cv2ToPil(img):
return Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
img = cv2.imread('validateCode.jpeg')
grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(grayImg, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
retImg = cv2.medianBlur(thresh, 3)
grayImg = cv2ToPil(grayImg)
thresh = cv2ToPil(thresh)
retImg = cv2ToPil(retImg[2:-2, 2:-2])
plt.imshow(img)
<matplotlib.image.AxesImage at 0x118e20a90>
plt.imshow(grayImg)
<matplotlib.image.AxesImage at 0x1193c8cc0>
plt.imshow(thresh)
<matplotlib.image.AxesImage at 0x119475978>
plt.imshow(retImg)
<matplotlib.image.AxesImage at 0x1196707f0>
pytesseract.image_to_string(retImg)
'3858'
def recogVerifCode(imgPath):
img = cv2.imread(imgPath)
grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(grayImg, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
retImg = cv2.medianBlur(thresh, 3)
verifcodeImg = retImg[2:-2, 2:-2]
return pytesseract.image_to_string(verifcodeImg, config='--psm 6 --oem 3 -c tessedit_char_whitelist=0123456789')
recogVerifCode('validateCode.jpeg')
'3858'
recogVerifCode('verif_code.jpeg')
'3213'
recogVerifCode('verif_code1.jpeg')
'0465'