OpenCV findcontours() 无法检测轮廓

2024-05-20 21:00:02 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的图片是我试图从中读取MICR E-13B font中的数字。
Recognize numbers
我使用OpenCV中的模板匹配来查找与图像。所以,问题分为3个步骤:
使用enter image description here
第2步:在第2步中,我们从上面获取每个轮廓(包含MICR E-13B字体),以便将它们分开,以便进一步单独断开数字。
第3步:This is where the error occurs.获得上述输出后,现在的任务是将一组数字分解为一位数,以便可以使用OpenCV中的模板匹配进行匹配。但是,当我应用findcontour方法并继续检测每个轮廓的boundRect时,我没有得到任何边界矩形。
以下是各个步骤的代码:
第1步:

# apply a tophat (whitehat) morphological operator to find light
# regions against a dark background
tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel)

# compute the Scharr gradient of the tophat image, then scale
# the rest back into the range [0, 255]
gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0,
    ksize=-1)
gradX = np.absolute(gradX)
(minVal, maxVal) = (np.min(gradX), np.max(gradX))
gradX = (255 * ((gradX - minVal) / (maxVal - minVal)))
gradX = gradX.astype("uint8")

# apply a closing operation using the rectangular kernel to help
# cloes gaps in between credit card number digits, then apply
# Otsu's thresholding method to binarize the image
gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel)
thresh = cv2.threshold(gradX, 0, 255,
    cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

# apply a second closing operation to the binary image, again
# to help close gaps between credit card number regions
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel)

thresh = cv2.dilate(thresh, None, iterations = 3)
clone = np.dstack([thresh.copy()] * 3
# find contours in the thresholded image, then initialize the
# list of digit locations
cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE,
    cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
locs = []

# loop over the contours
for (i, c) in enumerate(cnts):
    (x, y, w, h) = cv2.boundingRect(c)
    if i<=3:   #First 4 images are the MICR font
        cv2.rectangle(clone, (x,y), (x+w, y+h), (255,0,0), 1) #color is set to blue but it shows white (error?)
        locs.append((x, y, w, h))

第2步:

^{pr2}$

错误输出:绿色掩码没有正确绑定矩形。 enter image description here

第3步:

# detect the contours of each individual digit in the group,
# then sort the digit contours from left to right
digitCnts = cv2.findContours(group.copy(), cv2.RETR_TREE,
        cv2.CHAIN_APPROX_SIMPLE)
digitCnts = digitCnts[0] if imutils.is_cv2() else digitCnts[1]
cv2.drawContours(clone, digitCnts, -1, (0,255,0), 1)
cv2.imshow('Image6', clone)
cv2.waitKey()
for c in digitCnts:
    # compute the bounding box of the individual digit, extract
    # the digit, and resize it to have the same fixed size as
    # the reference MICR images
    (x, y, w, h) = cv2.boundingRect(c)
    print (x, y, x+w, y+h)
    cv2.rectangle(clone, (x,y), (x+w, y+h), (255,0,0), 3)
    cv2.imshow('Image7', clone) 
    cv2.waitKey()

错误输出
enter image description here

这就是错误产生的地方,因为它应该将步骤2的输出拆分为单独的数字,如“9”、“5”等等,这些数字可以传递到模板匹配上。但是等高线的长度是11,并且没有由上一步绘制的边界框来表示单独的数字。在


Tags: thetoincloneistophat数字cv2