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

image = cv2.imread("0.1/01.pgm", cv2.COLORBGR2GRAY) IMAGETHRESHOLD = 100 def…

  1. User

    image = cv2.imread("0.1/01.pgm", cv2.COLOR_BGR2GRAY)

    IMAGE_THRESHOLD = 100

    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)

    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 = 200 ) -> 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 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.5 threshold_b = 20

    while num_lines < 3:
        if num_lines == 0:
            remaining_points = np.copy(potential_points)
        print(f"remaining points: {len(remaining_points)}")
        best_inliers = []
        best_line = None
    
        for i in range(iterations_num):
            if len(remaining_points) < 2:
                break
            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)
            buffer = remaining_points
            remaining_points = np.delete(remaining_points, best_inliers, axis=0)
            if len(remaining_points) < 1:
                remaining_points = np.append(remaining_points, buffer[:len(buffer)//2 + 1])
    
        num_lines += 1
    
    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

    image = cv2.GaussianBlur(image, (25, 25), 0)

    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()

    Нужно как-то улучшить нахождение potential_points на изображении? Есть идеи? Размытие по гауссу подойдет? Реализуй, только так, чтобы с кодом стыковалось нормально

  2. Assistant

    Нахождение potential_points на изображении можно улучшить, например, с помощью использования размытия по Гауссу. Размытие поможет устранить шум и сделать изображение более гладким, что может помочь выделить настоящие точки на изображении.

    Вы можете добавить этот шаг перед процессом выделения potential_points, используя функцию cv2.GaussianBlur. Например, вы можете добавить следующую строку перед вызовом функции get_coords_by_threshold:

    image = cv2.GaussianBlur(image, (25, 25), 0)
    

    Это применит размытие по Гауссу к изображению с ядром 25x25.

    Обратите внимание, что размер ядра размытия (25x25) может потребоваться настроить в зависимости от конкретной задачи и характеристик изображения.

  3. User

    Тогда я получаю такую ошибку

    IndexError Traceback (most recent call last) in <cell line: 189>() 187 neigh_nums = get_neigh_nums_list(coords) 188 --> 189 sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) 190 191 potential_points = get_potential_points_coords(sorted_neigh_nums)

    in sort_neight_nums_by_N(neigh_nums) 53 54 np_neigh_nums = np_neigh_nums[ ---> 55 (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] 56 57 np_neigh_nums = np_neigh_nums[

    IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

  4. Assistant

    Ошибка возникает в функции sort_neight_nums_by_N, потому что np_neigh_nums является одномерным массивом, а вы пытаетесь индексировать его по двум осям.

    Для исправления этой ошибки можно изменить создание np_neigh_nums. Вместо использования np.array(neigh_nums), можно использовать np.array(neigh_nums, dtype=object), чтобы создать одномерный массив объектов, содержащих координаты и значения N.

    Вот исправленный код для функции sort_neight_nums_by_N:

    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, dtype=object)
    
        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
    

    Попробуйте выполнить код с этим исправлением и проверьте, исправляет ли он ошибку.

  5. User

    оибка --------------------------------------------------------------------------- IndexError Traceback (most recent call last) in <cell line: 190>() 188 neigh_nums = get_neigh_nums_list(coords) 189 --> 190 sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) 191 192 potential_points = get_potential_points_coords(sorted_neigh_nums)

    in sort_neight_nums_by_N(neigh_nums) 53 54 np_neigh_nums = np_neigh_nums[ ---> 55 (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] 56 57 np_neigh_nums = np_neigh_nums[

    IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

  6. Assistant

    Извините за предыдущую ошибку. Пропустил ошибку в коде.

    Попробуйте изменить следующую строку кода в функции sort_neight_nums_by_N:

    np_neigh_nums = np_neigh_nums[
        (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)]
    

    на:

    np_neigh_nums = np_neigh_nums[
        (np_neigh_nums[:, 1] != -1) & (np_neigh_nums[:, 1] != 0)]
    

    Полный исправленный код функции sort_neight_nums_by_N будет выглядеть следующим образом:

    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, dtype=object)
    
        np_neigh_nums = np_neigh_nums[
            (np_neigh_nums[:, 1] != -1) & (np_neigh_nums[:, 1] != 0)]
    
        np_neigh_nums = np_neigh_nums[
            np.argsort(-np_neigh_nums[:, 2])]
    
        return np_neigh_nums
    
  7. User

    размытие по Гауссу очень сильно ухудшает алгоритм, есть еще варианты? реализуй

  8. Assistant

    Если размытие по Гауссу ухудшает алгоритм, то можно рассмотреть другие варианты улучшения выделения potential_points на изображении.

    Один из вариантов - это применить морфологическую операцию, такую как расширение или сужение, для удаления шума и улучшения контуров объектов на изображении. Вы можете использовать функции cv2.dilate или cv2.erode для этого. Например, чтобы применить сужение (erosion), вы можете добавить следующий код перед вызовом функции get_coords_by_threshold:

    kernel = np.ones((5, 5), np.uint8)  # Размер ядра может быть настроен
    image = cv2.erode(image, kernel, iterations=1)
    

    Этот код применяет сужение с использованием квадратного ядра размером 5x5.

    Другой вариант - это использовать адаптивный пороговый метод для бинаризации изображения. Этот метод позволяет автоматически настраивать пороговое значение в зависимости от локальных характеристик изображения. Вы можете использовать функцию cv2.adaptiveThreshold для этого. Например, чтобы применить адаптивную бинаризацию, вы можете добавить следующий код перед вызовом функции get_coords_by_threshold:

    image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
    

    Этот код применяет адаптивную бинаризацию с использованием метода ADAPTIVE_THRESH_MEAN_C и размером блока 11x11.

    Пробуйте эти варианты и настраивайте параметры в соответствии с требованиями вашей задачи и характеристиками изображения.