image = cv2.imread("0.0/00.pgm") ImageService.showimage(image) %time import numpy as np…
- User
image = cv2.imread("0.0/00.pgm") ImageService.show_image(image)
%time import numpy as np import matplotlib.pyplot as plt from math import atan2, degrees
def gaussian_filter(image: np.ndarray, sigma: float=1.5) -> np.ndarray: """Returns image with gaussian filter.""" size = int(2 * np.ceil(3 * sigma) + 1)
codekernel = np.fromfunction( lambda x, y: (1 / (2 * np.pi * sigma**2)) * np.exp( -((x - size//2)**2 + (y - size//2)**2) / (2 * sigma**2)), ( size, size)) smoothed_image = np.zeros_like(image) for i in range(image.shape[0]): for j in range(image.shape[1]): neighborhood = image[max(i-size//2, 0):min(i+size//2+1, image.shape[0]), max(j-size//2, 0):min(j+size//2+1, image.shape[1])] smoothed_image[i, j] = np.sum(neighborhood * kernel[:neighborhood.shape[0], :neighborhood.shape[1]]) return smoothed_imagedef sobel_operator(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]]) gradient_x = np.zeros_like(image) gradient_y = np.zeros_like(image) for i in range(image.shape[0] - 2): for j in range(image.shape[1] - 2): neighborhood = image[i:i+3, j:j+3] gradient_x[i+1, j+1] = np.sum(neighborhood * kernel_x) gradient_y[i+1, j+1] = np.sum(neighborhood * kernel_y) edges = np.hypot(gradient_x, gradient_y) return edges
def binary_threshold(image, threshold): binary_image = np.zeros_like(image) binary_image[image > threshold] = 1 return binary_image
def binary_closing(image, iterations=1): closed_image = np.copy(image) for i in range(iterations): dilated_image = np.maximum(closed_image, np.maximum(np.roll(closed_image, 1, axis=0), np.roll(closed_image, -1, axis=0))) dilated_image = np.maximum(dilated_image, np.maximum(np.roll(dilated_image, 1, axis=1), np.roll(dilated_image, -1, axis=1))) closed_image = np.minimum(closed_image, dilated_image) return closed_image
def binary_opening(image, iterations=1): opened_image = np.copy(image) for i in range(iterations): eroded_image = np.minimum(opened_image, np.minimum(np.roll(opened_image, 1, axis=0), np.roll(opened_image, -1, axis=0))) eroded_image = np.minimum(eroded_image, np.minimum(np.roll(eroded_image, 1, axis=1), np.roll(eroded_image, -1, axis=1))) opened_image = np.maximum(opened_image, eroded_image) return opened_image
def probabilistic_hough_line(image, threshold, line_length, line_gap): lines = [] indices = np.argwhere(image > threshold) x_coords, y_coords = indices[:, 1], indices[:, 0] while len(indices) > 0: x1, y1 = x_coords[0], y_coords[0] distances = np.abs((x_coords - x1) + (y_coords - y1) * 1j) line_indices = np.where(distances < line_length)[0] line_x_coords = x_coords[line_indices] line_y_coords = y_coords[line_indices] x2, y2 = line_x_coords[-1], line_y_coords[-1] lines.append([(x1, y1), (x2, y2)]) line_indices = np.where((x_coords >= x1-line_gap) & (x_coords <= x2+line_gap) & (y_coords >= y1-line_gap) & (y_coords <= y2+line_gap))[0] x_coords = np.delete(x_coords, line_indices) y_coords = np.delete(y_coords, line_indices) return np.array(lines)
- Assistant
The error message indicates that there is an issue with the shapes of the operands in the line of code
smoothed_image[i, j] = np.sum(neighborhood * kernel[:neighborhood.shape[0], :neighborhood.shape[1]]).The problem arises because
neighborhoodis a 3-dimensional array with shape (6, 6, 3) whilekernel[:neighborhood.shape[0], :neighborhood.shape[1]]is a 2-dimensional array with shape (6, 6).To fix this, you can modify the code to convert
neighborhoodto grayscale before applying the Gaussian filter. This can be done by taking the mean of the pixel values across the color channels usingnp.mean(neighborhood, axis=2).Here's the modified code:
python - User
ValueError Traceback (most recent call last) in <cell line: 148>() 146 # angles = detect_triangle_angles(image) 147 # print(‘Углы треугольника:’, angles) --> 148 angles = detect_triangle_angles(image) 149 print(f"Corners of 3angle: {angles}")
1 frames in label(image) 93 for i in range(image.shape[0]): 94 for j in range(image.shape[1]): ---> 95 if image[i, j] == 1 and labeled_image[i, j] == 0: 96 stack = [(i, j)] 97 while len(stack) > 0:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Теперь вот такая ошибка
- Assistant
The new error message suggests that there is an issue with the comparison
if image[i, j] == 1 and labeled_image[i, j] == 0.This error occurs because
image[i, j]andlabeled_image[i, j]are arrays and the comparison operator==cannot be applied element-wise to the arrays.To fix this, you can modify the condition to use the
np.all()function, which checks if all elements in the array satisfy the condition.Here's the modified code:
python - User
Даны изображения серых 8-битных изображений размера 500х500 пикселей («серый 8-битный» означает, что значение каждого пикселя – целое число от 0 до 255). На изображениях нарисован треугольник, у которого длина наименьшей стороны больше 100 и величина наименьшего из углов больше 30 градусов. Каждое изображение зашумлено с вероятностью P (от 0 до 0.9), то есть значение каждого), то есть значение каждого пикселя заменяется на случайное целое, равномерно распределенное на отрезке [0; 255]. Требуемый результат Придумать и реализовать алгоритм восстановления координат вершин треугольника по изображению. Ограничение на время работы алгоритма на одно изображение - 1 секунда. Решение будет проверяться на закрытом наборе тестов различной сложности (различные значения параметра P). Для каждого теста будет оцениваться максимальное отклонение по трем вершинам (мера отклонения - евклидово расстояние до правильной позиции вершины). Если максимальное из трех отклонений больше 5, то максимальное отклонение для данного теста полагается равным 5. За итоговую оценку решения будет приниматься среднее максимальное отклонение по всем тестам. Цель: проверка базовых навыков программирования и решения алгоритмических задач, поэтому при решении не предполагается использование дополнительных библиотек (для считывания изображений допускается использование функцию opencv cv2.imread, можно использовать библиотеку numpy для работы с массивами).
- Assistant
Для решения данной задачи восстановления координат вершин треугольника по изображению можно использовать следующий алгоритм:
- Загрузить изображение с помощью функции cv2.imread и преобразовать его в градации серого, если оно еще не в таком формате.
- Применить фильтр для удаления шума, например, гауссовский фильтр.
- Найти границы треугольника на изображении с помощью оператора Собеля или метода Canny.
- Применить пороговую обработку для получения бинарного изображения с границами.
- Применить операцию замыкания (closing) для объединения частей границ треугольника.
- Применить операцию открытия (opening) для сглаживания границ треугольника.
- Найти контуры на бинарном изображении с помощью функции cv2.findContours.