将滑块连接到PyQt中的图形视图

3
我正在尝试显示从二进制文件中读取的图像数据(我已编写代码以从文件中检索此数据并将其存储为用于QImage()的图像)。 我想做的是将滑块连接到Graphics View小部件,以便当您移动滑块时,它会浏览帧并显示该帧的图像(这些是长度介于1-500帧的回声图)。 我对PyQt非常陌生,想知道如何开始处理?
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import numpy as np



class FileHeader(object):

    fileheader_fields=      ("filetype","fileversion","numframes","framerate","resolution","numbeams","samplerate","samplesperchannel","receivergain","windowstart","winlengthsindex","reverse","serialnumber","date","idstring","ID1","ID2","ID3","ID4","framestart","frameend","timelapse","recordInterval","radioseconds","frameinterval","userassigned")
   fileheader_formats=('S3','B','i4','i4','i4','i4','f','i4','i4','i4','i4','i4','i4','S32','S256','i4','i4','i4','i4','i4','i4','i4','i4','i4','i4','S136')

    def __init__(self,filename,parent=None):
        a=QApplication([])
        filename=str(QFileDialog.getOpenFileName(None,"open file","C:/vprice/DIDSON/DIDSON Data","*.ddf"))
        self.infile=open(filename, 'rb')
        dtype=dict(names=self.fileheader_fields, formats=self.fileheader_formats)
        self.fileheader=np.fromfile(self.infile, dtype=dtype, count=1)
        self.fileheader_length=self.infile.tell()


    for field in self.fileheader_fields:
        setattr(self,field,self.fileheader[field])



    def get_frame_first(self):
        frame=Frame(self.infile)
        print self.fileheader
        self.infile.seek(self.fileheader_length)
        print frame.frameheader
        print frame.data



    def __iter__(self):
        self.infile.seek(self.fileheader_length)

    for _ in range(self.numframes):
        yield Frame(self.infile)

    #def close(self):
        #self.infile.close()
    def display(self):
        print self.fileheader


class Frame(object):
    frameheader_fields=("framenumber","frametime","version","status","year","month","day","hour","minute","second","hsecond","transmit","windowstart","index","threshold","intensity","receivergain","degc1","degc2","humidity","focus","battery","status1","status2","velocity","depth","altitude","pitch","pitchrate","roll","rollrate","heading","headingrate","sonarpan","sonartilt","sonarroll","latitude","longitude","sonarposition","configflags","userassigned")
    frameheader_formats=("i4","2i4","S4","i4","i4","i4","i4","i4","i4","i4","i4","i4","i4","i4","i4","i4","i4","i4","i4","i4","i4","i4","S16","S16","f","f","f","f","f","f","f","f","f","f","f","f","f8","f8","f","i4","S60")
    data_format="uint8"

    def __init__(self,infile):

        dtype=dict(names=self.frameheader_fields,formats=self.frameheader_formats)
        self.frameheader=np.fromfile(infile,dtype=dtype,count=1)


        for field in self.frameheader_fields:
            setattr(self,field,self.frameheader[field])

        ncols,nrows=96,512


        self.data=np.fromfile(infile,self.data_format,count=ncols*nrows)

        self.data=self.data.reshape((nrows,ncols))

class QEchogram():
    def __init__(self):
        self.__colorTable=[]
        self.colorTable=None
        self.threshold=[50,255]
        self.painter=None
        self.image=None

    def echogram(self):
        fileheader=FileHeader(self)
        frame=Frame(fileheader.infile)
        echoData=frame.data

        #fileName = fileName

        self.size=[echoData.shape[0],echoData.shape[1]]

        #  define the size of the data (and resulting image)
        #size = [96, 512]

        #  create a color table for our image
        #  first define the colors as RGB triplets
        colorTable =  [(255,255,255),
                       (159,159,159),
                       (95,95,95),
                       (0,0,255),
                       (0,0,127),
                       (0,191,0),
                       (0,127,0),
                       (255,255,0),
                       (255,127,0),
                       (255,0,191),
                       (255,0,0),
                       (166,83,60),
                       (120,60,40),
                       (200,200,200)]

    #  then create a color table for Qt - this encodes the color table
    #  into a list of 32bit integers (4 bytes) where each byte is the
    #  red, green, blue and alpha 8 bit values. In this case we don't
    #  set alpha so it defaults to 255 (opaque)
        ctLength = len(colorTable)
        self.__ctLength=ctLength
        __colorTable = []
        for c in colorTable:
            __colorTable.append(QColor(c[0],c[1],c[2]).rgb())




        echoData = np.round((echoData - self.threshold[0])*(float(self.__ctLength)/(self.threshold[1]-self.threshold[0])))
        echoData[echoData < 0] = 0
        echoData[echoData > self.__ctLength-1] = self.__ctLength-1
        echoData = echoData.astype(np.uint8)
        self.data=echoData

    #  create an image from our numpy data
        image = QImage(echoData.data, echoData.shape[1], echoData.shape[0], echoData.shape[1],
                   QImage.Format_Indexed8)
        image.setColorTable(__colorTable)

    #  convert to ARGB
        image = image.convertToFormat(QImage.Format_ARGB32)


    #  save the image to file
        image.save(fileName)
        self.image=QImage(self.size[0],self.size[1],QImage.Format_ARGB32)
        self.painter=QPainter(self.image)
        self.painter.drawImage(QRect(0.0,0.0,self.size[0],self.size[1]),image)

    def getImage(self):
        self.painter.end()
        return self.image
    def getPixmap(self):
        self.painter.end()
        return QPixmap.fromImage(self.image)




if __name__=="__main__":

    data=QEchogram()
    fileName="horizontal.png"
    data.echogram()
    dataH=data.data
    print "Horizontal data", dataH
2个回答

6

如果您能展示一下您目前的尝试,我可以给您更具体的答案,但现在我会做出一些假设并给您一个例子。

首先,您需要创建一个 QSlider。将 QSlider 的最小/最大值设置为您可用的图像范围。当您滑动它时,sliderMoved 信号 将触发并告诉您新的值。

接下来,您可以预先创建包含所有 QPixmap 图像的列表。如果这些图像很大,并且您担心内存问题,您可能需要使用您已编码的方法按需创建它们。但是我们现在假设您可以将它们放入列表中,以使示例更容易理解。

然后您创建自己的QGraphics设置,使用单个QGraphicsPixmapItem。此项可以根据需要替换其像素图。

将所有内容放在一起,您会得到类似于以下内容:

from PyQt4 import QtCore, QtGui

class Widget(QtGui.QWidget):

    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.resize(640,480)
        self.layout = QtGui.QVBoxLayout(self)

        self.scene = QtGui.QGraphicsScene(self)
        self.view = QtGui.QGraphicsView(self.scene)
        self.layout.addWidget(self.view)

        self.image = QtGui.QGraphicsPixmapItem()
        self.scene.addItem(self.image)
        self.view.centerOn(self.image)

        self._images = [
            QtGui.QPixmap('Smiley.png'),
            QtGui.QPixmap('Smiley2.png')
        ]

        self.slider = QtGui.QSlider(self)
        self.slider.setOrientation(QtCore.Qt.Horizontal)
        self.slider.setMinimum(0)
        # max is the last index of the image list
        self.slider.setMaximum(len(self._images)-1)
        self.layout.addWidget(self.slider)

        # set it to the first image, if you want.
        self.sliderMoved(0)

        self.slider.sliderMoved.connect(self.sliderMoved)

    def sliderMoved(self, val):
        print "Slider moved to:", val
        try:
            self.image.setPixmap(self._images[val])
        except IndexError:
            print "Error: No image at index", val

if __name__ == "__main__":
    app = QtGui.QApplication([])
    w = Widget()
    w.show()
    w.raise_()
    app.exec_()

您可以看到,我们设置滑块的范围以匹配您的图像列表。任何时候,如果您的图像列表内容发生更改,您都可以更改此范围。当 sliderMoved 触发时,它将使用该值作为图像列表的索引并设置 pixmap。
我还在我们的 sliderMoved() SLOT 中添加了一个检查,以防万一您的滑块范围与您的图像列表不同步。如果滑动到不存在于您的图像列表中的索引,则会优雅地失败并保留现有图像。

非常感谢,这是个了不起的帮助!说实话,我甚至不知道该从哪里开始。我添加了我编写的用于从二进制文件生成数据和图像的代码;我卡在了如何在每次移动滑块时生成新帧的数据(因此也就是新的图像)… - Victoria Price
@VictoriaPrice:我不太理解你的代码。你是如何通过代码选择不同的“图像”的?如果你能给我展示一个例子,我会用一个连接它们的例子来更新我的答案。 - jdi
抱歉!我是一个超级初学者(在大约一个月前之前没有任何编码经验)。我从声纳“相机”中开始使用二进制文件。我读取文件并将文件头信息、帧头信息和每个数据字符串分离到numpy数组中。然后,我使用Frame类numpy数组中的数据创建0-255位图像,并使用Echogram类。现在,我正在保存图像(主要是为了确保它能正常工作),但最终我需要遍历文件中的每个帧并创建图像。这有帮助吗? - Victoria Price
很遗憾,没有太多。我真正想知道的只是如何在需要时提取QPixmap帧的简单几行代码。这是很多需要盯着看并且努力理解的代码。你能否更新你的问题,用几行简单的示例说明如何使用它并提取一些QPixmaps? - jdi
此外,由于代码结构的原因,我很难跟上它。我完全理解你正在学习。如果你想更深入地讨论这个问题,我们可以开始聊天。 - jdi
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/13370/discussion-between-jdi-and-victoria-price - jdi

2
您正在完成的许多工作——将图像数据转换为QImage,使用滑块显示帧——可能通过使用为此目的编写的库来更好地解决。我可以想到几个使用PyQt并提供您所需一切的库:

(免责声明:无耻的自我宣传)

如果您可以将所有图像数据收集到单个3D numpy数组中,则在pyqtgraph中显示此数据的代码如下:

import pyqtgraph as pg
pg.image(imageData)

这将为您提供一个带有帧滑块和颜色查找表控件的可缩放图像显示。

谢谢!我会花些时间今天探索一下——看起来这可能正是我所需要的。 - Victoria Price
嗨,Luke,我在使用pyqtgraph时遇到了一些困难...当我尝试导入它时,出现了NameError: name asUnicode未定义类型错误。你有什么想法吗? - Victoria Price
嗯,我之前没见过。你能告诉我你下载的是哪个版本,以及你的操作系统和Python版本吗?(最好在邮件列表上讨论:https://groups.google.com/forum/?fromgroups#!forum/pyqtgraph ) - Luke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接