def get_coords_by_threshold(
image: np.ndarray, threshold: int = IMAGE_THRESHOLD
) -> tuple:
"""Gets pixel coords with intensity more then 'theshold'."""
coords = np.where(image > threshold)
return coords
def delete_pixels_by_min_threshold(
image: np.ndarray, min_threshold: int = IMAGE_THRESHOLD
) -> np.ndarray:
"""Deletes coords from image and returns this image."""
anti_coords = np.where(image < min_threshold)
image[anti_coords] = 0
return image
def get_neigh_nums_list(
coords: tuple, kernel_size: int = 3
) -> list:
"""
Gets list with number of neighborhoods by kernel.
Returns list like [[x1, y1, N1], [x2, y2, N2]],
Where N - neighborhood's number.
"""
neigh_nums = []
offset = (kernel_size - 1) // 2
for x, y in zip(coords[0], coords[1]):
if x < 0 + offset or x > image.shape[0] - offset:
continue
if y < 0 + offset or y > image.shape[1] - offset:
continue
kernel = image[x-offset:x+offset+1, y-offset:y+offset+1]
step_neigh_num = np.count_nonzero(kernel) - 1
neigh_nums.append([x, y, step_neigh_num])
return neigh_nums
def sort_neight_nums_by_N(neigh_nums: list) -> np.ndarray:
"""
Sort neigh_nums by N parameter.
Removes N=-1, N=0 and sorts by N desc.
"""
np_neigh_nums = np.array(neigh_nums)
В этом примере cv2.GaussianBlur() применяет размытие Гаусса к изображению с помощью ядра размером 25x25. Значение 0 в третьем аргументе - это сигма, параметр, который определяет стандартное отклонение гауссовой функции. В данном примере сигма не задана, поэтому используется значение по умолчанию.
for equation in best_lines:
k, b = equation
x = np.arange(0, image.shape[1])
y = k * x + b
plt.imshow(image, cmap="gray")
plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o")
plt.plot(x, y, color="green")
plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o")
plt.show()
Метод get_best_lines не учитывает угла между прямыми, нужно сделать так, чтобы в конечном счете у нас остались только лучшие углы с минимальным углом между ними 30 градусов, а threshold_k тогда можно убрать. Обращаю внимание, что прямых по-прежнему должно вернуться три, то есть, если новая прямая нам не подходит по углу, мы продолжаем искать следующую, пока не найдем подходящую
best_lines = []
num_lines = 0
iterations_num = 1000
threshold_distance = 3
threshold_b = 20
min_angle = 30
while num_lines < 3:
if num_lines == 0:
remaining_points = np.copy(potential_points)
best_inliers = []
best_line = None
for i in range(iterations_num):
sample_indices = np.random.choice(remaining_points.shape[0], size=3, replace=False)
sample_points = remaining_points[sample_indices]
sample_x = sample_points[:, 1]
sample_y = sample_points[:, 0]
coefficients = np.polyfit(sample_x, sample_y, deg=1)
distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1)
inliers = np.where(distances < threshold_distance)[0]
is_similar = False
for line in best_lines:
diff_b = abs(coefficients[1] - line[1])
if diff_b <= threshold_b:
is_similar = True
break
if not is_similar and len(inliers) > len(best_inliers):
angle_check = True
for line in best_lines:
angle = angle_between_lines(coefficients, line)
if angle < min_angle:
angle_check = False
break
if angle_check:
best_line = coefficients
best_inliers = inliers
if best_line is not None:
best_lines.append(best_line)
remaining_points = np.delete(remaining_points, best_inliers, axis=0)
num_lines += 1
return np.array(best_lines)