def findlineby2points(points): A = points[0, 1] - points[1, 1] B = points[1, 0] -…
- User
def find_line_by_2_points(points): A = points[0, 1] - points[1, 1] B = points[1, 0] - points[0, 0] C = -(Apoints[0, 0] + Bpoints[0, 1]) line = np.array([A, B, C])/np.hypot(A, B) return line
def find_line_with_ransac(points, threshold, iterations_count): best_line = np.array([1., 1., 0.]) best_loss = 1e100 for iter_num in range(iterations_count): i = np.random.randint(len(points)) j=i while j==i: j = np.random.randint(len(points)) cur_line = find_line_by_2_points(points[[i, j]]) cur_loss = np.sum(distance_to_line_2d(points, cur_line) > threshold) if best_loss > cur_loss: best_loss = cur_loss best_line = cur_line return best_line ransac_line = find_line_with_ransac(points_2d, line_threshold, 1000) plot_2d_points_with_line(points_2d, ransac_line, line_threshold)
Есть вот такая реализация ransac, подредактируй код, чтобы мы детектировали с помощью этого алгоритма 3 прямых с длиной не менее 100, а на вход алгоритму подавалось черно-белое изображение
- Assistant
Для детектирования прямых на черно-белом изображении с помощью данной реализации RANSAC, нам потребуется некоторые изменения в коде. Вот обновленная реализация:
import numpy as np import cv2 def find_line_by_2_points(points): A = points[0, 1] - points[1, 1] B = points[1, 0] - points[0, 0] C = -(A*points[0, 0] + B*points[0, 1]) line = np.array([A, B, C])/np.hypot(A, B) return line def find_line_with_ransac(image, threshold, iterations_count): best_lines = [] best_losses = [] for iter_num in range(iterations_count): rows, cols = image.shape[:2] i = np.random.randint(rows) j = i while j == i: j = np.random.randint(rows) points = np.array([[i, 0], [j, cols-1]]) cur_line = find_line_by_2_points(points) cur_loss = 0 for row in range(rows): for col in range(cols): if image[row, col] > 0: distance = abs(cur_line[0]*row + cur_line[1]*col + cur_line[2]) if distance > threshold: cur_loss += 1 if cur_loss <= threshold: # Добавляем найденную линию и потери в список, только если потери находятся в пределах порога best_lines.append(cur_line) best_losses.append(cur_loss) # Сортируем список линий и потерь по возрастанию потерь sorted_losses = np.argsort(best_losses) best_lines = [best_lines[i] for i in sorted_losses[:3]] return best_lines # Пример использования image = cv2.imread("black_white_image.png", 0) # Путь к черно-белому изображению threshold = 100 iterations_count = 1000 detected_lines = find_line_with_ransac(image, threshold, iterations_count) # Выводим прямые на изображении for line in detected_lines: plot_2d_points_with_line(image, line, threshold)Пожалуйста, обратите внимание, что код использует функции
cv2.imread()иplot_2d_points_with_line(), которые должны быть определены их соответствующими реализациями.