The OpenCV circle is suitable, so let's draw a cleaner circle. The image of a circle with radius r
is 1 at a distance less than r-1
from the center, 0 at a distance greater than r
, and r-distance
between them.
import math, cv2, numpy as np
# r must be greater than 0.
def circle(r):
c = math.ceil(r - 1)
s = c * 2 + 1
return np.clip(r - np.sqrt(np.sum((np.stack((
np.tile(np.arange(s), (s, 1)),
np.repeat(np.arange(s), s).reshape((-1, s))
)) - c) ** 2, axis=0)), 0, 1)
# r must be greater than 0. width must be greater than 0 and less than r.
def outline_circle(r, width):
circ = circle(r)
icirc = circle(r - width)
ch, cw = circ.shape
ich, icw = icirc.shape
sx = (cw - icw) // 2
sy = (ch - ich) // 2
ex = sx + icw
ey = sy + ich
circ[sy:ey, sx:ex] = np.amax(np.stack((circ[sy:ey, sx:ex] - icirc, np.zeros((ich, icw)))), axis=0)
return circ
def save_cv2_circle(file_name, r, thickness = -1):
s = r * 2 + 1
cv2.imwrite(file_name, cv2.circle(np.zeros((s, s), dtype=np.uint8), (r, r), r, 255, thickness))
def save_circle(file_name, c):
im = (np.around(c) * 255).astype(np.uint8)
cv2.imwrite(file_name, im)
save_circle('/tmp/circle10.jpg', circle(11))
save_cv2_circle('/tmp/cv2_circle10.jpg', 10)
save_circle('/tmp/circle10_outline.jpg', outline_circle(11, 1))
save_cv2_circle('/tmp/cv2_circle10_outline.jpg', 10, 1)
/tmp/circle10.jpg
/tmp/cv2_circle10.jpg
/tmp/circle10_outline.jpg
/tmp/cv2_circle10_outline.jpg
The difference is obvious.
Recommended Posts