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
code
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)
def get_best_lines(potential_points: np.ndarray) -> np.ndarray:
"""
Gets all combinations of lines by all points.
Line y = kx + b.
Returns np.ndarray like [[k1, b1], [k2, b2]].
"""
combinations_points = []
code
Assistant
Ошибка возникает из-за того, что переменная best_lines возвращает список кортежей вида [(k1, b1), (k2, b2)], а в функции plt.plot() ожидается, что x и y будут массивами одинаковой длины.
Чтобы исправить ошибку и вернуть из функции get_best_lines() тип best_lines в виде [[k1, b1], [k2, b2]], вы можете изменить определение функции следующим образом:
python
def get_best_lines(potential_points: np.ndarray) -> list:
"""
Gets all combinations of lines by all points.
Line y = kx + b.
Returns list like [[k1, b1], [k2, b2]].
"""
combinations_points = []
...
best_lines = [[k, b] for k, b in best_equations]
return best_lines
После этого вы можете использовать новую версию функции get_best_lines() в вашем коде:
python
User
Как вернуть np.ndarray, а не list?
Assistant
Для возвращения результатов в виде массива np.ndarray вместо списка можно изменить определение функции get_best_lines() следующим образом:
python
def get_best_lines(potential_points: np.ndarray) -> np.ndarray:
"""
Gets all combinations of lines by all points.
Line y = kx + b.
Returns np.ndarray like [[k1, b1], [k2, b2]].
"""
combinations_points = []
...
best_lines = np.array([[k, b] for k, b in best_equations])
return best_lines
Теперь функция get_best_lines() будет возвращать массив np.ndarray с формой [[k1, b1], [k2, b2]].
После этого вы можете использовать новую версию функции get_best_lines() в вашем коде:
python
best_lines = get_best_lines(potential_points)
print(best_lines)
# Visualization
...
# 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.plot(x, y, color="green")
...
User
Этот алгоритм работает не корректно, прямые находит не верно, прямые не проходят через потенциальные точки, что не так?
Assistant
Изначально предложенный алгоритм для поиска прямых работает на основе всех возможных комбинаций точек, которые являются потенциальными точками линии. Он основан на предположении, что множество точек находится на одной прямой и может быть описано уравнением y = kx + b.
Однако, в реальных изображениях может быть шум и различные факторы, которые могут внести ошибку в результаты. Возможно, что прямые, найденные с использованием этого алгоритма, не проходят через все потенциальные точки из-за шума или наличия других нелинейных примесей.
User
Нет, нужно на numpy реализовать
Assistant
Понимаю, что вы хотите реализовать алгоритм на основе библиотеки numpy. Вот обновленная версия функции get_best_lines() на основе numpy:
python
def get_best_lines(potential_points: np.ndarray) -> np.ndarray:
"""
Finds the best lines that pass through the potential points.
Returns an array of lines represented as [[rho1, theta1], [rho2, theta2], ...].
"""
lines = []
# Iterate through all potential points
for i in range(len(potential_points)):
x1, y1 = potential_points[i]
for j in range(i+1, len(potential_points)):
x2, y2 = potential_points[j]
# Find rho and theta parameters
dx = x2 - x1
dy = y2 - y1
rho = np.sqrt(dx**2 + dy**2)
theta = np.arctan2(dy, dx)
lines.append([rho, theta])
lines = np.array(lines)
return lines
User
Надо также, чтобы учитывал
Погрешность для значений параметров k и b
tolerance_k = 0.1
tolerance_b = 10
tolerance_distance = 2 # tolerance for distance from the line
Assistant
Вернемся к функции get_best_lines(), чтобы добавить учет погрешности (tolerance) для параметров k и b, а также для расстояния от точки до прямой:
python
# Create combinations of points without using itertools.combinations
for i in range(len(potential_points)):
for j in range(i + 1, len(potential_points)):
combinations_points.append((potential_points[i], potential_points[j]))
# Погрешность для значений параметров k и b
tolerance_k = 0.1
tolerance_b = 10
tolerance_distance = 2 # tolerance for distance from the line
# Список для хранения уникальных уравнений прямых
unique_equations = []
# Словарь для хранения количества точек, лежащих на каждой прямой
points_count = {}
# Проходимся по каждой комбинации точек
for combo in combinations_points:
# Координаты первой точки
x1, y1 = combo[0]
# Координаты второй точки
x2, y2 = combo[1]
# Находим уравнение прямой
if x2 - x1 != 0: # Избегаем деления на ноль
k = (y2 - y1) / (x2 - x1)
b = y1 - k * x1
# Проверяем, есть ли уже похожая прямая в списке уникальных уравнений
is_similar = False
for equation in unique_equations:
k_unique, b_unique = equation
# Проверяем погрешности для значений параметров k и b
if abs(k - k_unique) <= tolerance_k and abs(b - b_unique) <= tolerance_b:
is_similar = True
break
# Если это уникальная прямая, добавляем ее в список уникальных уравнений и словарь количества точек
if not is_similar:
equation = (k, b)
unique_equations.append(equation)
points_count[equation] = 0
# Проходимся по каждой точке из potential_points
for point in potential_points:
# Координаты точки
x, y = point
# Проверяем расстояние точки до прямой
for equation in unique_equations:
k, b = equation
# Calculate the distance from the point to the line
distance = abs(k * x - y + b) / ((k ** 2 + 1) ** 0.5)
# Check if the distance is within the tolerance
if distance <= tolerance_distance:
# Увеличиваем счетчик точек для данной прямой
points_count[equation] += 1
# Сортируем словарь количества точек по убыванию количества точек
sorted_points_count = sorted(points_count.items(), key=lambda x: x[1], reverse=True)
# Выбираем три лучшие прямые
best_equations = [equation for equation, count in sorted_points_count[:3]]
# Выводим результаты
print("Лучшие уравнения прямых:")
for equation in best_equations:
k, b = equation
print(f"y = {k}x + {b}")
best_lines = sorted_points_count[:3]
print("Количество точек на каждой из лучших прямых:")
for equation, count in sorted_points_count[:3]:
print(f"Уравнение прямой: {equation}, Количество точек: {count}")
return best_lines
for equation in best_lines:
k, b = equation
x = np.arange(0, image.shape[1])
y = k * x + b
plt.plot(x, y, color="green")
plt.show()
получаю ошибку:
ValueError Traceback (most recent call last)
in <cell line: 180>()
181 k, b = equation
182 x = np.arange(0, image.shape[1])
--> 183 y = k * x + b
184 plt.plot(x, y, color="green")
185 plt.show()
ValueError: operands could not be broadcast together with shapes (2,) (500,)
как best_lines возвращать типа [[k1,b1], [k2, b2]]?
best_lines = get_best_lines(potential_points)
print(best_lines)
# Visualization
...
# 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.plot(x, y, color="green")
...
Для улучшения алгоритма и увеличения точности обнаружения прямых можно воспользоваться более сложными методами, такими как алгоритм Randomized Hough Transform, который ищет голоса линий в пространстве параметров (k, b), и затем выбирает наиболее вероятные прямые.
Вот пример, как можно изменить функцию get_best_lines() с использованием алгоритма Randomized Hough Transform с помощью библиотеки OpenCV:
python
import cv2
def get_best_lines(potential_points: np.ndarray) -> np.ndarray:
"""
Finds the best lines that pass through the potential points.
Returns an array of lines represented as [[rho1, theta1], [rho2, theta2], ...].
"""
lines = cv2.HoughLines(potential_points, rho=1, theta=np.pi / 180, threshold=50)
return lines.squeeze()
Для использования этого алгоритма, сначала необходимо предварительно обработать изображение, чтобы оставить только потенциальные точки, а затем передать их в функцию get_best_lines() для обнаружения прямых:
python
# Preprocess the image to obtain potential points
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
potential_points = np.where(image_gray > 150, 255, 0).astype(np.uint8)
# Find the best lines
best_lines = get_best_lines(potential_points)
print(best_lines)
# Visualization
...
Примечание: Вам может потребоваться настроить параметры функции cv2.HoughLines(), такие как rho, theta и threshold, чтобы получить оптимальный результат для вашего изображения.
Данный алгоритм реализует простой подход, перебирающий все комбинации точек и вычисляющий параметры rho и theta для каждой пары. В результате возвращается массив линий, где каждая линия представлена параметрами rho и theta.
Обратите внимание, что это достаточно простая реализация и может быть менее точной, особенно для сложных изображений. Если вам требуется более точный алгоритм, рекомендуется изучить алгоритм Hough Transform с использованием хеш-таблицы или алгоритм Randomized Hough Transform.
def get_best_lines(potential_points: np.ndarray) -> np.ndarray:
"""
Finds the best lines that pass through the potential points.
Returns an array of lines represented as [[k1, b1], [k2, b2], ...].
"""
lines = []
# Погрешности для значений параметров k и b
tolerance_k = 0.1
tolerance_b = 10
tolerance_distance = 2 # tolerance for distance from the line
# Iterate through all potential points
for i in range(len(potential_points)):
x1, y1 = potential_points[i]
for j in range(i+1, len(potential_points)):
x2, y2 = potential_points[j]
if x2 - x1 != 0: # Избегаем деления на ноль
# Находим параметры k и b
k = (y2 - y1) / (x2 - x1)
b = y1 - k * x1
# Проверяем расстояние точки до прямой
is_similar = False
for line in lines:
k_similar, b_similar = line
# Проверяем погрешности для значений параметров k и b
if abs(k - k_similar) <= tolerance_k and abs(b - b_similar) <= tolerance_b:
is_similar = True
break
# Если это уникальная прямая, добавляем е