如何将.txt文件解码为图像格式

2024-03-28 13:33:33 发布

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

我有一个包含像素坐标和像素值的.txt文件。我试图用8位压缩的png和jpeg格式将其可视化,但我希望它是像tiff一样的16位图像格式。我尝试过用tiff格式保存图像,但它不是我所期望的图像。它有很多噪音,与png或jpeg相比,我打开文件时甚至看不到图像

这是我的密码

import numpy as np
from PIL import Image 
import pandas as pd
from matplotlib import pyplot as plt 



file = open('filename')
data = pd.read_table(file, header=None, skiprows=8, decimal=",")
data = data.iloc[:, :]
rows, cols = data.shape

na = np.array(data)
plt.imshow(na)

plt.imsave('mes.png',an)
na.save('myimg.tif')

我在执行此操作时做错了什么,有什么建议或更改吗? 非常感谢您的帮助,谢谢您抽出时间


Tags: 文件from图像importdatapngas格式
1条回答
网友
1楼 · 发布于 2024-03-28 13:33:33

问题在于,对于未签名的16位TIFF或PNG文件,您尚未将数据标准化为0..65535的正确范围

我在这里使用的是OpenCV函数,但是您可以使用Numpy或直接Python来获得相同的结果。因此,在转换为Numpy数组之后

... your code ...
na = np.array(data)

import cv2
# Normalise (scale) to range 0..65535
sc = cv2.normalize(na, None, alpha=0, beta=65535, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_16U)

# Save, using any ONE of the following methods
Image.fromarray(sc).save('result.tif')
Image.fromarray(sc).save('result.png')
cv2.imwrite('result.tif', sc)
cv2.imwrite('result.png', sc)

enter image description here

相关问题 更多 >