from matplotlib import pyplot as plt import numpy as np import math import cv2…
- User
from matplotlib import pyplot as plt import numpy as np import math import cv2
potential_points_num = 200 image_threshold = 100
def hough_line(edge): theta = np.arange(0, 180, 1) cos = np.cos(np.deg2rad(theta)) sin = np.sin(np.deg2rad(theta))
rho_range = round(math.sqrt(edge.shape[0]**2 + edge.shape[1]**2)) accumulator = np.zeros((2 * rho_range, len(theta)), dtype=np.uint8) edge_pixels = np.where(edge == 255) coordinates = list(zip(edge_pixels[0], edge_pixels[1])) for p in range(len(coordinates)): for t in range(len(theta)): rho = int(round(coordinates[p][1] * cos[t] + coordinates[p][0] * sin[t])) accumulator[rho, t] += 2 return accumulatordef get_coords_by_threshold( image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > image_threshold) return coords
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_numsdef sort_neigh_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)
np_neigh_nums = np_neigh_nums[ (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] np_neigh_nums = np_neigh_nums[ np.argsort(-np_neigh_nums[:, 2])] return np_neigh_numsdef get_potential_points_coords( sorted_niegh_nums: np.ndarray ) -> np.ndarray: """ Gets best candidates, potential points coords only. Returns np.ndarray like [[x1, y1], [x2, y2]]. """ sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1) return sorted_neigh_nums[:potential_points_num]
image = cv2.imread("0.0/00.pgm", cv2.COLOR_BGR2GRAY)
my code
coords_by_threshold = get_coords_by_threshold(image) neigh_nums = get_neigh_nums_list(coords_by_threshold) sorted_neigh_nums = sort_neigh_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums)
end my code
Доработай алгоритм с помощью только numpy так, чтобы он находил три самые лучшие прямые.
- Находим самую лучшую прямую, такую, что количество potential_points на ней максимальное
- Удаляем potential_points, которые лежат на лучшей прямой, чтобы не найти её снова
- Повторяем так со второй и третьей прямой, каждый раз проверяя, что k и b у наденных прямых отличаются одновременно на 0.5 и 20 соответственно
- Assistant
import numpy as np
def find_best_line(potential_points): max_count = 0 best_line = None
for i in range(len(potential_points)): for j in range(i+1, len(potential_points)): x1, y1 = potential_points[i] x2, y2 = potential_points[j] # calculate slope and intercept of the line k = (y2 - y1) / (x2 - x1) b = y1 - k * x1 # count the number of points on the line count = 0 for x, y in potential_points: if abs(y - (k * x + b)) < 0.5: count += 1 # update the best line if necessary if count > max_count: max_count = count best_line = (k, b) return best_line - User
Где табуляциЯ?!
- Assistant
Вот исправленный код с табуляцией:
import numpy as np def find_best_line(potential_points): max_count = 0 best_line = None for i in range(len(potential_points)): for j in range(i+1, len(potential_points)): x1, y1 = potential_points[i] x2, y2 = potential_points[j] # calculate slope and intercept of the line k = (y2 - y1) / (x2 - x1) b = y1 - k * x1 # count the number of points on the line count = 0 for x, y in potential_points: if abs(y - (k * x + b)) < 0.5: count += 1 # update the best line if necessary if count > max_count: max_count = count best_line = (k, b) return best_line def remove_points_on_line(potential_points, line): k, b = line remaining_points = [] for x, y in potential_points: if abs(y - (k * x + b)) >= 0.5: remaining_points.append((x, y)) return remaining_points def find_lines(potential_points): lines = [] for _ in range(3): line = find_best_line(potential_points) lines.append(line) potential_points = remove_points_on_line(potential_points, line) return lines def calculate_distance(k1, b1, k2, b2): return abs(k1 - k2) + abs(b1 - b2) / 20 def filter_lines(lines): filtered_lines = [] for i in range(len(lines)): k1, b1 = lines[i] is_unique = True for j in range(i+1, len(lines)): k2, b2 = lines[j] distance = calculate_distance(k1, b1, k2, b2) if distance < 1: is_unique = False break if is_unique: filtered_lines.append(lines[i]) return filtered_lines potential_points = np.array(potential_points) lines = find_lines(potential_points) filtered_lines = filter_lines(lines) print(filtered_lines) - User
from matplotlib import pyplot as plt import numpy as np import math import cv2
potential_points_num = 200 image_threshold = 0
- Assistant
image = cv2.imread("0.0/00.pgm", cv2.COLOR_BGR2GRAY) coords_by_threshold = get_coords_by_threshold(image) neigh_nums = get_neigh_nums_list(coords_by_threshold) sorted_neigh_nums = sort_neigh_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) plt.imshow(image, cmap='gray') plt.scatter(potential_points[:, 1], potential_points[:, 0], color='red', s=5) plt.show()