因此,我尝试使用OpenCV扫描此表单,并从本质上为所标记的问题制定密钥。现在,我尝试列举一些在网上找到的示例,并将其转换为二进制图像,但是在检测问题标记时遇到了问题。我通过在线上找到的一本教程做了一些介绍,但是他们使用了另一种格式的表单,该表单上的材料比示例中显示的要多得多,我可以使用更熟悉OpenCV的人的一些意见。帮助不一定是对我的代码甚至是工作代码的改进,它可能是指向更有用的文档,材料或教程的链接和参考。
def analyzeKey(self):
keypix = self.doc.getPagePixmap(0, alpha=False)
keyim = self.pixel2np(keypix)
cv2.imwrite("keyimage.jpg",keyim)
key = cv2.imread("keyimage.jpg")
grayscale = cv2.cvtColor(key, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(grayscale, (5, 5), 0)
edged = cv2.Canny(blurred, 75, 200)
cv2.imshow("Key", edged)
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
docCnt = None
# ensure that at least one contour was found
if len(cnts) > 0:
# sort the contours according to their size in
# descending order
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
# loop over the sorted contours
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# if our approximated contour has four points,
if len(approx) == 4:
docCnt = approx
break
#originalkey = four_point_transform(key, docCnt.reshape(4, 2))
#newkey = four_point_transform(grayscale, docCnt.reshape(4, 2))
keyim[:,:,2] = 0
cv2.imshow("Split",keyim)
thresh = cv2.threshold(grayscale, 0,255,
cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
cv2.imshow("Otsu", thresh)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
questionCnts = []
for cntrs in cnts:
(x, y, w, h) = cv2.boundingRect(c)
ar = w / float(h)
if w>= 20 and h>=20 and ar>=0.9 and ar<=1.1:
questionCnts.append(c)
cv2.imshow("cnts", questionCnts[0])
答案 0 :(得分:2)
要获取铅笔标记的轮廓而不是阈值,可以使用cv2.inRange
来区分灰色/黑色铅笔标记和橙色文本。您可以为允许的颜色选择上下限。在这里,我仅选择黑色作为下限,并选择灰色(180,180,180)作为上限,然后将其应用于您给出的彩色图像。这些值之间的任何像素都在下面显示的输出掩码中指示。
img = cv2.imread('keyimage.jpg')
lower_bound = (0,0,0)
upper_bound = (180,180,180)
mask = cv2.inRange(img, lower_bound, upper_bound)
plt.imshow(mask, cmap='gray')
plt.show()