Search code examples
pythondrawing

Draw inscribe square into the circle


I am trying to draw inscribing square into the circle, but I don't know, how should I calculate the start and end point:

import numpy as np
import cv2

img = np.zeros([300,300,3],dtype=np.uint8)
img.fill(255) # or img[:] = 255

imageWithCircle = cv2.circle(img, (150,150), 60, (0, 0, 255), 2)

#startpoint = ...
#endpoint = ...

imageWithInscribingSquare = cv2.rectangle(imageWithCircle, startpoint, endpoint, (0, 0, 255) , 2)

cv2.imshow("Circle", imageWithCircle)
cv2.waitKey(0)
cv2.destroyAllWindows()

Solution

  • Check this:

    import numpy as np
    import cv2
    
    img = np.zeros([300,300,3],dtype=np.uint8)
    img.fill(255) # or img[:] = 255
    
    imageWithCircle = cv2.circle(img, (150,150), 60, (0, 0, 255), 2)
    
    r = 60
    startpoint = (int(150+(r/(2**0.5))),int(150-(r/(2**0.5))))
    endpoint = (int(150-(r/(2**0.5))),int(150+(r/(2**0.5))))
    
    print(startpoint,print(endpoint))
    
    
    imageWithInscribingSquare = cv2.rectangle(imageWithCircle, startpoint, endpoint, (255, 0, 0) , 2)
    
    cv2.imshow("Circle", imageWithCircle)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    Output:

    Output Image

    Calculation:

    If the radius is 'r', then the side of the square will be √2r, From the center the start point would be √2r/2 less in width and √2r/2 more in height, and vice versa for endpoint.