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

如何在列表/数组中快速生成30x30填充有机Blob形状?

快速生成30x30填充有机Blob的Python算法思路

针对30x30的小尺寸需求,以下几个基础算法思路能快速生成填充的有机Blob,避开你提到的角度遍历低效问题:

1. 随机种子扩散法

模拟细胞生长逻辑,计算量极小:

  • 初始化30x30的全0数组,随机选取1-3个内部点作为初始填充种子;
  • 多轮迭代:每轮遍历所有已填充的点,随机选择其未填充的相邻点(上下左右)进行填充,可通过概率控制每轮填充量(比如每个种子点有60%概率填充一个邻居);
  • 停止条件:填充面积达到目标(比如画布的30%-60%),或固定迭代5-8轮。

生成的Blob边缘自然无规则,简单实现示例:

import random
import numpy as np

def seed_diffusion_blob(size=30, target_area=400):
    blob = np.zeros((size, size), dtype=int)
    # 随机选初始种子(避开边缘)
    seeds = [(random.randint(4, size-5), random.randint(4, size-5)) for _ in range(2)]
    for x, y in seeds:
        blob[x, y] = 1
    filled = seeds.copy()
    
    while len(filled) < target_area:
        new_points = []
        for x, y in filled:
            # 打乱方向增加随机性
            dirs = [(-1,0), (1,0), (0,-1), (0,1)]
            random.shuffle(dirs)
            for dx, dy in dirs:
                nx, ny = x+dx, y+dy
                if 0 <= nx < size and 0 <= ny < size and blob[nx, ny] == 0:
                    blob[nx, ny] = 1
                    new_points.append((nx, ny))
                    if len(filled) + len(new_points) >= target_area:
                        break
            if len(filled) + len(new_points) >= target_area:
                break
        filled.extend(new_points)
    return blob

2. 噪声阈值法

全程向量运算,速度极快,生成的Blob边缘平滑:

  • 生成30x30的随机均匀噪声数组;
  • 对噪声数组做高斯模糊(sigma设为2-3,适配30x30尺寸),模糊后噪声会形成连续平滑区域;
  • 设定阈值,将模糊后数组中高于阈值的区域设为1(填充),低于的设为0,得到填充Blob。

实现示例:

import numpy as np
from scipy.ndimage import gaussian_filter

def noise_threshold_blob(size=30, sigma=2.5, threshold=0.3):
    # 生成0-1范围的随机噪声
    noise = np.random.uniform(0, 1, (size, size))
    # 高斯模糊平滑噪声
    blurred_noise = gaussian_filter(noise, sigma=sigma)
    # 阈值化得到填充Blob
    blob = (blurred_noise > threshold).astype(int)
    return blob

3. 多边形膨胀法

形状可控,膨胀后边缘圆润:

  • 随机生成3-8个顶点的简单多边形(顶点分布在画布内部);
  • 用填充算法(比如PIL的ImageDraw.polygon)填充多边形;
  • 对填充后的区域做2-3次形态学膨胀(用3x3的结构元),让棱角边缘变得圆润有机。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 12:54:19