首页 > 解决方案 > 如何在python中使用opencv识别多行和单词?

问题描述

我是巴西学生,在 pt-stackoverflow 中对此一无所知。我是python和opencv的新手,很难学习。
我正在尝试在 python 中做一个 OCR 程序,它可以通过网络摄像头提供的视频识别多行和单词。

我首先尝试使用静态图像进行测试,并且我已经尝试过使用 opencv 教程中的代码,就像这样,但只返回 1 行或覆盖单词

# single line
    if lines is not None:
        for rho, theta in lines[0]:
            a = np.cos(theta)
            b = np.sin(theta)
            x0 = a * rho
            y0 = b * rho
            x1 = int(x0 + 800 * (-b))
            y1 = int(y0 + 800 * (a))
            x2 = int(x0 - 800 * (-b))
            y2 = int(y0 - 800 * (a))
            cv2.line(cap, (x1, y1), (x2, y2), (0, 0, 255), 2)
        cv2.imshow("windowName", cap)

# -
# demark text with multiple lines
# -

if True:  # HoughLinesP
        lines = cv.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 30, 10)
        a, b, c = lines.shape
        for i in range(a):
            cv.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv.LINE_AA)

    else:  # HoughLines
        lines = cv.HoughLines(dst, 1, math.pi/180.0, 50, np.array([]), 0, 0)
        if lines is not None:
            a, b, c = lines.shape
            for i in range(a):
                rho = lines[i][0][0]
                theta = lines[i][0][1]
                a = math.cos(theta)
                b = math.sin(theta)
                x0, y0 = a*rho, b*rho
                pt1 = (int(x0+1000*(-b)), int(y0+1000*(a)))
                pt2 = (int(x0-1000*(-b)), int(y0-1000*(a)))
                cv.line(cdst, pt1, pt2, (0, 0, 255), 3, cv.LINE_AA)

    cv.imshow("detected lines", cdst)

在代码的第一部分,我将只标记一行,在第二部分有多行,但它们在单词的前面。

![1]: https://i.imgur.com/lZ3oAtx.png "单行" ![2]: https://i.imgur.com/5N0SHQI.png "多行"

我想要多行和一种模式来识别行中的单词,如下图所示。

![3]: https://i.imgur.com/ecmYGN6.png "多行" ![4]: https://i.imgur.com/2GxlGox.png "我的目标"

抱歉发了一大篇文章,但我这里没有人可以帮助我,我两步就放弃了。

额外信息:轮廓代码

sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])

for i, ctr in enumerate(sorted_ctrs):
    x, y, w, h = cv2.boundingRect(ctr)
    roi = image[y:y + h, x:x + w]
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

    if w > 15 and h > 15:
        im = Image.fromarray(roi)
        text = pytesseract.image_to_string(im)
        print text
        voiceEngine.say(text)
        voiceEngine.runAndWait()

标签: pythonopencvocrhoughlinesp

解决方案


推荐阅读