solver.py import numpy as np from cornerdetector.cornerdetector import CornerDetector…
- User
solver.py
import numpy as np
from corner_detector.corner_detector import CornerDetector
class Solver(object): def init(self): self.alg = CornerDetector()
def solve(self, image_gray: np.ndarray) -> np.ndarray: result = self.alg.find_corners(image_gray) return resultcorner_detector.corner_detector.corner_detector.py
import numpy as np
from c_settings import ( ITERATIONS_NUM, IMAGE_THRESHOLD_MIN, IMAGE_THRESHOLD_MAX, NOISE_LESS, POTENTIAL_POINTS_NUM, THRESHOLD_DISTANCE, THRESHOLD_K, THRESHOLD_B, TIME_MAX )
from services.image_service import ImageService from services.time_service import TimeService
class CornerDetector(object): """Class for corner detection on image.""" def init( self, potential_points_num: int = POTENTIAL_POINTS_NUM, iterations_num: int = ITERATIONS_NUM, threshold_distance: int = THRESHOLD_DISTANCE, threshold_k: float = THRESHOLD_K, threshold_b: int = THRESHOLD_B ): self.potential_points_num = potential_points_num self.iterations_num = iterations_num self.threshold_distance = threshold_distance self.threshold_k = threshold_k self.threshold_b = threshold_b self.image = None self.image_threshold = None self.time_service = TimeService(TIME_MAX) self.random_answer = np.array([1, 1], [2, 2], [3, 3])
def __get_coords_by_threshold( self, image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > self.image_threshold) return coords def __get_neigh_nums_list( self, 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 > self.image.shape[0] - offset: continue if y < 0 + offset or y > self.image.shape[1] - offset: continue kernel = self.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 @staticmethod def __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) 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( self, 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[:self.potential_points_num] def __get_best_lines( self, potential_points: np.ndarray ) -> np.ndarray: """ Gets the best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ remaining_points = 0 best_lines = [] num_lines = 0 while num_lines < 3: if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}") best_inlines = [] best_line = None if len(remaining_points) == 0: remaining_points = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) for i in range(self.iterations_num): sample_indices = np.random.choice( remaining_points.shape[0], size=3, replace=False) sample_points = remaining_points[sample_indices] sample_x = sample_points[:, 1] sample_y = sample_points[:, 0] coefficients = np.polyfit(sample_x, sample_y, deg=1) distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inlines = np.where(distances < self.threshold_distance)[0] is_similar = False for line in best_lines: diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[1] - line[1]) if diff_k <= self.threshold_k and diff_b <= self.threshold_b: is_similar = True break if not is_similar and len(inlines) > len(best_inlines): best_line = coefficients best_inlines = inlines if best_line is not None: best_lines.append(best_line) remaining_points = np.delete(remaining_points, best_inlines, axis=0) num_lines += 1 return np.array(best_lines) def find_corners(self, image: np.ndarray) -> np.ndarray: """Finding triangle corners on image process.""" self.time_service.start_time() self.image = image zero_percentage = ImageService.calculate_zero_pixel_percentage(image) if not self.time_service.time_check(): return self.random_answer if zero_percentage > NOISE_LESS: self.image_threshold = IMAGE_THRESHOLD_MIN else: self.image_threshold = IMAGE_THRESHOLD_MAX # Noise i cannot realise. if zero_percentage < 45: return self.random_answer coords = self.__get_coords_by_threshold(image) if not self.time_service.time_check(): return self.random_answer neigh_nums = self.__get_neigh_nums_list(coords) if not self.time_service.time_check(): return self.random_answer sorted_neigh_nums = self.__sort_neigh_nums_by_N(neigh_nums) if not self.time_service.time_check(): return self.random_answer potential_points = self.__get_potential_points_coords(sorted_neigh_nums) if not self.time_service.time_check(): return self.random_answer best_lines = self.__get_best_lines(potential_points) if not self.time_service.time_check(): return self.random_answer intersection_points = np.array([ np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), np.array([-best_lines[0][1], -best_lines[1][1]])), np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[0][1], -best_lines[2][1]])), np.linalg.solve(np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[1][1], -best_lines[2][1]])) ], dtype=np.float32) return intersection_pointsПОЛУЧАЮ ОШИБКУ: solver.py import ERROR: 401 Unauthorized: unsupported operand type(s) for |: 'type' and 'type'; Traceback: File "/3divi/estimators/test_estimator.py", line 42, in estimator; module = load_module_python(_vars.entrypoint); File "/3divi/estimators/est_utils.py", line 19, in load_module_python; abort(401, str(e)); File "/usr/local/lib/python3.9/site-packages/werkzeug/exceptions.py", line 881, in abort; _aborter(status, *args, **kwargs); File "/usr/local/lib/python3.9/site-packages/werkzeug/exceptions.py", line 864, in call; raise self.mapping[code](*args, **kwargs) ЧТО МОЖЕТ БЫТЬ НЕ ТАК?!
- Assistant
Исходя из ошибки, возможно, проблема связана с идентификацией и аутентификацией пользователя. Проверьте, имеете ли вы правильные учетные данные и разрешения для доступа к ресурсам. Убедитесь, что вы правильно настроили доступ к вашему репозиторию или библиотеке, из которой вы пытаетесь импортировать код.
- User
Solver class init ERROR: array() takes from 1 to 2 positional arguments but 3 were given; Traceback: File "/3divi/estimators/test_estimator.py", line 54, in estimator; solver = module.Solver(); File "/tmp/tmpw2r3gode/solver.py", line 8, in init; self.alg = CornerDetector(); File "/tmp/tmpw2r3gode/corner_detector/corner_detector.py", line 37, in init; self.random_answer = np.array([1, 1], [2, 2], [3, 3])
Исправь
- Assistant
Ошибка возникает из-за неправильного создания массива в строке
self.random_answer = np.array([1, 1], [2, 2], [3, 3]). Вместо этого массив должен быть создан с помощью следующего синтаксиса:self.random_answer = np.array([[1, 1], [2, 2], [3, 3]])Исправленный код будет выглядеть так:
## solver.py import numpy as np from corner_detector.corner_detector import CornerDetector class Solver(object): def __init__(self): self.alg = CornerDetector() def solve(self, image_gray: np.ndarray) -> np.ndarray: result = self.alg.find_corners(image_gray) return result ## corner_detector.corner_detector.corner_detector.py import numpy as np from c_settings import ( ITERATIONS_NUM, IMAGE_THRESHOLD_MIN, IMAGE_THRESHOLD_MAX, NOISE_LESS, POTENTIAL_POINTS_NUM, THRESHOLD_DISTANCE, THRESHOLD_K, THRESHOLD_B, TIME_MAX ) from services.image_service import ImageService from services.time_service import TimeService class CornerDetector(object): """Class for corner detection on image.""" def __init__( self, potential_points_num: int = POTENTIAL_POINTS_NUM, iterations_num: int = ITERATIONS_NUM, threshold_distance: int = THRESHOLD_DISTANCE, threshold_k: float = THRESHOLD_K, threshold_b: int = THRESHOLD_B ): self.potential_points_num = potential_points_num self.iterations_num = iterations_num self.threshold_distance = threshold_distance self.threshold_k = threshold_k self.threshold_b = threshold_b self.image = None self.image_threshold = None self.time_service = TimeService(TIME_MAX) self.random_answer = np.array([[1, 1], [2, 2], [3, 3]]) def __get_coords_by_threshold( self, image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > self.image_threshold) return coords # остальной код остается неизменнымПосле внесения изменений ошибка должна исчезнуть.
- User
ERROR: 'NoneType' object is not callable; Traceback: File "/3divi/estimators/test_estimator.py", line 72, in estimator; result = solver.solve(image); File "/tmp/tmpt50jl2yy/solver.py", line 11, in solve; result = self.alg.find_corners(image_gray); File "/tmp/tmpt50jl2yy/corner_detector/corner_detector.py", line 157, in find_corners; self.time_service.start_time()
В чем суть? Вот timeService:
- Assistant
Ошибка возникает из-за вызова метода
start_time()на объектеself.time_service, который является объектом классаNoneType. Это означает, что переменнаяself.time_serviceне была правильно инициализирована и присвоена объектуTimeService.Вам нужно убедиться, что вы правильно создаете и инициализируете объект
TimeServiceв конструкторе классаCornerDetector. Если у вас есть соответствующий файлtime_service.py, убедитесь, что вы его импортировали правильно. Проверьте, что импортированный объектTimeServiceинициализируется правильно и присваивается переменнойself.time_service.Приведите код из файла
time_service.py, чтобы я мог помочь вам с более конкретным решением проблемы.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.