opencv-IndexError:索引26在尺寸为17的轴0的范围之外

时间:2018-12-07 13:26:55

标签: python opencv text-segmentation

我正在尝试分割文本图像,但是roi(感兴趣区域)的图像之一的尺寸为(24,3)并且存在问题 (44,3),它会给我 IndexError:此特定图像的索引26超出了轴0的大小17的范围。我正在使用opencv使用numpy数组分割图像。我该怎么解决?为什么会这样?我在SO上看到了类似的答案,但是您可以向我解释为什么以及如何纠正它吗?或者给我-4。

import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
#import image
image = cv2.imread('wonde_1.png')
#cv2.imshow('orig',image)
#cv2.waitKey(0)

#grayscale
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.imshow('gray',gray)
cv2.waitKey(0)

#binary
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)
cv2.imshow('second',thresh)
cv2.waitKey(0)

#dilation
kernel = np.ones((5,5), np.uint8)
img_dilation = cv2.dilate(thresh, kernel, iterations=1)
cv2.imshow('dilated',img_dilation)
cv2.waitKey(0)

#find contours
im2,ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

#sort contours
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])

for i, ctr in enumerate(sorted_ctrs):
    # Get bounding box
    x, y, w, h = cv2.boundingRect(ctr)

    # Getting ROI
    roi = image[y:y+h, x:x+w]

    # show ROI
    #cv2.imshow('segment no:'+str(i),roi)
    filename='crop/file_%i.png'%i
    print(roi[26].shape)
    #cv2.imwrite(filename,roi[i])


    #am_char=input()
    #cv2.rectangle(image,(x,y),( x + w, y + h ),(90,0,255),2)
    cv2.waitKey(0)

cv2.imshow('marked areas',image)
cv2.waitKey(0)

1 个答案:

答案 0 :(得分:0)

我不需要roi [i],因为roi是可迭代的本身,所以roi就足够了。