使用Numpy按列优先重塑图像时出现图片重复问题求助
问题解决方法
核心原因
直接对(256,256,3)的数组使用reshape((3,256,256), order='F')会打乱通道与空间维度的对应关系,导致图像显示时出现重复分块。列优先(Fortran order)的reshape是对整个数组的元素按列顺序重新排布形状,而非在保持通道独立的前提下调整空间维度的存储顺序。
正确处理流程
- 转换通道顺序:先把
(H, W, C)格式的图片数组转为(C, H, W)格式,用transpose保持通道独立:im = Image.open(file) imarr = np.array(im) # 从(H,W,C)转成(C,H,W) imarr_chw = imarr.transpose((2, 0, 1)) - 按列优先处理存储格式:如果需要将
(C, H, W)数组按列优先存储到bin文件,对该数组做列优先的扁平化处理:# 按列优先展平数组,用于写入bin文件 arr_for_bin = imarr_chw.flatten(order='F') # 写入bin文件示例 arr_for_bin.tofile('your_file.bin') - 正常显示图片:将
(C, H, W)格式转回去即可正常显示:# 转回(H,W,C)用于绘图 img = imarr_chw.transpose((1, 2, 0)) plt.imshow(img) plt.title('generate bin files') plt.show()
还原验证(从bin文件读取)
如果需要从生成的bin文件读取并还原图片,可按以下步骤:
# 从bin文件读取,按列优先重构为(C,H,W) restored_arr = np.fromfile('your_file.bin', dtype=np.uint8).reshape((3, 256, 256), order='F') # 转回(H,W,C)显示 restored_img = restored_arr.transpose((1,2,0)) plt.imshow(restored_img) plt.show()
内容的提问来源于stack exchange,提问作者Willy Lutz
相关产品推荐
相关产品推荐

