在图像/矩阵中创建随机的白色矩形/数组

2024-10-02 08:25:47 发布

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

我有一个在Python(512x512)中保存为矩阵的图像。 现在我想添加一些大小恒定的随机矩形来模拟一些缺失的区域。 通常,我会在图像大小内创建一个随机索引,并使用嵌套循环创建一个5x5大小的数组,其值为255(=Python中为白色)。 我需要另一个循环来创建特定数量的矩形。 总而言之,我需要3个循环:

for (0,amountOfRec):
    startPoint = (randomIndex1,randomIndex2)
         for (0,sizeOfRec)        #jump to next row
              for (0,sizeOfRec)   #create a row with value 255

这种方式似乎很幼稚。没有更好的方法不使用3个嵌套循环吗?在


Tags: 图像区域for数量矩阵数组row嵌套循环
1条回答
网友
1楼 · 发布于 2024-10-02 08:25:47

对于处理大型矩阵,您应该使用Numpy,这使您能够使用向量化操作,以及许多其他好处。在

假设您的图像是灰度级的(或只有一个RGB通道),并以简单的嵌套数组格式表示,您可以尝试如下操作:

import numpy as np

#Generate random "image" (replace this with your original image)
img = np.random.randint(0,256, size=512**2).reshape(512,512)

#Make white box
box = np.array([255]*5*5).reshape(5,5)

#Generate random coordinates
x, y = np.random.randint(0,512-5, size=2)

#Replace original image with white box
img[x:x+5, y:y+5] = box

相关问题 更多 >

    热门问题