使用Python OpenCV检测图像中的所有圆(光学标记识别)
问题描述
我需要为我的高中假期项目做一个OMR检测系统(如果足够可靠,它可能在一定程度上被学校使用),我对它做了相当多的研究,并尝试了从轮廓到模板匹配的一切方法,我觉得模板匹配工作很好,但它只能检测OMR表中许多圆圈中的一个圆圈,有人能帮我弄清楚如何检测OMR表中的多个(所有)圆圈(无论它们是否起泡),OMR表及其各自的坐标,这对我来说就足够了。
我尝试的内容:
import numpy as np
import cv2
img = cv2.resize(cv2.imread('assets/omr_match1.jpg', 0), (0, 0), fx=0.2, fy=0.5)
template = cv2.resize(cv2.imread('assets/circle.jpg', 0), (0, 0), fx=0.2, fy=0.5)
h, w = template.shape
methods = [cv2.TM_CCOEFF, cv2.TM_CCOEFF_NORMED, cv2.TM_CCORR,
cv2.TM_CCORR_NORMED, cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]
methods=methods[0]
# This is one among the above which works perfectly
for method in methods:
img2 = img.copy()
result = cv2.matchTemplate(img2, template, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
location = min_loc
else:
location = max_loc
bottom_right = (location[0] + w, location[1] + h)
cv2.rectangle(img2, location,bottom_right, 0, 1)
cv2.imshow('Match', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
#Circle.jpg
如上所示,只标记了一个随机圆圈,而不是所有圆圈。
解决方案
开始:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('/path/tabela_circle.jpg', 0)
template = cv2.imread('/path/circle.jpg', 0)
h, w = template.shape
res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
cv2.imwrite('res.png',img)
也只检测答案:
相关文章