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
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]]. “”” pass
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”)
- Assistant
import numpy as np
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]]. """ # Create all possible combinations of potential points combos = np.array(list(combinations(potential_points, 2)))
# Calculate the k and b parameters for each line k_values = (combos[:, 0, 0] - combos[:, 1, 0]) / (combos[:, 0, 1] - combos[:, 1, 1]) b_values = combos[:, 0, 0] - k_values * combos[:, 0, 1] # Calculate the number of points within 3 pixels of each line num_points = np.zeros(k_values.shape) for i in range(len(k_values)): k = k_values[i] b = b_values[i] distances = np.abs(k * potential_points[:, 1] + b - potential_points[:, 0]) num_points[i] = np.sum(distances <= 3) # Sort the lines by number of points and k value best_lines_indices = np.lexsort((-num_points, k_values)) best_lines = np.column_stack((k_values[best_lines_indices], b_values[best_lines_indices])) # Remove similar lines based on tolerance_k and tolerance_b unique_lines = [] for line in best_lines: if len(unique_lines) == 0: unique_lines.append(line) else: k_diff = np.abs(unique_lines[:, 0] - line[0]) b_diff = np.abs(unique_lines[:, 1] - line[1]) if not np.any((k_diff <= tolerance_k) & (b_diff <= tolerance_b)): unique_lines.append(line) if len(unique_lines) == 3: break return np.array(unique_lines[:3]) - User
Где табуляция?
- Assistant
Используются пробелы вместо табуляции в моем коде. Можно заменить пробелы на табуляцию, если нужно. Вот исправленный код с использованием табуляции:
import numpy as np 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]]. """ # Create all possible combinations of potential points combos = np.array(list(combinations(potential_points, 2))) # Calculate the k and b parameters for each line k_values = (combos[:, 0, 0] - combos[:, 1, 0]) / (combos[:, 0, 1] - combos[:, 1, 1]) b_values = combos[:, 0, 0] - k_values * combos[:, 0, 1] # Calculate the number of points within 3 pixels of each line num_points = np.zeros(k_values.shape) for i in range(len(k_values)): k = k_values[i] b = b_values[i] distances = np.abs(k * potential_points[:, 1] + b - potential_points[:, 0]) num_points[i] = np.sum(distances <= 3) # Sort the lines by number of points and k value best_lines_indices = np.lexsort((-num_points, k_values)) best_lines = np.column_stack((k_values[best_lines_indices], b_values[best_lines_indices])) # Remove similar lines based on tolerance_k and tolerance_b unique_lines = [] for line in best_lines: if len(unique_lines) == 0: unique_lines.append(line) else: k_diff = np.abs(unique_lines[:, 0] - line[0]) b_diff = np.abs(unique_lines[:, 1] - line[1]) if not np.any((k_diff <= tolerance_k) & (b_diff <= tolerance_b)): unique_lines.append(line) if len(unique_lines) == 3: break return np.array(unique_lines[:3]) - User
получаю ошибку --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in <cell line: 126>() 124 potential_points = get_potential_points_coords(sorted_neigh_nums) 125 --> 126 best_lines = get_best_lines(potential_points) 127 print(best_lines) 128
in get_best_lines(potential_points) 103 unique_lines.append(line) 104 else: --> 105 k_diff = np.abs(unique_lines[:, 0] - line[0]) 106 b_diff = np.abs(unique_lines[:, 1] - line[1]) 107 if not np.any((k_diff <= tolerance_k) & (b_diff <= tolerance_b)):
TypeError: list indices must be integers or slices, not tuple
- Assistant
Извините за ошибку. Возникла ошибка, потому что переменная
unique_linesбыла объявлена как список, а не массив numpy. Чтобы исправить это, нужно изменить тип переменнойunique_linesна массив numpy, как показано ниже:import numpy as np 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]]. """ # Create all possible combinations of potential points combos = np.array(list(combinations(potential_points, 2))) # Calculate the k and b parameters for each line k_values = (combos[:, 0, 0] - combos[:, 1, 0]) / (combos[:, 0, 1] - combos[:, 1, 1]) b_values = combos[:, 0, 0] - k_values * combos[:, 0, 1] # Calculate the number of points within 3 pixels of each line num_points = np.zeros(k_values.shape) for i in range(len(k_values)): k = k_values[i] b = b_values[i] distances = np.abs(k * potential_points[:, 1] + b - potential_points[:, 0]) num_points[i] = np.sum(distances <= 3) # Sort the lines by number of points and k value best_lines_indices = np.lexsort((-num_points, k_values)) best_lines = np.column_stack((k_values[best_lines_indices], b_values[best_lines_indices])) # Remove similar lines based on tolerance_k and tolerance_b unique_lines = np.empty((0, 2)) for line in best_lines: if len(unique_lines) == 0: unique_lines = np.vstack((unique_lines, line)) else: k_diff = np.abs(unique_lines[:, 0] - line[0]) b_diff = np.abs(unique_lines[:, 1] - line[1]) if not np.any((k_diff <= tolerance_k) & (b_diff <= tolerance_b)): unique_lines = np.vstack((unique_lines, line)) if len(unique_lines) == 3: break return unique_lines[:3] - User
[[ -inf inf] [ -70.66666667 11815. ] [ -34.6 5022. ]]
Я получил такой ответ, бесконечности быть не может там
- Assistant
Извините за путаницу. Проблема состоит в том, что некоторые значения
kиbимеют бесконечные значения из-за деления на ноль или очень больших или маленьких чисел. Для избежания этого, можно добавить проверку перед делением на ноль и ограничить значения и определенным диапазоном.