我想在给定的图像(python)中,在不同的随机点添加4个圆,但是添加了这些圆之后代码就不起作用了

2024-06-30 12:17:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在图像上的任意点添加圆。代码将圆添加到图像中

附件是我尝试的代码:

img = np.zeros([100,100],dtype=np.uint8)
img.fill(20)



def createCircle(width,height , rad ):
  w = random.randint(1, height)
  h = random.randint(1, height)
  center = [int(w), int(h)]
  radius = rad

  Y, X = np.ogrid[:height, :width]
  dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)

  mask = dist_from_center <= radius

  return mask


def addCircle(test_image):
  m = createCircle(width = 100, height = 100 , rad = 8 )
  masked_img = test_image.copy()
  masked_img[~m] = 0
  return masked_img

im = addCircle(test_image=img)
plt.imshow(im)
plt.show()

im1 = addCircle(test_image = im)
plt.imshow(im1)
plt.show()

当我对图像应用addCircle函数img时,它会将圆添加到图像中,但当我对im应用addCircle函数时,它不会将另一个圆添加到图像中。你知道吗

我想在同一张图片上随机添加4个圆,但现在我只能添加一个圆,之后代码就不起作用了。你知道吗


Tags: 代码test图像imageimgdefnpplt
1条回答
网友
1楼 · 发布于 2024-06-30 12:17:20

正如评论中提到的。。。你的问题似乎在这行masked_img[~m] = 0。你知道吗

def addCircle(test_image):
    m = createCircle(width = 100, height = 100 , rad = 8 )
    masked_img = test_image.copy()
    masked_img[m] = 0
    return masked_img

# im = addCircle(test_image=img)
# plt.imshow(im)
# plt.show()
for i in range(4):
    img = addCircle(test_image=img)
plt.imshow(img)
plt.show()

Result

相关问题 更多 >