我一直在尝试检测复选框。虽然我能够检测到图像中的复选框,但我无法检测到复选框是否被选中。如果选中复选框,则复选框以某种颜色为界,如果未选中复选框,则该框以其他颜色为界。
这是我的代码:
import os
import sys
import cv2
file_path = "page1.jpg"
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("contours found: " +str(contour_list))
# 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, 0, 255), 2)
boxes_found += 1
cv2.imshow('img2', img2)
cv2.waitKey(0)
print("Boxes found: " + str(boxes_found))
else:
print("no file")