pyqt5,python,GUI

pyqt5中QImage读取16位raw图像,怎么正常显示?

imgName, imgType = QFileDialog.getOpenFileName(self.centralwidget, '选择文件', '', 'All files(*)')
img = np.fromfile(imgName, dtype=np.uint16)
N = int(np.size(img) / 640 / 512)
img = img.reshape(N, 512, 640)
img = img[0, :, :]
 qimage = QtGui.QImage(self.shrink.data, self.shrink.shape[1], self.shrink.shape[0], self.shrink.shape[1], QtGui.QImage.Format_Grayscale16)
 pix = QtGui.QPixmap.fromImage(qimage)
self.label.setPixmap(pix)
self.label.setScaledContents(True)
不知道你这个问题是否已经解决, 如果还没有解决的话:

  • 您还可以看一下 闫鄂生老师的Python UI编程PyQt程序设计课程中的 PyQt主要模块介绍小节, 巩固相关知识点
  • 以下回答由chatgpt基于相关博客总结生成:

    在PyQt5中正常显示读取的16位raw图像,可以按照以下步骤进行操作:

    1. 导入需要的模块和类:
    from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow
    from PyQt5.QtGui import QImage, QPixmap
    import numpy as np
    
    1. 创建一个QMainWindow类的子类作为主窗口,例如MainWindow
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
    
            # 其他初始化操作
    
    1. 在主窗口类中添加一个方法用于显示图像:
    def display_image(self, image_data):
        height, width = image_data.shape
        bytes_per_line = width * 2
    
        # 创建QImage对象并将图像数据传入
        qimage = QImage(image_data.data, width, height, bytes_per_line, QImage.Format_Grayscale16)
    
        # 创建QPixmap对象并将QImage转换为QPixmap
        qpixmap = QPixmap.fromImage(qimage)
    
        # 创建一个QLabel用于显示图像
        label = QLabel(self)
        label.setPixmap(qpixmap)
    
        # 将label添加到主窗口中的布局或位置
        # 例如:self.setCentralWidget(label)或self.layout().addWidget(label)
    
    1. 在主窗口类中添加一个方法用于读取16位raw图像文件并调用显示图像的方法:
    def load_image(self, filename):
        # 使用numpy读取raw图像文件
        image_data = np.fromfile(filename, dtype=np.uint16)
        image_data = image_data.reshape((height, width))
    
        self.display_image(image_data)
    
    1. 在主窗口类的初始化方法中调用上述方法来初始化界面并显示图像:
    def __init__(self):
        super().__init__()
    
        self.load_image("path_to_raw_image.raw")
    
    1. if __name__ == '__main__':部分创建应用程序并运行主窗口:
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        main_window = MainWindow()
        main_window.show()
        sys.exit(app.exec_())
    

    注意: 需要将"path_to_raw_image.raw"替换为实际的raw图像文件路径。此外,还需要根据实际的图像尺寸和数据类型(dtype)来设置代码中的相关参数。

    这样,运行程序后,应该能够成功读取并显示16位raw图像文件。如果仍然无法正常显示,可能是图像数据读取或显示的过程存在问题,可能需要进行进一步的调试和排查。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^