【问题标题】:Extracting hand writing text out in shape with OpenCV使用 OpenCV 提取手写文本的形状
【发布时间】:2017-01-16 09:28:36
【问题描述】:

我是 OpenCV Python 的新手,我真的需要一些帮助。

所以我在这里要做的是在下图中提取这些单词。

文字和形状都是手绘的,所以并不完美。我在下面做了一些编码。

首先,我将图像灰度化

img_final = cv2.imread(file_name)
img2gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

然后我使用 THRESH_INV 来显示内容

ret, new_img = cv2.threshold(image_final, 100 , 255, cv2.THRESH_BINARY_INV)

然后,我扩大内容

kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3 , 3)) 
dilated = cv2.dilate(new_img,kernel,iterations = 3)

我放大图像是因为我可以将文本识别为一个簇

之后,我在轮廓周围应用 boundingRect 并在矩形周围绘制

contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours
index = 0
for contour in contours:

    # get rectangle bounding contour
    [x,y,w,h] = cv2.boundingRect(contour)

    #Don't plot small false positives that aren't text
    if w < 10 or h < 10:
        continue

    # draw rectangle around contour on original image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,255),2)

这就是我在那之后得到的。

我只能检测到其中一个文本。我尝试了许多其他方法,但这是我得到的壁橱结果,它不符合要求。

我之所以识别文字,是为了让我可以通过放置一个边界矩形“boundingRect()”来获得这张图片中每个文字的X和Y坐标。

请帮帮我。非常感谢

【问题讨论】:

  • 不能用tesseract对图片做OCR吗?
  • @Kells1986 原因是因为我需要知道每个单词的坐标以用于其他目的。使用围绕已识别单词的 boundingRect(),我将能够获取此图像本身中单词的 X 和 Y 坐标

标签: python opencv


【解决方案1】:

您可以利用字母的连接组件比图表其余部分的大笔划小得多的事实。

我在代码中使用了 opencv3 连接组件,但您可以使用 findContours 执行相同的操作。

代码:

import cv2
import numpy as np

# Params
maxArea = 150
minArea = 10

# Read image
I = cv2.imread('i.jpg')

# Convert to gray
Igray = cv2.cvtColor(I,cv2.COLOR_RGB2GRAY)

# Threshold
ret, Ithresh = cv2.threshold(Igray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

# Keep only small components but not to small
comp = cv2.connectedComponentsWithStats(Ithresh)

labels = comp[1]
labelStats = comp[2]
labelAreas = labelStats[:,4]

for compLabel in range(1,comp[0],1):

    if labelAreas[compLabel] > maxArea or labelAreas[compLabel] < minArea:
        labels[labels==compLabel] = 0

labels[labels>0] =  1

# Do dilation
se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(25,25))
IdilateText = cv2.morphologyEx(labels.astype(np.uint8),cv2.MORPH_DILATE,se)

# Find connected component again
comp = cv2.connectedComponentsWithStats(IdilateText)

# Draw a rectangle around the text
labels = comp[1]
labelStats = comp[2]
#labelAreas = labelStats[:,4]

for compLabel in range(1,comp[0],1):

    cv2.rectangle(I,(labelStats[compLabel,0],labelStats[compLabel,1]),(labelStats[compLabel,0]+labelStats[compLabel,2],labelStats[compLabel,1]+labelStats[compLabel,3]),(0,0,255),2)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-07-06
  • 2020-03-07
  • 2013-05-16
  • 2019-01-13
  • 2019-11-06
  • 1970-01-01
  • 2014-06-23
  • 1970-01-01
相关资源
最近更新 更多