簡體   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