Python如何将斐波那契数列模255的数值列表转换为RGB图像
斐波那契数列转RGB图像实现方案
错误原因
- RGB图像要求输入为
(高度, 宽度, 3)结构的三维数组,最后一维的3个值分别对应红、绿、蓝三个通道的亮度,你当前生成的rgb是一维数组,不符合输入要求 - 数组数值没有转换为
uint8类型,图像库无法正确识别0-255区间的亮度取值
实现代码
基础版:用现有数列生成像素块
现有取模后的rgb列表长度为99,刚好可以拆分为33组R/G/B值,我们把它调整为3行11列的像素块,可按需放大显示:
import numpy as np from PIL import Image import matplotlib.pyplot as plt # 你之前得到的取模后数值列表 rgb = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 122, 100, 222, 67, 34, 101, 135, 236, 116, 97, 213, 55, 13, 68, 81, 149, 230, 124, 99, 223, 67, 35, 102, 137, 239, 121, 105, 226, 76, 47, 123, 170, 38, 208, 246, 199, 190, 134, 69, 203, 17, 220, 237, 202, 184, 131, 60, 191, 251, 187, 183, 115, 43, 158, 201, 104, 50, 154, 204, 103, 52, 155, 207, 107, 59, 166, 225, 136, 106, 242, 93, 80, 173, 253, 171, 169, 85, 254, 84, 83, 167, 250, 162, 157, 64, 221] # 裁剪数组为3的整数倍,每3个值对应一个像素的R/G/B pixel_count = len(rgb) // 3 rgb_trim = rgb[:pixel_count * 3] # 转为三维uint8数组,这里设置为3行11列的像素结构 img_arr = np.array(rgb_trim, dtype=np.uint8).reshape(3, 11, 3) # --- 用PIL生成保存图像 --- # 放大10倍避免像素太小,使用 nearest 采样保留边缘清晰 img = Image.fromarray(img_arr) img_resized = img.resize((330, 90), resample=Image.Resampling.NEAREST) img_resized.save('fib_rgb.png') img_resized.show() # --- 用matplotlib生成保存图像 --- # plt.imshow(img_arr) # plt.axis('off') # plt.savefig('fib_rgb_plt.png', bbox_inches='tight', pad_inches=0) # plt.show()
进阶版:生成100*100的完整RGB图像
如果需要填满你之前定义的100*100尺寸,可将生成的颜色序列循环填充到全图:
# 接上面的代码 color_list = np.array(rgb_trim, dtype=np.uint8).reshape(-1, 3) full_img = np.zeros((100, 100, 3), dtype=np.uint8) # 循环填充颜色 for i in range(100): for j in range(100): full_img[i][j] = color_list[(i * 100 + j) % len(color_list)] Image.fromarray(full_img).save('100x100_fib_rgb.png') Image.fromarray(full_img).show()
内容的提问来源于stack exchange,提问作者Bartu Bozkurt
相关产品推荐
相关产品推荐

