0

I want to split this image into multiple images based on the black lines

enter image description here

I use cv2.HoughLines to get some lines, merging them to avoid overlapping lines. And here my drawing code:

# After get lines from cv2.HoughLines()
for line in lines:

    rho, theta = line
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a * rho
    y0 = b * rho
    x1 = int(x0 + 1000 * (-b))
    y1 = int(y0 + 1000 * (a))
    x2 = int(x0 - 1000 * (-b))
    y2 = int(y0 - 1000 * (a))

    cv2.line(image, (x1, y1), (x2, y2), (0, 200, 0), 2)

cv2.imwrite('results/result.jpg', image)

Here's the result:

enter image description here

I wonder how can I split the images into multiple small images with those green lines

Blurie
  • 148
  • 1
  • 2
  • 13

2 Answers2

1

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.

Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
  • The cv2.HoughLines(...) return only rho and theta, I don't know how to get start_y_coordinate, start_y_coordinate, etc. – Blurie Mar 08 '19 at 08:51
0

See "region of interest"
(Region of Interest opencv python - StackOverflow)

Read this to get x/y:
(Hough Line Transform - Opencv Phyton Tutorials 1 documentation)

busybyte
  • 19
  • 5