You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用NumPy生成包含重复随机块的噪声图像?

How to Generate Blocky Noise Images with NumPy

Hey there! I totally get what you're aiming for—instead of every pixel being a unique random value, you want larger, uniform color blocks. Let's walk through how to do this easily with NumPy.

The Core Idea

First, create a smaller "base" array where each element represents the color of one block in your final image. Then, scale this base array up by repeating each element across rows and columns to form the solid blocks.

Example Code for 4x4 Image with 2x2 Blocks

import numpy as np

# Step 1: Create a 2x2 base array (each value maps to one 2x2 block in the final image)
base_blocks = np.random.randint(0, 255, (2, 2), dtype=np.uint8)
# Step 2: Repeat each element 2 times in rows and 2 times in columns to build the blocky image
blocky_img = base_blocks.repeat(2, axis=0).repeat(2, axis=1)

print(blocky_img)

This will output exactly the kind of blocky structure you want, like:

array([[150, 150, 246, 246],
       [150, 150, 246, 246],
       [206, 206, 188, 188],
       [206, 206, 188, 188]], dtype=uint8)

Customizing Block Size

Want to adjust the block size or overall image dimensions? Just tweak the base array size and repeat count:

  • For 3x3 blocks in a 9x9 image:
    base_blocks = np.random.randint(0, 255, (3, 3), dtype=np.uint8)
    blocky_img = base_blocks.repeat(3, axis=0).repeat(3, axis=1)
    

Alternative Method: Kronecker Product

If you prefer a more mathematical approach, you can use NumPy's np.kron function. It multiplies the base array by a matrix of ones to expand each element into a solid block:

blocky_img = np.kron(base_blocks, np.ones((2, 2), dtype=np.uint8))

This gives the exact same result as the repeat method—pick whichever feels more intuitive to you!

内容的提问来源于stack exchange,提问作者Nic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:35:59