pytesseract的使用 | python识别验证码

目录

    • 1. 安装tesseract
    • 2.安装pytesseract
    • 3. 修改包中部分代码
    • 4.代码网站测试

1. 安装tesseract

详见:
https://blog.csdn.net/lijiamingccc/article/details/119459775

2.安装pytesseract

在pycharm终端下,安装 pytesseract,如图所示

pip install pytesseract

pytesseract的使用 | python识别验证码_第1张图片

3. 修改包中部分代码

pytesseract的使用 | python识别验证码_第2张图片
文件中的这个路径,改成第一步你安装的位置,建议找到之后直接复制
前面加个r,是为了说明这个路径是一段字符串,防止转义

4.代码网站测试

代码:

网址可以自己随便找一个

    res = requests.get(url="x'x'x'x'x")

    with open('image.jpg', 'wb') as fw:
        fw.write(res.content)

    img = cv2.imread("image.jpg")

    # 四周置白色  图片降噪
    def around_white(img):
        w, h, s = img.shape
        for _w in range(w):
            for _h in range(h):
                if (_w <= 5) or (_h <= 5) or (_w >= w-5) or (_h >= h-5):
                    img.itemset((_w, _h, 0), 255)
                    img.itemset((_w, _h, 1), 255)
                    img.itemset((_w, _h, 2), 255)
        return img
	
    img2 = around_white(img)
    ret, img2 = cv2.threshold(img2, 150, 255, cv2.THRESH_BINARY)
	
	 # 前面需要添加一些图像降噪的操作
    code = pytesseract.image_to_string(img2,config="--psm 6 digits")
    code = re.findall('\d+',code)[0]
    print("识别的验证码为:{}".format(code))

效果:
pytesseract的使用 | python识别验证码_第3张图片
识别效果不一定保证每次都正确,但是基本上5次之内都是可以成功的,这里可以写一个循环,直到成功为止。

你可能感兴趣的:(爬虫,python,爬虫,图像识别)