Untitled conversation
- User
[[x1, y1, N1], [x2, y2, N2]] есть список такой структуры, нужно преобразовать его к numpy, а затем убрать оттуда все N=-1, N=0, и отсортировать его в порядке убывания N
- Assistant
Для преобразования списка к массиву numpy можно воспользоваться функцией
numpy.array()следующим образом:import numpy as np data = [[x1, y1, N1], [x2, y2, N2]] arr = np.array(data)Чтобы удалить все значения
Nравные -1 и 0, можно воспользоваться индексацией numpy и условным оператором:arr = arr[(arr[:, 2] != -1) & (arr[:, 2] != 0)]Для сортировки массива по убыванию значения
N, можно воспользоваться функциейnumpy.argsort():arr = arr[np.argsort(-arr[:, 2])]Таким образом, окончательный код будет выглядеть следующим образом:
import numpy as np data = [[x1, y1, N1], [x2, y2, N2]] arr = np.array(data) arr = arr[(arr[:, 2] != -1) & (arr[:, 2] != 0)] arr = arr[np.argsort(-arr[:, 2])]Теперь массив
arrсодержит преобразованный список данных без значенийNравных -1 и 0, отсортированный по убыванию значенияN. - User
Теперь нужно отобрать только те, которые имеют максимальное значение N, но как минимум три таких! То есть 6, 5, 5 тоже можно
- Assistant
Чтобы отобрать только записи с максимальным значением
N, но как минимум три таких, можно воспользоваться следующим кодом:import numpy as np data = [[x1, y1, N1], [x2, y2, N2]] arr = np.array(data) arr = arr[(arr[:, 2] != -1) & (arr[:, 2] != 0)] arr = arr[np.argsort(-arr[:, 2])] max_n = np.max(arr[:, 2]) filtered_arr = arr[arr[:, 2] == max_n] if len(filtered_arr) < 3: filtered_arr = [] print(filtered_arr)Здесь мы используем функцию
np.max()для нахождения максимального значенияNв массивеarr. Затем мы фильтруем массивarrи оставляем только строки, у которых значениеNравно максимальному. Если количество таких строк меньше трех, то мы присваиваемfiltered_arrпустой массив.Затем мы выводим
filtered_arr, который содержит только записи с максимальным значениемN, но как минимум три таких. - User
image = cv2.imread("0.1/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 = 150 ) -> 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
- Assistant
To visualize the potential points on the image using
plt, you can update the code as follows:import cv2 import numpy as np import matplotlib.pyplot as plt image = cv2.imread("0.1/01.pgm", cv2.COLOR_BGR2GRAY) # Rest of the code... # 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(sorted_neigh_nums) # Visualization plt.imshow(image, cmap='gray') plt.scatter(potential_points[:, 1], potential_points[:, 0], color='red', marker='o') plt.show()Here, after getting the
potential_points, we useplt.imshow()to display the grayscale image. Then, we useplt.scatter()to plot red circles at the coordinates of the potential points. Finally, we callplt.show()to show the image with the potential points highlighted.Make sure you have the necessary libraries imported (
cv2,numpy, andmatplotlib.pyplot). Also, adjust the specific filename and path in thecv2.imread()function according to your actual image location. - User
image = cv2.imread("0.2/00.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
- Assistant
- User
Мне нужно искать треугольник, поэтому количество прямых должно быть не более трёх, самые лучшие три прямые
- Assistant
Если вы ищете треугольник и хотите ограничить количество прямых не более трех, то вы можете обновить код следующим образом:
import cv2 import numpy as np import matplotlib.pyplot as plt def ransac(points, num_iterations, threshold): best_lines = [] best_inliers = [] for _ in range(num_iterations): random_idxs = np.random.choice(len(points), 3, replace=False) random_points = points[random_idxs] lines = fit_lines(random_points) inliers = get_inliers(points, lines, threshold) if len(inliers) > len(best_inliers): best_lines = lines best_inliers = inliers return best_lines, best_inliers def fit_lines(points): lines = [] for i in range(2): x = points[:, 0] y = points[:, 1] A = np.vstack([x, np.ones(len(x))]).T b = y m, c = np.linalg.lstsq(A, b, rcond=None)[0] lines.append((m, c)) points = np.roll(points, -1, axis=0) return lines def get_inliers(points, lines, threshold): inliers = [] for line in lines: m, c = line x = points[:, 0] y = points[:, 1] distances = np.abs(y - (m * x + c)) inliers.append(points[distances < threshold]) return inliers # Read image and find potential points image = cv2.imread("0.2/00.pgm", cv2.COLOR_BGR2GRAY) 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(sorted_neigh_nums) # Perform RANSAC to find lines and intersection points lines, inliers = ransac(potential_points, num_iterations=100, threshold=100) # Filter out short lines long_lines = [line for line in lines if abs(line[0]) >= 1 / 100][:3] # Find intersection points intersection_points = [] for i in range(len(long_lines)): m1, c1 = long_lines[i] for j in range(i + 1, len(long_lines)): m2, c2 = long_lines[j] x = (c2 - c1) / (m1 - m2) y = m1 * x + c1 intersection_points.append((x, y)) # Visualization plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="