我在这段代码中尝试将txt文件中的jpeg值转换为jpg图像。 捕获图像的大小=120*160,文件中的值数=2396(我不知道为什么总长度如此)
我得到这个错误
na = np.array(pixels, dtype=np.uint8).reshape((int(h),int(w)))
ValueError: cannot reshape array of size 2396 into shape (120,160)
代码:
# Open image file, slurp the lot
contents = Path('C://Users//hp//Desktop//file.txt').read_text()
# Make a list of anything that looks like numbers using a regex...
# ... taking first as height, second as width and remainder as pixels
h, w, *pixels = re.findall(r'[0-9]+', contents)
# Now make pixels into Numpy array of uint8 and reshape to correct height, width and depth
na = np.array(pixels, dtype=np.uint8).reshape((int(h),int(w)))
# Now make the Numpy array into a PIL Image and save
Image.fromarray(na).save('C://Users//hp//Desktop//jp.jpg')
不需要PIL库。您已经有一个JPEG文件。
只需将这些数字转换为字节并保存即可
结果:
注意:结尾处似乎缺少数据。您可能尚未捕获所有数据。
您声称有2396个值,但您的示例有3842个值
相关问题 更多 >
编程相关推荐