任何机构都可以解决错误: 我正在尝试对包含数字的ROI进行细分。 该代码适用于某些图像。但是对于其他人则显示以下错误:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-58-1a8d1317985a> in <module>
1 #segment digits from images in Marks folder
----> 2 digits_in_cell("./Cropped/Marks/")
<ipython-input-57-8fe190745c08> in digits_in_cell(cropped_dir_path)
23 cv2.CHAIN_APPROX_SIMPLE)
24
---> 25 cnts = cnts[0] if imutils.is_cv2() else cnts[1]
26
27 orig = cell.copy()
IndexError: list index out of range
这是我的代码:
i=7
cell = cv2.imread(str(i) + '.png')
gray = cv2.cvtColor(cell, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
# threshold the image
ret,thresh1 = cv2.threshold(gray ,112,255,cv2.THRESH_BINARY_INV)
cv2.imshow("Image", thresh1)
cv2.waitKey(0)
# dilate the white portions
dilate = cv2.dilate(thresh1, None, iterations=5)
cv2.imshow("Image", dilate)
cv2.waitKey(0)
# find contours in the image
cnts, hierarchy = cv2.findContours(dilate.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
orig = cell.copy()
#for cnt in cnts:
# Check the area of contour, if it is very small ignore it
#if(cv2.contourArea(cnt) < 100):
# continue
# Filtered countours are detected
x,y,w,h = cv2.boundingRect(cnts)
# Taking ROI of the cotour
roi = cell[y:y+h, x:x+w]
# Mark them on the image if you want
cv2.rectangle(orig,(x,y),(x+w,y+h),(0,255,0),2)
# Save your contours or characters
cv2.imwrite("roi" + str(i) + ".png", roi)
i = i + 1
cv2.imshow("Image", orig)
cv2.waitKey(0)
答案 0 :(得分:0)
行的执行
cnts, hierarchy = cv2.findContours
返回cnts
变量的空列表。这只是意味着该函数没有找到任何轮廓,但是在下一行中,您正在请求第一个轮廓,因此会出现错误。