import numpy as np def detectlines(image, threshold): Применение фильтра Собеля для…
- User
import numpy as np
def detect_lines(image, threshold): # Применение фильтра Собеля для обнаружения границ sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) sobel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
gradient_x = convolution(image, sobel_x) gradient_y = convolution(image, sobel_y) # Вычисление амплитуды градиента gradient_magnitude = np.sqrt(np.power(gradient_x, 2) + np.power(gradient_y, 2)) # Бинаризация изображения по порогу binary_image = np.where(gradient_magnitude > threshold, 255, 0) # Применение оператора Хафа для обнаружения линий lines = hough_transform(binary_image) # Фильтрация линий по углу filtered_lines = [] for rho, theta in lines: if np.abs(theta - 90) >= 30: filtered_lines.append((rho, theta)) return filtered_linesdef convolution(image, kernel): return cv2.filter2D(image, -1, kernel)
def hough_transform(image): lines = []
threshold_image = np.where(image > 127, 255, 0) height, width = threshold_image.shape diagonal = np.int(np.ceil(np.sqrt(height ** 2 + width ** 2))) accumulator = np.zeros((2 * diagonal, 180), dtype=np.int) for x in range(height): for y in range(width): if threshold_image[x, y] != 0: for angle in range(0, 180): radian = np.pi/180 * angle rho = int(x * np.cos(radian) + y * np.sin(radian)) accumulator[rho + diagonal, angle] += 1 for rho in range(2 * diagonal): for angle in range(180): if accumulator[rho, angle] > 150: lines.append((rho - diagonal, angle)) return linesЗагрузка изображения
image = cv2.imread("0.1/02.pgm", cv2.COLOR_BGR2GRAY)
Установка порогового значения
threshold = 100
Обнаружение линий на зашумленном изображении
lines = detect_lines(image, threshold)
Визуализация обнаруженных линий
plt.imshow(image, cmap="gray") plt.title("Noisy Image") plt.axis("off")
for rho, theta in lines: a = np.cos(np.deg2rad(theta)) b = np.sin(np.deg2rad(theta)) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000 * (-b)) y1 = int(y0 + 1000 * (a)) x2 = int(x0 - 1000 * (-b)) y2 = int(y0 - 1000 * (a))
plt.plot([x1, x2], [y1, y2], "r")plt.show()
На этот код получаю такое: :39: DeprecationWarning:
np.intis a deprecated alias for the builtinint. To silence this warning, useintby itself. Doing this will not modify any behavior and is safe. When replacingnp.int, you may wish to use e.g.np.int64ornp.int32to specify the precision. If you wish to review your current use, check the release note link for additional information. Deprecated in NumPy 1.20; for more details and guidance: diagonal = np.int(np.ceil(np.sqrt(height ** 2 + width ** 2))) :40: DeprecationWarning: is a deprecated alias for the builtin . To silence this warning, use by itself. Doing this will not modify any behavior and is safe. When replacing , you may wish to use e.g. or to specify the precision. If you wish to review your current use, check the release note link for additional information. Deprecated in NumPy 1.20; for more details and guidance: accumulator = np.zeros((2 * diagonal, 180), dtype=np.int) - Assistant
Чтобы избежать DeprecationWarning, можно использовать
intвместоnp.intпри определении переменнойdiagonalиaccumulator.Для вывода получившихся прямых и их уравнений в консоль, можно использовать следующий код:
equations = [] plt.imshow(image, cmap="gray") plt.title("Noisy Image") plt.axis("off") for rho, theta in lines: a = np.cos(np.deg2rad(theta)) b = np.sin(np.deg2rad(theta)) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000 * (-b)) y1 = int(y0 + 1000 * (a)) x2 = int(x0 - 1000 * (-b)) y2 = int(y0 - 1000 * (a)) plt.plot([x1, x2], [y1, y2], "r") equation = f"y = {-a/b}x + {-rho/b}" equations.append(equation) print(equation) plt.show()Теперь код должен выводить обнаруженные прямые и их уравнения.