对于干扰线颜色和验证码一致,但是粗细不一致的情况可以使用如下方法去除干扰线

多数情况下都会将彩色图片灰度化, 因此只有黑白色,所以颜色可以不考虑,由于粗细不一致,可以通过判断一个像素附近有多少个相同像素的数量来进行判断该像素是否为干扰

from io import BytesIO
import numpy as np
import cv2
import os
import numpy as np
import copy

import requests
from PIL import Image
import pytesseract

#number为 附近的点数

def del_noise(img,number):
    height = img.shape[0]
    width = img.shape[1]

    img_new = copy.deepcopy(img)
    for i in range(1, height - 1):
        for j in range(1, width - 1):
            point = [[], [], []]
            count = 0
            point[0].append(img[i - 1][j - 1])
            point[0].append(img[i - 1][j])
            point[0].append(img[i - 1][j + 1])
            point[1].append(img[i][j - 1])
            point[1].append(img[i][j])
            point[1].append(img[i][j + 1])
            point[2].append(img[i + 1][j - 1])
            point[2].append(img[i + 1][j])
            point[2].append(img[i + 1][j + 1])
            for k in range(3):
                for z in range(3):
                    if point[k][z] == 0:
                        count += 1
            if count <= number:
                img_new[i, j] = 255
    return img_new

#path 为图片路径
def identification_verification_code(path):
    image = cv2.imread(path)
    # 灰度化
    # print(image.shape)
    grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 二值化
    result = cv2.adaptiveThreshold(grayImage, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 1)
    # 去噪声
    img = del_noise(result, 6)
    img = del_noise(img, 4)
    img = del_noise(img, 3)
    # 加滤波去噪
    # im_temp = cv2.bilateralFilter(src=img, d=15, sigmaColor=130, sigmaSpace=150)
    im_temp = im_temp[1:-1, 1:-1]
    im_temp = cv2.copyMakeBorder(im_temp, 83, 83, 13, 13, cv2.BORDER_CONSTANT, value=[255])
    # cv2.imwrite('./test1/%s.jpg' %(name), im_temp)
    # print("%s %s.jpg"%(i,name))
    text = pytesseract.image_to_string(im_temp, lang="eng"
                                       ,
                                       config="--psm 8 --oem 3 -c tessedit_char_whitelist=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")


    return text.replace(" ", "").replace('\n', '').replace('\r', '')

欢迎提问

更多推荐