Using the Hough transform, I am looking for the boundaries of the any rectangle. Then I try to find the coordinates of the corners and draw points, but it turns out something is wrong. I found intersection using numpy.linalg.solve()
import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage.transform import hough_line, hough_line_peaks
image = cv2.imread('/rect_pics/5.png')
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
gray = cv2.GaussianBlur(gray, (3, 3), 0)
cv2.imwrite("gray.png", gray)
edged = cv2.Canny(gray, 0, 10)
cv2.imwrite("edged.png", edged)
using_angles = np.linspace(-np.pi / 2, np.pi / 2, 1800)
halfspace, theta, dist = hough_line(edged, using_angles)
plt.figure(figsize=(15, 10))
plt.title('Hough Accumulator', size=30)
plt.imshow(halfspace, cmap='gray')
plt.savefig('accumulator.png')
angle_list = []
fig, axes = plt.subplots(1, 2, figsize=(20, 8))
ax = axes.ravel()
ax[0].imshow(edged, cmap='gray')
ax[0].set_title('Edged rectangle', size=30)
ax[0].set_axis_off()
ax[1].imshow(edged, cmap='gray')
origin = np.array((0, edged.shape[1]))
lines = []
def find_inter(k1, b1, k2, b2):
A = np.array([[k1, -1], [k2, -1]])
b = np.array(([-b1, -b2]))
x = np.linalg.solve(A, b)
return x[0], x[1]
for _, angle, dist in zip(*hough_line_peaks(halfspace, theta, dist)):
y0, y1 = (dist - origin * np.cos(angle)) / np.sin(angle)
ax[1].plot(origin, (y0, y1), '-r')
lines += [(np.tan(angle), dist)]
print(np.degrees(angle), dist)
inter = []
for i in range(len(lines)):
for j in range(i+1, len(lines)):
print(f"intersection of lines{lines[i]} and {lines[j]}:", end=' ')
x, y = find_inter(lines[i][0], lines[i][1], lines[j][0], lines[j][1])
if abs(x) > 1000 or abs(y) > 1000:
print("NO INTERSECTION")
else:
print(x, y)
inter += [(y, -x)]
ax[1].scatter([i[0] for i in inter], [i[1] for i in inter], color='b')
ax[1].set_xlim(origin)
ax[1].set_ylim((edged.shape[0], 0))
# ax[1].set_axis_off()
ax[1].set_title('Detected rectangle', size=30)
plt.savefig('detection.png')
plt.show()
example of a rectangle with wrong points
Please, help me to find a mistake. I'm confused about it