Python如何基于各像素RGB值创建NumPy图像数组并生成可正常打开的图片
问题原因
- 随机值数组的维度不符合图像格式要求。你遍历像素时把所有RGB值按顺序存入了一维列表
value,转成numpy数组后shape为(921600, 3),而PIL生成RGB图像要求输入数组的shape必须是(高度, 宽度, 3),你当前使用的图像尺寸为720高、1280宽,需要把数组reshape为(720, 1280, 3)才能生成有效图像。 - 存在隐藏的数值溢出问题。初始图像默认是uint8类型(取值范围0-255的无符号整数),像素值减去随机数如果得到负数,会自动溢出变为255附近的异常值,和预期计算结果不符,建议计算前先转成int类型,输出前再转回uint8。
修正后代码
import numpy as np import random from PIL import Image # 初始化原图像 a = Image.new('RGB', [1280, 720], (255, 255, 255)) a = np.array(a).astype(int) # 转int避免减法溢出 h, w = a.shape[:2] value = [] for x in a: for y in range(0, len(x)): temp = [random.randrange(0, 255), random.randrange( 0, 255), random.randrange(0, 255)] b = np.array(temp) x[y] = x[y]-b value.append(temp) # 生成第一张处理后图像 a = np.clip(a, 0, 255).astype(np.uint8) # 限制数值范围转回uint8 a = Image.fromarray(a) a.show() # 生成随机值对应的图像,核心是reshape为正确维度 c = np.array(value).reshape(h, w, 3).astype(np.uint8) d = Image.fromarray(c) d.show()
优化提示
如果不需要兼容现有逻辑,可以用numpy的随机接口直接生成对应维度的数组,完全替代双重循环,运行效率提升非常明显:c = np.random.randint(0, 255, size=(h, w, 3), dtype=np.uint8)
内容的提问来源于stack exchange,提问作者DAF201
相关产品推荐
相关产品推荐

