python OCR识别简单验证码

# -*- coding: utf-8 -*- 
# @Time : 2022/9/19 5:02 
# @Author : lck 
# @File : demo_ocr.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

#导入下面三个包
import cv2 as cv
import pytesseract
from PIL import Image


driver = webdriver.Chrome()
driver.maximize_window()
driver.get("http://novel.hctestedu.com/user/register.html")
locator = (By.ID,"chkd")
WebDriverWait(driver,5).until(EC.visibility_of_element_located(locator))
driver.find_element(*locator).screenshot(r"./img/verifyimg.png")

"""-----------------预处理--------------------"""
#文件读取
img_path = r"./img/verifyimg.png"
image = cv.imread(img_path)
#均值迁移法去噪
blurred = cv.pyrMeanShiftFiltering(image,10,100)
#保存文件
blurred_path = r"./img/blurred.png"
cv.imwrite(blurred_path,blurred)
#灰度图
gray = cv.cvtColor(blurred,cv.COLOR_BGR2GRAY)
#保存文件
gray_path = r"./img/gray.png"
cv.imwrite(gray_path,gray)
#二值化处理
t,binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
print(t)
#保存文件
binary_path = r"./img/binary.png"
cv.imwrite(binary_path,binary)

"""-----------------OCR识别--------------------"""

image = Image.open(binary_path)
img_str = pytesseract.image_to_string(image)
print(img_str)

"""
需要安装的包:
(1)CV2
注意:下面这个包,实际安装的是cv2,pycharm自动装是装不了的,必须使用下面命令
pip install opencv-python
(2)pytesseract
pip install pytesseract
(3)需要安装一个软件,并配置环境变量:
安装软件tesseract-ocr

在D盘建立文件夹Tesseract-OCR,于该目录下解压,安装到电脑。
配置环境变量
①右键“此电脑”——设置——高级系统设置——环境变量——系统变量---path---编辑
——新建,写入Tesseract文件的路径,配置环境变量——确定保存
或②win+R,输入“sysdm.cpl”,回车,打开环境变量面板
"""

你可能感兴趣的:(python,opencv,开发语言)