numpy-进行重复的随机数块(噪声图像)



我想制作"噪声"图像。如果我做

img = np.random.randint(0, 255, (4, 4), dtype=np.uint8)
print(img)

out:

array([[150,  45, 246, 137],
       [195, 141, 246, 197],
       [206, 126, 188,  76],
       [134, 168, 166, 190]])

每个像素都是不同的。但是,如果我想要更大的"像素",例如:

array([[150, 150, 246, 246],
       [150, 150, 246, 246],
       [206, 206, 188, 188],
       [206, 206, 188, 188]])

我该怎么做?

您可以使用np.kron

>>> np.kron(np.random.randint(0, 256, (4, 4)), np.ones((2, 2), int))
array([[252, 252,  51,  51,  10,  10, 124, 124],
       [252, 252,  51,  51,  10,  10, 124, 124],
       [161, 161, 137, 137,   8,   8,  89,  89],
       [161, 161, 137, 137,   8,   8,  89,  89],
       [ 12,  12,  24,  24,  37,  37,  98,  98],
       [ 12,  12,  24,  24,  37,  37,  98,  98],
       [151, 151, 149, 149, 147, 147,  15,  15],
       [151, 151, 149, 149, 147, 147,  15,  15]])

np.repeat(每个维度一次(:

>>> np.repeat(np.repeat(np.random.randint(0, 256, (4, 4)), 2, 0), 2, 1)
array([[ 41,  41,  29,  29, 103, 103,  67,  67],
       [ 41,  41,  29,  29, 103, 103,  67,  67],
       [231, 231, 203, 203, 231, 231, 157, 157],
       [231, 231, 203, 203, 231, 231, 157, 157],
       [ 18,  18, 126, 126,  15,  15, 196, 196],
       [ 18,  18, 126, 126,  15,  15, 196, 196],
       [198, 198, 152, 152,  74,  74, 211, 211],
       [198, 198, 152, 152,  74,  74, 211, 211]])