opencv-OMR -Python-订购问题

时间:2018-08-23 13:16:54

标签: python opencv image-processing computer-vision optical-mark-recognition

我编写了一个脚本,该脚本应获取扫描的图像并检查调查结果。我已经设法识别调查选项框并确定页面上已选中了哪个。

问题:我希望能够确定在索引上已勾选了哪个方框。因此,在下面的示例中,我具有选项1-5,勾选了数字2,但是由于某种原因,我的盒子的顺序在我的列表中混杂了,在控制台输出中,它表明复选框5是工单。我需要此信息来正确地告诉我复选框2处于选中状态,这样我就可以继续存储/分析整个调查的信息

import os
import sys
import cv2

if os.path.isfile(file_path):

    # read the image
    img = cv2.imread(file_path, 1)
    # convert to gray
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # obtain inverse binary image
    _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
    # find contours
    _, contours, hierarchy = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)

    # select contours having a parent contour and append them to a list
    contour_list = []

    for h in hierarchy[0]:
        if h[0] > -1 and h[2] > -1:
            contour_list.append(h[2])

    print str(len(contour_list))+" contours found"

    # copy original image
    img2 = img.copy()

    a = 0
    # calculate the average size of contour and use this rough size for assuming we have a checkbox
    for j, i in enumerate(contour_list):
        a = a + cv2.contourArea(contours[i])
    mean_area = int(a / len(contour_list))

    boxes_found = 0
    options = 0
    answer = 0

    # draw those contours
    for cnt in contour_list:
        # if contour roughly matches our average size
        if (cnt > 0) & (cv2.contourArea(contours[cnt]) > mean_area):
            # print len(contours[cnt])
            options += 1
            answer += 1
            if len(contours[cnt]) > 210:
                # larger contour length signifies a tick
                cv2.drawContours(img2, [contours[cnt]], -1, (0, 255, 0), 2)
                print "option: "+str(options)+" ticked"
                # print str(options) + " options"
                # options = 0
            else:
                cv2.drawContours(img2, [contours[cnt]], -1, (0, 255, 255), 2)

            boxes_found += 1


    cv2.imshow('img2', img2)
    cv2.waitKey(0)

    print "Boxes found: " + str(boxes_found)

else:
    print "no file"

原始图片: enter image description here

当前输出图像: enter image description here

控制台输出:

6 contours found
option: 5 ticked
Boxes found: 5

1 个答案:

答案 0 :(得分:0)

This post表示findContours从图像的底部找到轮廓。因此,在这种情况下,对象从左到右排序,您需要根据它们的x坐标来识别它们。

[contours[cnt]]中的值

cv2.drawContours(img2, [contours[cnt]], -1, (0, 255, 0), 2)

,订单中的头寸应该很容易得出。