gpt4 book ai didi

pyqt - 在 PyQt 中将 slider 连接到图形 View

转载 作者:行者123 更新时间:2023-12-02 07:40:53 32 4
gpt4 key购买 nike

我正在尝试显示从二进制文件中读取的图像数据(我编写了用于从文件中检索此数据并将其存储为图像以供 QImage() 使用的代码)。我想做的是将 slider 连接到图形 View 小部件,以便当您移动 slider 时,它会在帧中移动并显示该帧中的图像(这些是长度范围为 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

最佳答案

如果你展示了你到目前为止的尝试,我可以给你一个更具体的答案,但现在我只是做出假设并给你一个例子。

首先你要做的是创建一个 QSlider .您将 QSlider 最小值/最大值设置为您可用的图像范围。滑动时,sliderMoved signal将触发并告诉您新值是什么。

接下来,您可以创建一个列表,其中包含您所有的 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_()

您可以看到我们设置了 slider 的范围以匹配您的图像列表。如果图像列表的内容发生变化,您可以随时更改此范围。当 sliderMoved 触发时,它将使用该值作为图像列表的索引并设置像素图。

我还在我们的 sliderMoved() SLOT 中添加了一个检查,以防您的 slider 范围与您的图像列表不同步。如果您滑动到图像列表中不存在的索引,它将正常失败并离开现有图像。

关于pyqt - 在 PyQt 中将 slider 连接到图形 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11250110/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com