Suppose image
is the variable in which the image is read by opencv as an nd-array.
image = cv2.imread(image_filepath)
Now if lines
is the variable assigned after the houghline transformation like :
lines = cv2.HoughLinesP(...)
Get its's shape :
a,b,c = lines.shape
Initiate a variable to get the coordinates and append the bounding-boxes :
line_coords_list = []
for i in range(a):
line_coords_list.append([(lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3])])
Now, loop through the list of bounding boxes and crop the main image and write them with some filename :
temp_img = image[start_y_coordinate : end_y_coordinate , start_x_coorinate : end_x_coordinate]
temp_name = image_filepath[:-4] + "_"+str(start_y_coordinate )+"_"+str(end_y_coordinate)+ "_" + str(start_x_coorinate) + "_" + str(end_x_coordinate) + ".png"
cv2.imwrite(temp_name, temp_img)
If you are using cv2.HoughLines(...)
, then you probably have to find contours in the image using :
_, blackAndWhite = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY_INV)
_,contours,h = cv2.findContours(blackAndWhite,cv2.RETR_LIST ,cv2.CHAIN_APPROX_SIMPLE)
and, then loop through the contours :
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
line_coords_list.append((x,y,w,h))
Here while finding contours the third and fourth items are width and height respectively. So end_y_coordinate = y+h
and end_x_coordinate = x+w
.