numpy - 制作重复的随机数块(噪声图像)

numpy - make repeated random number blocks (noise image)

我想制作一张 "noise" 图片。如果我这样做

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

输出:

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

每个像素都不一样。但是如果我想要更大的 'pixels' 怎么办,例如:

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]])