image = cv2.imread("0.0/01.pgm", cv2.COLORBGR2GRAY) def getcoordsbythreshold(image:…
- User
image = cv2.imread("0.0/01.pgm", cv2.COLOR_BGR2GRAY)
def get_coords_by_threshold(image: np.ndarray, threshold: int = 150) -> 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 = 100 ) -> 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
codefor 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_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)
codenp_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, potential_points_num: int = 30 ) -> 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]
def get_best_lines(potential_points: np.ndarray) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] best_inliers = [] iterations_num = 1000 threshold_distance = 3
code - Assistant
- User
алгоритм почему-то нашел только одну прямую
- Assistant
Причиной того, что алгоритм находит только одну прямую, может быть недостаточное количество точек, которые удовлетворяют условиям фильтрации и выбора лучших прямых.
Чтобы увеличить вероятность обнаружения трех прямых, можно рассмотреть варианты для улучшения алгоритма:
-
Проверьте значения порогов в функции
get_coords_by_thresholdиdelete_pixels_by_min_threshold. Возможно, значения диапазонов интенсивности пикселей должны быть настроены под конкретное изображение. -
Рассмотрите возможность изменения параметров в функции
get_neigh_nums_list. Изменение размера ядра (kernel) может привести к обнаружению большего количества точек. -
Измените параметры в функции
get_best_lines, такие как количество итераций и пороговые значения. Экспериментируйте с этими параметрами, чтобы достичь лучших результатов. -
Если на изображении присутствуют шумы или артефакты, рассмотрите возможность применения фильтрации или предварительной обработки изображения перед применением алгоритма.
-
- User
А если переписать немного алгоритм таким образом: После нахождения лучшей первой прямой, убирать потенциальные точки, которые принадлежат окрестности этой прямой, искать вторую и так далее, так мы сможем задетектировать все три прямые
- Assistant