python - opencv创建圈出界

标签 python numpy opencv graphics geometry

我正在尝试创建一个在图像上添加随机圆的函数。该圆不应穿过图像的边界。我这样尝试过:

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)    

圆圈不断脱离图像边界

enter image description here

最佳答案

确定所生成的位置和半径是否有效的逻辑上有一个小错误。条件

rad - pos[0] >= 0 and rad - pos[1] >= 0

相当于

rad >= pos[0] and rad >= pos[1]

仅当半径同时超过圆心的Truex坐标时,才为y。您想要相反的情况,即

pos[0] >= rad and pos[1] >= pos[1]
# or
pos[0] - rad >= 0 and pos[1] - rad >= 0

仅当圆心的Truex坐标都超过半径时,它才会评估y

关于python - opencv创建圈出界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61131809/

相关文章:

python - 使python代码运行更快以减少偏移

python - 使用 OpenCV python 绑定(bind)索引 channel 数据(numpy 数组)

python - pyqtgraph编译为可执行文件失败

Python numpy.square 与 **

python - 如何找到图像外遗漏的角落

c++ - 二值图像的特征提取

Python turtle 颜色未正确填充

python - 使用 nbconvert html 导出时合并 'toc' 和 'hide input'

opencv - 从 OpenCv 图像比较中获取比较分数

python - 从字符串列表中删除重复项