增强OCR图像

时间:2018-03-16 08:34:15

标签: python opencv ocr

[这是示例图片]

我想为OCR裁剪出其他类似彩色图像的标题文本。预处理图像的最有效步骤是什么,以便仅对标题文本进行更好的识别。

2 个答案:

答案 0 :(得分:3)

res

<强>注意

对于想要复制代码并希望在其他项目中使用它的所有人:您将不得不调整和调整它(特别是阈值/内核/迭代值)。 此版本最适合用户提供的图像。

import cv2

image = cv2.imread("image.jpg")
image_c = image.copy()

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # grayscale
cv2.imshow('gray', gray)
cv2.waitKey(0)

_, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)  # threshold
cv2.imshow('thresh', thresh)
cv2.waitKey(0)

kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))

dilated = cv2.dilate(thresh, kernel, iterations=13)  # dilate
cv2.imshow('dilated', dilated)
cv2.waitKey(0)

image, contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)  # get contours

# for each contour found, draw a rectangle around it on original image
for i, contour in enumerate(contours):
    # get rectangle bounding contour
    x, y, w, h = cv2.boundingRect(contour)

    roi = image_c[y:y + h, x:x + w]

    if 50 < h < 100 or 200 < w < 420:  # these values are specific for this example

        # draw rectangle around contour on original image
        rect = cv2.rectangle(image_c, (x, y), (x + w, y + h), (255, 255, 255), 1)
        cv2.imshow('rectangles', rect)
        cv2.waitKey(0)

        cv2.imwrite('extracted{}.png'.format(i), roi)


# write original image with added contours to disk - change values above to (255,0,255) to see clearly the contours
cv2.imwrite("contoured.jpg", image_c)

答案 1 :(得分:0)

可能您可以先尝试检测文本然后从检测到的区域获取最大行索引并将其剪切掉。使用opencv有多种方法可以检测文本。您可以尝试this question here