python - 使用 OpenCV 提取手写文本的形状

标签 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 坐标。

请帮帮我。非常感谢

最佳答案

您可以利用这样一个事实:字母的连接部分比图表其余部分的大笔画小得多。

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

关于python - 使用 OpenCV 提取手写文本的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39391080/

相关文章:

python - wxpython 从 ID 访问对象

opencv - 从特征关键点在 OpenCV 中手动进行成对匹配

python - 为什么我的numpy文件比使用同一数组生成的PNG大?

c++ - 如何配置概率占用图人员检测器

java - OpenCV - 安卓 : java. lang.IllegalArgumentException: bmp == null

python - 带有 Python 的 cv2.createTrackbar 控制面板

python - 使用 "cv2.drawMatches"时,出现错误 : "outImg is not a numpy array, neither a scalar"

python - Queryset.create() 方法中的 Django, 'self._for_write' 是什么?

python - 计算 pandas groupby 相同 2 个日期的对象中 2 个日期的差异

python - OpenCV Python GTK错误