如何从复杂验证码中提取数字

2024-09-30 08:16:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解析下图的验证码

哦!https://ibb.co/35X723J

我试过使用tessaract

data = br.open(captchaurl).read()
b = bytearray(data)
save = open(filename, 'wb')
save.write(data)
save.close()
ctext= pytesseract.image_to_string(Image.open(filename))

Tags: httpsbrreaddatasaveopenfilename验证码
2条回答

选项1:

我认为使用Pytesseract应该可以解决这个问题。我试用了你的代码,当我输入到pytesseract时,它给出了以下结果:

输入图像:

This is the cropped picture from the URL that you specified

输出:

print(ctext)
 '436359 oS'

我建议你不要把整页的url作为pytesseract的输入。取而代之的是,将确切的图像url设为“https://i.ibb.co/RGn9fF5/Jpeg-Image-CS2.jpg”,它将只接收图像。你知道吗

对于输出中额外的“oS”字符,您可以执行字符串操作来切掉输出中除数字以外的字符。你知道吗

re.sub("[^0-9]", "", ctext)

选项2:

你也可以使用谷歌的OCR来实现这一点,它会给你准确的结果而不会出错。虽然我已经向您展示了它的web界面,但是google有很好的python库,您可以通过python本身来实现这一点。看起来像这样:

enter image description here

这里有一个解决方法。你需要清除一点图像,但你不会得到一个完美的结果。请尝试以下操作:

try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
import cv2

file = 'sample.jpg'

img = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, None, fx=10, fy=10, interpolation=cv2.INTER_LINEAR)
img = cv2.medianBlur(img, 9)
th, img = cv2.threshold(img, 185, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4,8))
img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imwrite("sample2.jpg", img)


file = 'sample2.jpg'
text = pytesseract.image_to_string(file)
print(''.join(x for x in text if x.isdigit()))

相关问题 更多 >

    热门问题