from matplotlib import pyplot as plt import numpy as np import math import cv2…
- User
from matplotlib import pyplot as plt import numpy as np import math import cv2
potential_points_num = 200 image_threshold = 100
def hough_line(edge): theta = np.arange(0, 180, 1) cos = np.cos(np.deg2rad(theta)) sin = np.sin(np.deg2rad(theta))
coderho_range = round(math.sqrt(edge.shape[0]**2 + edge.shape[1]**2)) accumulator = np.zeros((2 * rho_range, len(theta)), dtype=np.uint8) edge_pixels = np.where(edge == 255) coordinates = list(zip(edge_pixels[0], edge_pixels[1])) for p in range(len(coordinates)): for t in range(len(theta)): rho = int(round(coordinates[p][1] * cos[t] + coordinates[p][0] * sin[t])) accumulator[rho, t] += 2 return accumulatordef get_coords_by_threshold( image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > image_threshold) return coords
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
codefor 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_numsdef sort_neigh_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)
codenp_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_numsdef get_potential_points_coords( sorted_niegh_nums: np.ndarray ) -> 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]
- Assistant
import matplotlib.pyplot as plt import numpy as np import cv2
def draw_lines(image, lines): for rho, theta in lines: a = np.cos(theta) b = np.sin(theta) x0 = arho y0 = brho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
def detect_triangle(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize=3) lines = cv2.HoughLines(edges, 1, np.pi/180, 100)
codeif lines is not None: lines = lines[:, 0, :] draw_lines(image, lines[:3]) return imageimage = cv2.imread("0.0/00.pgm") result = detect_triangle(image)
plt.imshow(result) plt.show()
- User
где табуляция?!
- Assistant
Приношу извинения за отстутствие табуляции в предоставленном коде. Вот исправленный код с правильным форматированием:
pythonimport matplotlib.pyplot as plt import numpy as np import cv2 def draw_lines(image, lines): for rho, theta in lines: a = np.cos(theta) b = np.sin(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)) cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2) def detect_triangle(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize=3) lines = cv2.HoughLines(edges, 1, np.pi / 180, 100) if lines is not None: lines = lines[:, 0, :] draw_lines(image, lines[:3]) return image image = cv2.imread("0.0/00.pgm") result = detect_triangle(image) plt.imshow(result) plt.show() - User
Надо, чтобы этот код искал ТРИ разные прямые, с отличающимися k, b, а он нашел 7 и все почти одинаковые
- Assistant
При использовании преобразования Хафа для обнаружения прямых на изображении, может возникать проблема с детектированием множества линий, особенно если на изображении есть шум или другие линейные структуры, которые могут быть интерпретированы как прямые.