I’m trying to get the coordinate of every end point on every line, but i couldn’t come up with a solution, this is what I’ve currently got but its finding the outline of the lines not the lines itself
JavaScript
x
35
35
1
import cv2
2
import numpy as np
3
4
img = cv2.imread('out copy.png')
5
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
6
7
kernel_size = 5
8
blur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size),0)
9
10
low_threshold = 50
11
high_threshold = 150
12
edges = cv2.Canny(blur_gray, low_threshold, high_threshold)
13
14
rho = 1 # distance resolution in pixels of the Hough grid
15
theta = np.pi / 180 # angular resolution in radians of the Hough grid
16
threshold = 15 # minimum number of votes (intersections in Hough grid cell)
17
min_line_length = 50 # minimum number of pixels making up a line
18
max_line_gap = 20 # maximum gap in pixels between connectable line segments
19
line_image = np.copy(img) * 0 # creating a blank to draw lines on
20
21
# Run Hough on edge detected image
22
# Output "lines" is an array containing endpoints of detected line segments
23
lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]),
24
min_line_length, max_line_gap)
25
26
for line in lines:
27
for x1,y1,x2,y2 in line:
28
cv2.line(line_image,(x1,y1),(x2,y2),(0,255,0),5)
29
30
lines_edges = cv2.addWeighted(img, 0.8, line_image, 1, 0)
31
32
cv2.imshow('out copy.png', lines_edges)
33
cv2.waitKey(0) ```
34
35
Advertisement
Answer
The hit-or-miss transform can be used to find end points of a line after skeletonization.
Code:
JavaScript
1
7
1
img = cv2.imread('image.png')
2
img2 = img.copy()
3
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
4
5
# inverse binary image, to make the lines in white
6
th = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
7
JavaScript
1
3
1
# obtain binary skeleton
2
sk = cv2.ximgproc.thinning(th, None, 1)
3
JavaScript
1
20
20
1
# kernels to find endpoints in all 4 directions
2
k1 = np.array(([0, 0, 0], [-1, 1, -1], [-1, -1, -1]), dtype="int")
3
k2 = np.array(([0, -1, -1], [0, 1, -1], [0, -1, -1]), dtype="int")
4
k3 = np.array(([-1, -1, 0], [-1, 1, 0], [-1, -1, 0]), dtype="int")
5
k4 = np.array(([-1, -1, -1], [-1, 1, -1], [0, 0, 0]), dtype="int")
6
7
# perform hit-miss transform for every kernel
8
o1 = cv2.morphologyEx(sk, cv2.MORPH_HITMISS, k1)
9
o2 = cv2.morphologyEx(sk, cv2.MORPH_HITMISS, k2)
10
o3 = cv2.morphologyEx(sk, cv2.MORPH_HITMISS, k3)
11
o4 = cv2.morphologyEx(sk, cv2.MORPH_HITMISS, k4)
12
13
# add results of all the above 4
14
out = o1 + o2 + o3 + o4
15
16
# find points in white (255) and draw them on original image
17
pts = np.argwhere(out == 255)
18
for pt in pts:
19
img2 = cv2.circle(img2, (pt[1], pt[0]), 15, (0,255,0), -1)
20