首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用OPENCV和PYTESSERACT对多选题进行排序

使用OPENCV和PYTESSERACT对多选题进行排序
EN

Stack Overflow用户
提问于 2020-07-18 10:56:00
回答 1查看 374关注 0票数 0

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

我的问题是,我无法将选项按其对应的字母进行排序

下面是这些选择的图片

Multiple Choices

我的代码按换行符对选项进行排序

代码语言:javascript
复制
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")

如果选项很短,则效果很好,但在包含多个新行的其他选项中会失败

Choices having multiple new lines

我正在尝试找到一种方法来有效地根据相应的字母对这些选项进行排序,我在想,也许去限制器可以工作,或者将新转换的文本合并到一行,或者可能是在图像处理中?我对如何解决我的问题有想法,但我不知道如何继续,我仍然是python的初学者,在stackoverflow中严重依赖教程或过去回答的问题

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-18 19:37:12

您的图像似乎是无噪声的。因此,很容易提取文本。

代码:

代码语言:javascript
复制
    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)

输出

代码语言:javascript
复制
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.

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

代码语言:javascript
复制
    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)

输出:

代码语言:javascript
复制
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.

这就对了,所有的选项。希望这能解决这个问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62964160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档