Я впервые пишу объектно-ориентированный детектор формы на Python. Я родом из Java. Можете ли вы дать совет по кодированию?
https://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/
@dataclass
class Coordinate:
x_value: int
y_value: int
@dataclass
class Rectangle:
coordinate_upper_left: Coordinate
width: float
height: float
from cv2 import cv2
from numpy.random import randint
import constants.shape_constants as shape_constants
from models.coordinate import Coordinate
from models.rectangle import Rectangle
class ShapeItem():
def __init__(self, curve_data):
# these items must run in sequence to be set correctly
self.curve_data = curve_data
self.drawing_item_id = uuid.uuid4()
self.approx_poly_dp = self.get_approx_poly()
self.vertices = self.get_vertices()
self.bounded_rectangle = self.get_bounded_rectangle()
self.center_coordinate = self.get_center_coordinate()
self.shape = self.get_shape()
def get_approx_poly(self):
perimeter_value = cv2.arcLength(self.curve_data, True)
return cv2.approxPolyDP(self.curve_data, 0.04 * perimeter_value, True)
def get_vertices(self):
vertices_list : list[Coordinate] = []
vertices_data_curve = self.approx_poly_dp.tolist()
for vertices_in_shape in [vertices_data_curve]:
for vertices_shape_two_brackets in vertices_in_shape:
for vertices_shape_one_bracket in vertices_shape_two_brackets:
vertices_item = Coordinate(vertices_shape_one_bracket[0], vertices_shape_one_bracket[1])
vertices_list.append(vertices_item)
return vertices_list
def get_bounded_rectangle(self):
(x_cv, y_cv, width_cv, height_cv) = cv2.boundingRect(self.approx_poly_dp)
bounded_rectangle = Rectangle(
coordinate_upper_left=Coordinate(x_cv, y_cv),
width=width_cv,
height=height_cv
)
return bounded_rectangle
def get_shape(self):
shape_value: str
if len(self.vertices) == 3:
shape_value = shape_constants.TRIANGLE
elif len(self.vertices) == 4:
shape_value = shape_constants.RECTANGLE
elif len(self.vertices) == 5:
shape_value = shape_constants.PENTAGON
else:
shape_value = shape_constants.ELLIPSE
return shape_value
def get_secondary_shape(self):
if self.shape == shape_constants.RECTANGLE and
0.95 <= (self.bounded_rectangle.width / float(self.bounded_rectangle.height) <= 1.05):
return shape_constants.SQUARE
else:
return shape_constants.RECTANGLE
def get_center_coordinate(self):
moment_data = cv2.moments(self.curve_data)
center_x = int((moment_data["m10"] / moment_data["m00"]))
center_y = int((moment_data["m01"] / moment_data["m00"]))
center_coordinate = Coordinate(center_x, center_y)
return center_coordinate
def set_background_color(self):
random_color_index = randint(1, 10)
return random_color_index