将txt文件中的jpeg值转换为图像

2024-05-09 01:27:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这段代码中尝试将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')

Tags: and文件of代码txtasnparray
1条回答
网友
1楼 · 发布于 2024-05-09 01:27:50

不需要PIL库。您已经有一个JPEG文件。
只需将这些数字转换为字节并保存即可

with open("C://Users//hp//Desktop//file.txt", "r") as f:
    data = f.read()
data = data.split(",") # split the numbers
data = [int(b) for b in data] # convert them to integers
data = data[2:] # remove width and height
data = bytes(data) # convert the array of numbers to bytes
with open("C://Users//hp//Desktop//jp.jpg", "wb") as f:
    f.write(data)

结果:

jp.jpg

注意:结尾处似乎缺少数据。您可能尚未捕获所有数据。
您声称有2396个值,但您的示例有3842个值

相关问题 更多 >