OpenCV MSER检测文本区域 - Python

时间:2016-10-17 04:43:28

标签: python opencv image-processing ocr

我有发票图片,我想检测上面的文字。所以我计划使用两个步骤:首先是识别文本区域,然后使用OCR识别文本。

我在python中使用OpenCV 3.0。我能够识别文本(包括一些非文本区域),但我还想从图像中识别文本框(也不包括非文本区域)。

我的输入图片为:Original,输出为:Processed 我正在使用以下代码:

img = cv2.imread('/home/mis/Text_Recognition/bill.jpg')
mser = cv2.MSER_create()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Converting to GrayScale
gray_img = img.copy()

regions = mser.detectRegions(gray, None)
hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]
cv2.polylines(gray_img, hulls, 1, (0, 0, 255), 2)
cv2.imwrite('/home/mis/Text_Recognition/amit.jpg', gray_img) #Saving

现在,我想识别文本框,并删除/取消识别发票上的任何非文本区域。我是OpenCV的新手,也是Python的初学者。我可以在MATAB exampleC++ example中找到一些示例,但如果我将它们转换为python,则需要花费很多时间。

是否有任何使用OpenCV的python示例,或者任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:11)

以下是代码 导入包

import cv2
import numpy as np

#Create MSER object
mser = cv2.MSER_create()

#Your image path i-e receipt path
img = cv2.imread('/home/rafiullah/PycharmProjects/python-ocr-master/receipts/73.jpg')

#Convert to gray scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

vis = img.copy()

#detect regions in gray scale image
regions, _ = mser.detectRegions(gray)

hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]

cv2.polylines(vis, hulls, 1, (0, 255, 0))

cv2.imshow('img', vis)

cv2.waitKey(0)

mask = np.zeros((img.shape[0], img.shape[1], 1), dtype=np.uint8)

for contour in hulls:

    cv2.drawContours(mask, [contour], -1, (255, 255, 255), -1)

#this is used to find only text regions, remaining are ignored
text_only = cv2.bitwise_and(img, img, mask=mask)

cv2.imshow("text only", text_only)

cv2.waitKey(0)

答案 1 :(得分:0)

这是一篇过时的文章,但是我想提供一点,如果您尝试从图像中提取所有文本,下面是将这些文本存储在数组中的代码。

import cv2
import numpy as np
import re
import pytesseract
from pytesseract import image_to_string
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
from PIL import Image

image_obj = Image.open("screenshot.png")

rgb = cv2.imread('screenshot.png')
small = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)

#threshold the image
_, bw = cv2.threshold(small, 0.0, 255.0, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)

# get horizontal mask of large size since text are horizontal components
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 1))
connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel)

# find all the contours
contours, hierarchy,=cv2.findContours(connected.copy(),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
#Segment the text lines
counter=0
array_of_texts=[]
for idx in range(len(contours)):
    x, y, w, h = cv2.boundingRect(contours[idx])
    cropped_image = image_obj.crop((x-10, y, x+w+10, y+h ))
    str_store = re.sub(r'([^\s\w]|_)+', '', image_to_string(cropped_image))
    array_of_texts.append(str_store)
    counter+=1

print(array_of_texts)
相关问题