首页 > 解决方案 > 使用 OPENCV 和 PYTESSERACT 对多项选择题进行排序

问题描述

我正在尝试制作和编写多项选择测验,MCQ 问题来自不同的书籍和其他来源,以便我可以以数字方式回答它们。我没有费心一一打字,因为这很麻烦,而且会消耗很多时间。所以我从书中拍摄了问题的照片,然后将它们输入到我的脚本中,该脚本使用 openCV 进行图像处理,使用 Py-tesseract 将它们转换为文本,并使用 python 模块将其导出到充当“数据库”的 excel 中。问题。

我的问题是我无法将选择排序为相应的字母

这是选择的图像

多项选择

以及按换行符对选择进行排序的代码

choices = cv2.imread("ROI_2.png", 0)
custom_config = r'--oem 3 --psm 6'
c = pytesseract.image_to_string(choices, config=custom_config, lang='eng')

x = re.sub(r'\n{2}', '\n', c)
text = repr(x)
print(text)
newtext = text.split("\\n")

如果选择很短,但在具有多个新行的其他选择中失败,则效果很好

具有多个新行的选项

我试图找到一种方法通过相应的字母有效地对这些选择进行排序,我在想也许分隔符会起作用,或者将新转换的文本组合成一行,或者它可能在图像处理中?我对如何解决我的问题有想法,但我不知道如何继续我仍然是 python 的初学者,并且严重依赖于教程或过去在 stackoverflow 中回答的问题

标签: python-3.xopencvpython-tesseract

解决方案


您的图像似乎没有噪音。所以很容易提取文本。

代码:

    img = cv2.imread("options.png",0)
    img_copy = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
    otsu = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
    custom_oem_psm_config = r'--oem 3 --psm 6'
    ocr = pytesseract.image_to_data(otsu, output_type=Output.DICT,config=custom_oem_psm_config,lang='eng')
    boxes = len(ocr['text'])
    texts = []

    for i in range(boxes):
        if (int(ocr['conf'][i])!=-1):
            (x,y,w,h) = (ocr['left'][i],ocr['top'][i],ocr['width'][i],ocr['height'][i])
            cv2.rectangle(img_copy,(x,y),(x+w,y+h),(255,0,0),2)
            texts.append(ocr['text'][i])

    def list_to_string(list):
        str1 = " "
        return str1.join(list)

    string = list_to_string(texts)
    print("String: ",string)

输出

String:  A. A sound used to indicate when a transmission is complete. B. A sound used to identify the repeater. C. A sound used to indicate that a message is waiting for someone. D. A sound used to activate a receiver in case of severe weather.

但是在这里,我们将所有选项连接在一个字符串中。因此,为了根据选项拆分字符串,我使用了拆分功能。

    a = string.split("A.")
    b = a[1].split("B.")
    c = b[1].split("C.")
    d = c[1].split("D.")

    option_A = b[0]
    option_B = c[0]
    option_C = d[0]
    option_D = d[1]

    print("only options RHS")
    print(option_A)
    print(option_B)
    print(option_C)
    print(option_D)

输出:

only options RHS
 A sound used to indicate when a transmission is complete.
 A sound used to identify the repeater.
 A sound used to indicate that a message is waiting for someone.
 A sound used to activate a receiver in case of severe weather.

你去吧,所有的选择。希望这能解决问题。


推荐阅读