如何将像素数组写入文件并在Raspberry Pi Pico上正确读取?
解决方案:像素数组的存储与读取(适配Raspberry Pi Pico)
方法1:二进制存储(推荐,紧凑高效)
这种方式直接将每个RGB值以字节形式存储,文件体积最小、读取速度快,非常适合资源有限的Pico设备。
写入代码(Python)
# 示例像素数组 pixels = [(255, 0, 0), (125, 111, 2), (0, 255, 0), (0, 0, 255)] # 将所有RGB值展开为一维整数列表 flat_pixels = [val for pixel in pixels for val in pixel] # 转换为字节对象(0-255的整数可直接转为对应字节) byte_data = bytes(flat_pixels) # 写入二进制文件 with open("pixels.bin", "wb") as f: f.write(byte_data)
读取代码(Python/MicroPython)
with open("pixels.bin", "rb") as f: byte_data = f.read() # 每3个字节重组为一个RGB像素三元组 pixels = [tuple(byte_data[i:i+3]) for i in range(0, len(byte_data), 3)] # 测试:获取第十个像素的红色值(索引从0开始) # print(pixels[9][0])
如果你的像素是二维数组(按图片行列排列),可以先存储宽高信息再存像素数据:
二维数组写入
width = 10 # 每行像素数 height = 5 # 行数 # 示例二维像素数组 pixels_2d = [ [(255,0,0), (125,111,2)] * 5, [(0,255,0), (0,0,255)] *5 ] # 先存宽高,再展开所有像素值 flat_data = [width, height] + [val for row in pixels_2d for pixel in row for val in pixel] byte_data = bytes(flat_data) with open("pixels_2d.bin", "wb") as f: f.write(byte_data)
二维数组读取
with open("pixels_2d.bin", "rb") as f: byte_data = f.read() width = byte_data[0] height = byte_data[1] pixel_bytes = byte_data[2:] pixels_2d = [] idx = 0 for _ in range(height): row = [] for _ in range(width): row.append( (pixel_bytes[idx], pixel_bytes[idx+1], pixel_bytes[idx+2]) ) idx +=3 pixels_2d.append(row) # 测试:获取第1行第10个像素的红色值 # print(pixels_2d[0][9][0])
方法2:CSV格式存储(可读易修改)
如果需要手动查看或修改像素数据,CSV格式更友好,代价是文件体积更大。
写入代码(Python)
import csv pixels = [(255, 0, 0), (125, 111, 2), (0, 255, 0)] with open("pixels.csv", "w", newline='') as f: writer = csv.writer(f) writer.writerows(pixels)
读取代码(Python)
import csv pixels = [] with open("pixels.csv", "r") as f: reader = csv.reader(f) for row in reader: pixels.append( tuple(int(val) for val in row) )
读取代码(MicroPython,无csv模块时)
pixels = [] with open("pixels.csv", "r") as f: for line in f: line = line.strip() if not line: continue r, g, b = line.split(',') pixels.append( (int(r), int(g), int(b)) )
问题根源说明
你之前尝试的chr()、直接写入整数等方法无效,原因是:
chr(255)会将整数转为对应ASCII字符,写入的是字符编码而非原始字节值;- 文件对象的
write()方法仅接受字符串或字节对象,直接传入整数会报错; - 用字符串存储会引入额外字符(如括号、逗号、换行),增加解析复杂度。
而bytes()可以直接接收0-255的整数列表,将每个整数转为对应字节,完美匹配你的需求。
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

