我想查看原始图像

时间:2018-06-26 05:55:49

标签: python pyside qimage qfile qdatastream

enter image description here

我要查看原始图像文件。

但是所有图像都会转换为斑点的损坏图像。

前一个图像似乎不等于后一个图像。

请在QImage的构造函数中将图像大小更改为任意样本图像的大小。

如果执行此代码,则捕获了损坏的图像。为什么?

enter image description here

我试图将Format.Format_ARGB32_Premultiplied更改为各种模式。

但是所有模式都不顺利。

from PIL import Image
import numpy as np
from PySide import QtCore
from PySide import QtGui
import sys
#the original file
filename = 'Any_Data.png'

im = Image.open(filename)
data = np.array(im)

file_ = QtCore.QFile("test_file.img")
file_.open(QtCore.QIODevice.WriteOnly)
qdatastream = QtCore.QDataStream(file_)


bytedatas = QtCore.QByteArray(data.tobytes())
#print(bytedatas)
#print(len(data.tobytes()),type(data))

qdatastream << bytedatas

output_file_ = QtCore.QFile("test_file.img")
output_file_.open(QtCore.QIODevice.ReadOnly)
qdatastream = QtCore.QDataStream(output_file_)
#the behind file
bytedata = QtCore.QByteArray()

qdatastream >> bytedata


Image = QtGui.QImage(220,133,QtGui.QImage.Format.Format_ARGB32_Premultiplied)
Image.fromData(bytedata)
def main():
    try:
        QtGui.QApplication([])
    except Exception as e:
        print(e)

    widget = QtGui.QLabel()

    pixmap = QtGui.QPixmap()
    pixmap.convertFromImage(Image)
    widget.setPixmap(pixmap)

    widget.show()
    sys.exit(QtGui.QApplication.exec_())
if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:1)

按字节转换和保存数据时,将丢失尺寸信息。如果您的目标是保存图像信息,则最好将PIL转换为QImage,然后将此QImage保存在文件中,然后只需恢复即可,如下所示:

import sys

from PIL import Image
import numpy as np

from PySide import QtCore, QtGui

filename = 'Any_Data.png'
filename_out = "data.bin"

im = Image.open(filename)
data = np.array(im)
qimagein = QtGui.QImage(data.data, data.shape[1], data.shape[0], data.strides[0], QtGui.QImage.Format_RGB888)

# save data
filewrite = QtCore.QFile(filename_out)
filewrite.open(QtCore.QIODevice.WriteOnly)
out_datastream = QtCore.QDataStream(filewrite)
out_datastream << qimagein

# read data
fileread = QtCore.QFile(filename_out)
fileread.open(QtCore.QIODevice.ReadOnly)
qimageout = QtGui.QImage()
in_datastream = QtCore.QDataStream(fileread)
in_datastream >> qimageout

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    w = QtGui.QLabel()
    pix = QtGui.QPixmap.fromImage(qimageout)
    w.setPixmap(pix)
    w.show()
    sys.exit(app.exec_())