I am trying to segment text images, but I have a problem with one of the images of roi(region of interest) that its dimensions is (24, 3) and (44, 3) and it gives me IndexError: index 26 is out of bounds for axis 0 with size 17 for this particular image. I am using opencv to segment the image using numpy array. How can I solve this?Why is this happening? I have seen similar answers here on SO, but can you explain it to me why and how to correct it? Or give me -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)