繁体   English   中英

无法使用 python tesseract 和 OpenCV 读取图像文本

[英]Unable to read image text with python tesseract and OpenCV

我正在尝试从中读取文本

这个图片

将 Python 与 OpenCV 结合使用。 但是,它无法读取它。

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img=cv.imread(file_path,0)

img = cv.medianBlur(img,5)
ret,th1 = cv.threshold(img,127,255,cv.THRESH_BINARY)

th2 =cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,\
    cv.THRESH_BINARY,11,2)

th3 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\
    cv.THRESH_BINARY,11,2)

titles = ['Original Image', 'Global Thresholding (v = 127)',
    'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']

images = [img, th1, th2, th3]

for i in range(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])

plt.show()

无论如何要这样做?

不是在灰度图像上工作,而是在 HSV 颜色空间的饱和度通道上工作,使后续步骤更容易。

img = cv2.imread(image_path_to_captcha)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
s_component = hsv[:,:,1]

s_component 在此处输入图像描述

接下来,应用适当内核大小和 sigma 值的高斯模糊,以及稍后的阈值。

blur = cv2.GaussianBlur(s_component,(7,7), 7)
ret,th3 = cv2.threshold(blur,127,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

th3 在此处输入图像描述

接下来,在上面的图像中找到轮廓并将高于某个区域阈值的轮廓保留在black图像变量中,稍后将用作掩码。

contours, hierarchy = cv2.findContours(th3, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
black = np.zeros((img.shape[0], img.shape[1]), np.uint8)

for contour in contours:
    if cv2.contourArea(contour) >600 :
        cv2.drawContours(black, [contour], 0, 255, -1)

black 在此处输入图像描述

使用black图像变量作为阈值图像上的掩码

res = cv2.bitwise_and(th3, th3, mask = black)   

res 在此处输入图像描述

最后,对上述结果应用形态细化

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
erode = cv2.erode(res, kernel, iterations=1)

erode 在此处输入图像描述

最终的结果不是你所期望的。 您也可以在绘制轮廓之前尝试不同的形态学操作。

编辑

您可以对上图执行距离变换并使用结果:

dist = cv2.distanceTransform(res, cv2.DIST_L2, 3)
dst = cv2.normalize(dist, dst=None, alpha=0, beta=255,norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

dst 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM