我正在尝试创建一个在图像上添加随机圆的函数。该圆不应穿过图像的边界。我这样尝试过:
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)
圆圈不断脱离图像边界
最佳答案
确定所生成的位置和半径是否有效的逻辑上有一个小错误。条件
rad - pos[0] >= 0 and rad - pos[1] >= 0
相当于
rad >= pos[0] and rad >= pos[1]
仅当半径同时超过圆心的
True
和x
坐标时,才为y
。您想要相反的情况,即pos[0] >= rad and pos[1] >= pos[1]
# or
pos[0] - rad >= 0 and pos[1] - rad >= 0
仅当圆心的
True
和x
坐标都超过半径时,它才会评估y
。
关于python - opencv创建圈出界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61131809/