Кто-нибудь может помочь мне решить эту следующую ошибку: «индекс списка вне диапазона»? - PullRequest
0 голосов
/ 06 октября 2019

Может ли тело устранить ошибку: я пытался сегментировать область интереса, которая содержит цифры. Код работал для некоторых изображений. Но для других это показывает следующую ошибку:

---------------------------------------------------------------------------
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)

1 Ответ

0 голосов
/ 06 октября 2019

Выполнение строки

cnts, hierarchy = cv2.findContours

возвращает пустой список для переменной cnts. Это просто означает, что функция не находит никаких контуров, но на следующей строке вы запрашиваете первый из них, отсюда и ошибка.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...