使用OpenCV提取形状文本的形状

时间:2016-09-08 12:35:01

标签: python opencv

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

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

hand drawn image

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

首先,我将图像灰度化

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)

这就是我之后得到的。

result image

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

我识别文本的原因是我可以通过放置一个边界矩形“boundingRect()”来获取此图像中每个文本的X和Y坐标。

请帮帮我。非常感谢你

1 个答案:

答案 0 :(得分:4)

您可以使用这样一个事实,即字母的连通分量比图表其余部分的大笔划要小得多。

我在代码中使用了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)

enter image description here