Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

image = cv2.imread("0.0/01.pgm", cv2.COLORBGR2GRAY) def getcoordsbythreshold(image:…

  1. 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

    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)

    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_nums
    

    def 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 threshold_k = 0.1 threshold_b = 10

    for i in range(iterations_num):
        sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False)
    
        sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_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_k = abs(coefficients[0] - line[0])
            diff_b = abs(coefficients[0] - line[0])
    
            if diff_k <= threshold_k and diff_b <= threshold_b:
                is_similar = True
                break
    
        if not is_similar and len(inliers) > len(best_inliers):
            best_lines = [coefficients]
            best_inliers = inliers
        elif not is_similar and len(inliers) == len(best_inliers):
            best_lines.append(coefficients)
    
    return np.array(best_lines)
    

    def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: """Calculates the angle in degrees between two lines.""" k1, b1 = line1 k2, b2 = line2 angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2) angle_deg = np.degrees(angle_rad) return angle_deg

    main

    coords = get_coords_by_threshold(image)

    image = delete_pixels_by_min_threshold(image)

    neigh_nums = get_neigh_nums_list(coords)

    sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums)

    potential_points = get_potential_points_coords(sorted_neigh_nums)

    best_lines = get_best_lines(potential_points) print(best_lines)

    Visualization

    plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show()

    Plot the lines on the image

    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 таким образом, чтобы он удалял potential_points, которые лежат на лучшей прямой, чтобы находить следующую, и искал три самых лучших прямых таким образом

  2. Assistant

    Для реализации данного поведения в методе get_best_lines можно воспользоваться следующим подходом:

    1. Создать копию массива potential_points и назвать его, например, remaining_points.
    2. Создать список best_lines и инициализировать его пустым.
    3. Установить переменную num_lines равной 0.
    4. Запустить цикл, который будет выполняться до тех пор, пока num_lines не станет равной 3 или remaining_points не станет пустым:
      • Найти лучшую прямую с использованием текущего состояния remaining_points и добавить ее в best_lines.
      • Удалить из remaining_points точки, которые лежат на этой прямой. Можно использовать функцию np.delete() для удаления соответствующих строк из remaining_points.
      • Увеличить num_lines на 1.
    5. Вернуть массив best_lines.

    Обновленный код метода get_best_lines будет выглядеть следующим образом:

    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 = []
        remaining_points = np.copy(potential_points)
        num_lines = 0
        iterations_num = 1000
        threshold_distance = 3
        threshold_k = 0.1
        threshold_b = 10
    
        while num_lines < 3 and remaining_points.shape[0] > 0:
            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_k = abs(coefficients[0] - line[0])
                    diff_b = abs(coefficients[1] - line[1])
    
                    if diff_k <= threshold_k and diff_b <= threshold_b:
                        is_similar = True
                        break
    
                if not is_similar and len(inliers) > len(best_inliers):
                    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)
    

    Теперь метод get_best_lines будет искать и сохранять только три самых лучших прямых, удаляя точки, которые лежат на каждой из найденных прямых из potential_points.

  3. User

    Алгоритм каждый раз находит разные прямые, а нужно, чтобы находил лучшие

  4. Assistant

    Для того чтобы алгоритм каждый раз находил одни и те же лучшие прямые, можно модифицировать метод get_best_lines следующим образом:

    1. Создать список best_lines и инициализировать его пустым.
    2. Установить переменную num_lines равной 0.
    3. Создать пустой массив remaining_points для хранения точек, которые еще не были использованы.
    4. Запустить цикл, который будет выполняться до тех пор, пока num_lines не станет равной 3:
      • Если num_lines равно 0, то использовать весь массив potential_points как remaining_points.
      • Найти лучшую прямую с использованием текущего состояния remaining_points и добавить ее в best_lines.
      • Удалить из remaining_points все точки, которые лежат на этой прямой. Можно использовать функцию np.delete() для удаления соответствующих строк из remaining_points.
      • Увеличить num_lines на 1.
    5. Вернуть массив best_lines.

    С помощью этой модификации, алгоритм будет находить лучшие прямые, а не произвольные прямые на каждой итерации.

    Обновленный код метода get_best_lines будет выглядеть следующим образом:

    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 = []
        num_lines = 0
        iterations_num = 1000
        threshold_distance = 3
        threshold_k = 0.1
        threshold_b = 10
    
        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_k = abs(coefficients[0] - line[0])
                    diff_b = abs(coefficients[1] - line[1])
    
                    if diff_k <= threshold_k and diff_b <= threshold_b:
                        is_similar = True
                        break
    
                if not is_similar and len(inliers) > len(best_inliers):
                    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)
    

    Теперь метод get_best_lines будет находить и сохранять одни и те же лучшие прямые при каждом вызове.

  5. User

    алгоритм не учитвает угол, используй angle_between_lines(), чтобы угол между каждыми найденными лучшими прямыми был не менее 30 градусов, а если он менее, то нужно продолжать искать

  6. Assistant

    Для того, чтобы алгоритм учитывал угол между найденными лучшими прямыми, можно модифицировать цикл в методе get_best_lines следующим образом:

    1. Создать список best_lines и инициализировать его пустым.
    2. Установить переменную num_lines равной 0.
    3. Создать пустой массив remaining_points для хранения точек, которые еще не были использованы.
    4. Запустить цикл, который будет выполняться до тех пор, пока num_lines не станет равной 3:
      • Если num_lines равно 0, то использовать весь массив potential_points как remaining_points.
      • Найти лучшую прямую с использованием текущего состояния remaining_points и добавить ее в best_lines.
      • Создать флаг angle_satisfied со значением False.
      • Проверить угол между новой найденной прямой и всеми прямыми в best_lines при помощи функции angle_between_lines. Если угол между какой-либо парой прямых меньше 30 градусов, то установить флаг angle_satisfied в True и прервать цикл.
      • Если флаг angle_satisfied равен True, то удалить из remaining_points все точки, которые лежат на новой найденной прямой. Можно использовать функцию np.delete() для удаления соответствующих строк из remaining_points.
      • Иначе, увеличить num_lines на 1.
    5. Вернуть массив best_lines.

    Обновленный код метода get_best_lines с учетом углов будет выглядеть следующим образом:

    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 = []
        num_lines = 0
        iterations_num = 1000
        threshold_distance = 3
        threshold_k = 0.1
        threshold_b = 10
    
        while num_lines < 3:
            if num_lines == 0:
                remaining_points = np.copy(potential_points)
    
            best_inliers = []
            best_line = None
            angle_satisfied = False
    
            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_k = abs(coefficients[0] - line[0])
                    diff_b = abs(coefficients[1] - line[1])
    
                    if diff_k <= threshold_k and diff_b <= threshold_b:
                        is_similar = True
                        break
    
                if not is_similar and len(inliers) > len(best_inliers):
                    best_line = coefficients
                    best_inliers = inliers
    
            if best_line is not None:
                for line in best_lines:
                    angle = angle_between_lines(line, best_line)
                    if angle < 30:
                        angle_satisfied = True
                        break
    
                if angle_satisfied:
                    remaining_points = np.delete(remaining_points, best_inliers, axis=0)
                else:
                    best_lines.append(best_line)
                    num_lines += 1
    
        return np.array(best_lines)
    

    Теперь метод get_best_lines будет находить и сохран