Reputation: 35
I am trying to create a function that adds a random circle on an image. The circle should not pass the boundaries of the image. I tried it this way:
def create_circle(image):
found = False
color = (np.random.randint(low=0, high=255),
np.random.randint(low=0, high=255),
np.random.randint(low=0, high=255))
while not found:
pos = (np.random.randint(low=0, high=image.shape[1]),
np.random.randint(low=0, high=image.shape[0]))
rad = np.random.randint(low=0, high=image.shape[0]//2)
if( rad +pos[0]< image.shape[0] and rad +pos[1]< image.shape[1]
and rad -pos[0] >= 0 and rad -pos[1]>= 0):
found = True
cv2.circle(image,pos,rad,color,-1)
the circle keep getting out of the image boundaries
Upvotes: 1
Views: 424
Reputation: 10320
There is a small error in the logic for deciding if the generated position and radius are valid. The conditions
rad - pos[0] >= 0 and rad - pos[1] >= 0
are equivalent to
rad >= pos[0] and rad >= pos[1]
Which is True
only if the radius exceeds both the x
and y
coordinate of the center of the circle. You want the opposite, i.e.
pos[0] >= rad and pos[1] >= pos[1]
# or
pos[0] - rad >= 0 and pos[1] - rad >= 0
Which will evaluate True
only if both the x
and y
coordinates of the center of the circle exceed the radius.
Upvotes: 1