[Python] Finding the bounding circle

Discussão em 'Python' iniciado por Stack, Setembro 25, 2024.

  1. Stack

    Stack Membro Participativo

    The logic in my code is not absolute. I tried to find the center coordinates and radius of bounding circle by taking the diameter end points as 1) the point farthest from origin and 2) the point farthest away from (1). But this is does not give me an actual result in all cases. pls dont mind indendation (I use tabs and copied my code.)

    from tkinter import *

    class point2D:
    def __init__(self, x=0, y=0):
    self.__x = x
    self.__y = y

    def x(self):
    return self.__x

    def y(self):
    return self.__y

    def setx(self, x):
    self.__x = x

    def sety(self, y):
    self.__y = y

    def __str__(self):
    return f"({self.__x}, {self.__y})"

    def distance(self, other):
    return ((self.__x-other.__x)**2 + (self.__y-other.__y)**2) ** 0.5

    class box:
    def __init__(self):
    root = Tk()
    root.title("Bounding Circle")
    width, height = 600, 600
    root.geometry(f"{width}x{height}")

    self.canvas = Canvas(root, width=width, height=height, bg="white")
    self.canvas.pack()
    self.canvas.bind("<Button-1>", self.addpoint)

    self.origin = point2D()

    self.points = []

    root.mainloop()

    def addpoint(self, event):
    radius = 5
    self.canvas.create_oval(event.x - radius, event.y - radius,
    event.x + radius, event.y + radius, fill = "black")
    self.points.append(point2D(event.x, event.y))
    self.getboundingcircle()

    def getboundingcircle(self):
    if len(self.points) == (1 or 0):
    return
    #Finding the point farthest from origin (0,0 in canvas)
    d, start = self.points[0].distance(self.origin), 0
    for i in range(1, len(self.points)):
    x = self.points.distance(self.origin)
    if x > d:
    d = x
    start = i
    #Finding the point farthest from points[start]
    d, end = 0, 0
    for i in range(len(self.points)):
    if i == start:
    continue
    x = self.points.distance(self.points[start])
    if x > d:
    d = x
    end = i

    center_x = (self.points[start].x() + self. points[end].x()) / 2
    center_y = (self.points[start].y() + self. points[end].y()) / 2
    radius = self.points[start].distance(self.points[end]) / 2

    self.canvas.delete("circle")
    self.canvas.create_oval(center_x - radius, center_y - radius,
    center_x + radius, center_y + radius, outline = "red", tags = "circle")

    box()

    Continue reading...

Compartilhe esta Página