def homography_open_image_camera(self):
"""Opens a file dialog, allowing user to select an camera image file.
Creates a QImage object from the filename of an camera image
selected by the user in a popup file dialog menu.
"""
qi = self.open_image_fd(dialog_text="Select camera image...")
if qi:
self.ui.homography_cameraview.load_image(qi)
python类QImage()的实例源码
def homography_open_image_aerial(self):
"""Opens a file dialog, allowing user to select an aerial image file.
Creates a QImage object from the filename of an aerial image
selected by the user in a popup file dialog menu.
"""
qi = self.open_image_fd(dialog_text="Select aerial image...")
if qi:
self.ui.homography_aerialview.load_image(qi)
def load_image(self, image):
"""
Call this to load a new image from the provide QImage into
this HomographyView's scene. The image's top left corner will
be placed at (0,0) in the scene.
"""
self.scene_image = image
new_scene = QtWidgets.QGraphicsScene(self)
pmap = QtGui.QPixmap().fromImage(image)
pmapitem = new_scene.addPixmap(pmap)
new_scene.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(0, 0, 0)))
self.setScene(new_scene)
self.fitInView(0, 0, pmap.width(), pmap.height(), Qt.KeepAspectRatio)
self.show()
self.image_loaded = True
def load_image_from_path(self, path):
im = QtGui.QImage(path)
self.load_image(im)
def __init__(self, haar_cascade_filepath, parent=None):
super().__init__(parent)
self.classifier = cv2.CascadeClassifier(haar_cascade_filepath)
self.image = QtGui.QImage()
self._red = (0, 0, 255)
self._width = 2
self._min_size = (30, 30)
def get_qimage(self, image: np.ndarray):
height, width, colors = image.shape
bytesPerLine = 3 * width
QImage = QtGui.QImage
image = QImage(image.data,
width,
height,
bytesPerLine,
QImage.Format_RGB888)
image = image.rgbSwapped()
return image
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawImage(0, 0, self.image)
self.image = QtGui.QImage()
def __init__(self, haar_cascade_filepath, parent=None):
super().__init__(parent)
self.classifier = cv2.CascadeClassifier(haar_cascade_filepath)
self.image = QtGui.QImage()
self._red = (0, 0, 255)
self._width = 2
self._min_size = (30, 30)
def get_qimage(self, image: np.ndarray):
height, width, colors = image.shape
bytesPerLine = 3 * width
QImage = QtGui.QImage
image = QImage(image.data,
width,
height,
bytesPerLine,
QImage.Format_RGB888)
image = image.rgbSwapped()
return image
def __init__(self, parent=None):
super(ImageModel, self).__init__(parent)
self.modelImage = QImage()
def setImage(self, image):
self.beginResetModel()
self.modelImage = QImage(image)
self.endResetModel()
def openImage(self, fileName):
image = QImage()
if image.load(fileName):
self.model.setImage(image)
if not fileName.startswith(':/'):
self.currentPath = fileName
self.setWindowTitle("%s - Pixelator" % self.currentPath)
self.printAction.setEnabled(True)
self.updateView()
def loadFromMemory(self):
""" This slot function is called in the second Dialog process, when the
user presses the "Load Image from Shared Memory" button. First, it
attaches the process to the shared memory segment created by the first
Dialog process. Then it locks the segment for exclusive access, copies
the image data from the segment into a QBuffer, and streams the QBuffer
into a QImage. Then it unlocks the shared memory segment, detaches
from it, and finally displays the QImage in the Dialog.
"""
if not self.sharedMemory.attach():
self.ui.label.setText(
"Unable to attach to shared memory segment.\nLoad an "
"image first.")
return
buf = QBuffer()
ins = QDataStream(buf)
image = QImage()
self.sharedMemory.lock()
buf.setData(self.sharedMemory.constData())
buf.open(QBuffer.ReadOnly)
ins >> image
self.sharedMemory.unlock()
self.sharedMemory.detach()
self.ui.label.setPixmap(QPixmap.fromImage(image))
def changeIcon(self):
icon = QIcon()
for row in range(self.imagesTable.rowCount()):
item0 = self.imagesTable.item(row, 0)
item1 = self.imagesTable.item(row, 1)
item2 = self.imagesTable.item(row, 2)
if item0.checkState() == Qt.Checked:
if item1.text() == "Normal":
mode = QIcon.Normal
elif item1.text() == "Active":
mode = QIcon.Active
elif item1.text() == "Disabled":
mode = QIcon.Disabled
else:
mode = QIcon.Selected
if item2.text() == "On":
state = QIcon.On
else:
state = QIcon.Off
fileName = item0.data(Qt.UserRole)
image = QImage(fileName)
if not image.isNull():
icon.addPixmap(QPixmap.fromImage(image), mode, state)
self.previewArea.setIcon(icon)
def init_ui(self):
# v.box
gbox = QtWidgets.QGridLayout()
box = QtWidgets.QVBoxLayout()
self.rbox = QtWidgets.QVBoxLayout()
self.hbox = QtWidgets.QHBoxLayout()
# padding/margins
gbox.setContentsMargins(0, 0, 0, 0)
self.rbox.setContentsMargins(0, 0, 10, 10)
self.hbox.setContentsMargins(0, 0, 10, 10)
box.addStretch()
self.hbox.addStretch()
gbox.setSpacing(10)
box.setSpacing(0)
self.rbox.setSpacing(5)
self.hbox.setSpacing(0)
image = QtGui.QImage()
image.loadFromData(urllib.request.urlopen('http://i.imgur.com/04DUqa3.png').read())
png = QLabel(self)
pixmap = QtGui.QPixmap(image)
png.setPixmap(pixmap)
gbox.addWidget(png, 0, 0, 1, 1, Qt.AlignTop)
box.insertSpacing(1, 10)
self.l1 = QLabel(self)
self.l1.setWordWrap(True)
self.large_font.setBold(True)
self.l1.setFont(self.large_font)
box.addWidget(self.l1, 0, Qt.AlignTop)
hline = QtWidgets.QFrame()
hline.setFrameShape(QtWidgets.QFrame.HLine)
hline.setFrameShadow(QtWidgets.QFrame.Sunken)
gbox.addWidget(hline, 0, 0, 1, 3, Qt.AlignBottom)
# start form
self.req_ui()
self.rbox.setAlignment(Qt.AlignTop)
box.addLayout(self.rbox, 1)
gbox.addLayout(box, 0, 1, 1, 2)
gbox.addLayout(self.hbox, 1, 0, 1, 3)
self.setLayout(gbox)
# window
self.setFixedSize(490, 400)
self.setWindowIcon(QtGui.QIcon('red.ico'))
self.setWindowTitle('Red Discord Bot - Setup')
self.show()
def preview_image_file(self, path):
filename = path.split('/')[-1]
if self.graphics_preview is None:
msg = "Graphics preview widget not created yet."
logger.critical(msg)
return
if not self.isVisible():
msg = "Preview widget invisible, not previewing image."
logger.info(msg)
return
self.setCurrentWidget(self.graphics_preview)
scene = QtWidgets.QGraphicsScene(self)
self.graphics_preview.setScene(scene)
# Using QImage instead of directly creating the QPixmap
# prevents a segmentation fault in my container setup
image = QtGui.QImage(path)
if image.isNull():
fmt = "File '{}' should be an image, but isn't."
msg = fmt.format(filename)
logger.error(msg)
return
pixmap = QtGui.QPixmap.fromImage(image)
if pixmap.isNull():
fmt = "Failed to generate pixmap from image '{}'."
msg = fmt.format(filename)
logger.critical(msg)
return
pixmap_item = QtWidgets.QGraphicsPixmapItem(pixmap)
scene.addItem(pixmap_item)
self.graphics_preview.fitInView(
pixmap_item,
Qt.Qt.KeepAspectRatio,
)
fmt = "Previewed file '{}' as an image."
msg = fmt.format(filename)
logger.info(msg)
def handleSignals(self, signal, param):
if signal == 'Input.OnInputRequested':
self.showInputDialog()
print("Text sending")
if signal == 'Player.OnStop':
self.isPlaying = False
self.status.setText( 'Nothing playing now' )
self.img.setPixmap(QPixmap(IMG_PATH))
if self.timer.isActive():
self.timer.stop()
self.pbar.setValue(0)
print('Stoping timer')
if signal == 'play':
self.isPlaying = True
self.status.setText( param )
self.rpc("Player.GetItem",{"properties":["thumbnail","fanart"],"playerid":1}, True)
if not self.timer.isActive():
self.timer.start(1000, self)
print('Starting timer')
if signal == 'queue':
gui.rpc("GUI.ShowNotification",{"title":"Added to playlist!", "message":param}, False)
if signal == 'System.OnQuit' or signal == 'System.OnRestart':
if self.timer.isActive():
self.timer.stop()
print('Stoping timer')
self.quit(False)
if signal == 'thumbnail':
url = urllib.parse.unquote(param)
try:
img_arr = urllib.request.urlopen(url).read()
qImg = QImage()
qImg.loadFromData(img_arr)
self.img.setPixmap(QPixmap(qImg))
except Exception as e:
print("---> Error while getting image: %s" % e)
if signal == 'time':
tokens = param.split('-',1)
curTime = int(tokens[0])
totTime = int(tokens[1])
if totTime>0:
self.pbar.setValue((curTime/totTime)*100)
if signal == 'addons':
OpenDialog(param, self).exec_()
#print (signal)
def startCapture(self):
global currentSecond
global delayVideoData
#cap = self.capturer
num = 0
while(self.capturing):
while (self.paused and self.capturing):
time.sleep(0.05)
prevTime = datetime.now()
if (self.frameNumberChanged):
newFrameNumber = int(self.sliderVideoFrame.value()*30)
num = newFrameNumber
self.frameNumber = newFrameNumber
self.frameNumberChanged = False
frame = self.videoReader.get_data(num)
num = num+1
if (num >= self.videoReader.get_length()):
self.frameNumberChanged=True
self.sliderVideoFrame.setValue(0)
self.start_button.setText('Start')
self.video_thread = False
self.capturing = False
break
self.frameNumber = num
currentSecond = self.frameNumber/fps #valor importante para sync datos
self.labelCurrentVideoSecond.setText("{0:.1f}".format(currentSecond - delayVideoToData))
if (self.sliderWasReleased):
self.sliderVideoFrame.setValue(int(self.frameNumber/fps))
#Convert opencv mat to QImage:
imageQ = QtGui.QImage(frame.tostring(), frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888)
if (frame.shape[1] != videowidthShow or frame.shape[0] != videoheightShow):
imageQ = imageQ.scaled(videowidthShow, videoheightShow) #resize image to fit
#Convert QImage to pixmap:
pixmap = QtGui.QPixmap.fromImage(imageQ)
#Set pixmap to label:
#self.labelImage.setPixmap(pixmap) #old mode, cuidado porque es un thread outside the GUI, esto da problemas en pyqt
self.signalUpdatePixmap.emit(pixmap) #nuevo mode para evitar esos problemas
self.updateScoreLabels()
diftime = ((datetime.now()-prevTime).microseconds)/1000000.0
#print (diftime)
#print(1/fps - diftime )
if (diftime < 1/fps):
time.sleep (1/fps - diftime)
else:
time.sleep(0.01)
app.processEvents() #prevents app from crashing because of lack of responsiveness
def __init__(self,args,parent=None):
QtGui.QMainWindow.__init__(self,parent)
self.srclist=[] # list of source directories
self.imageIndex=0 # index of selected image
self.seriesMap=OrderedDict() # maps series table row tuples to DicomSeries object it was generated from
self.seriesColumns=list(seriesListColumns) # keywords for columns
self.selectedRow=-1 # selected series row
self.lastDir='.' # last loaded directory root
self.filterRegex='' # regular expression to filter tags by
# create the directory queue and loading thread objects
self.dirQueue=Queue() # queue of directories to load
self.loadDirThread=threading.Thread(target=self._loadDirsThread)
self.loadDirThread.daemon=True # clean shutdown possible with daemon threads
self.loadDirThread.start() # start the thread now, it will wait until something is put on self.dirQueue
# setup ui
self.setupUi(self) # create UI elements based on the loaded .ui file
self.setWindowTitle('DicomBrowser v%s (FOR RESEARCH ONLY)'%(__version__))
self.setStatus('')
# connect signals
self.importButton.clicked.connect(self._openDirDialog)
self.statusSignal.connect(self.setStatus)
self.updateSignal.connect(self._updateSeriesTable)
self.filterLine.textChanged.connect(self._setFilterString)
self.imageSlider.valueChanged.connect(self.setSeriesImage)
self.seriesView.clicked.connect(self._seriesTableClicked)
# setup the list and table models
self.srcmodel=QStringListModel()
self.seriesmodel=SeriesTableModel(self.seriesColumns)
self.seriesmodel.layoutChanged.connect(self._seriesTableResize)
self.tagmodel=QtGui.QStandardItemModel()
# assign models to views
self.sourceListView.setModel(self.srcmodel)
self.seriesView.setModel(self.seriesmodel)
self.tagView.setModel(self.tagmodel)
# create the pyqtgraph object for viewing images
self.imageview=pg.ImageView()
layout=QtGui.QGridLayout(self.view2DGroup)
layout.addWidget(self.imageview)
# load the empty image placeholder into a ndarray
qimg=QtGui.QImage(':/icons/noimage.png')
bytedata=qimg.constBits().asstring(qimg.width()*qimg.height())
self.noimg=np.ndarray((qimg.width(),qimg.height()),dtype=np.ubyte,buffer=bytedata)
# add the directories passed as arguments to the directory queue to start loading
for i in args:
if os.path.isdir(i):
self.addSourceDir(i)
def render_image(self, rect, image_path, dpm, quality, bg_color, autocrop):
"""Render a section of self.scene to an image.
It is assumed that all input arguments are valid.
Args:
rect (Rect): The part of the document to render,
in document coordinates.
image_path (str): The path to the output image.
This must be a valid path relative to the current
working directory.
dpm (int): The pixels per meter of the rendered image.
quality (int): The quality of the output image for compressed
image formats. Must be either `-1` (default compression) or
between `0` (most compressed) and `100` (least compressed).
bg_color (Color): The background color for the image.
autocrop (bool): Whether or not to crop the output image to tightly
fit the contents of the frame. If true, the image will be
cropped such that all 4 edges have at least one pixel not of
`bg_color`.
Returns: None
Raises:
ImageExportError: If Qt image export fails for unknown reasons.
"""
scale_factor = dpm / Unit(Meter(1)).value
pix_width = Unit(rect.width).value * scale_factor
pix_height = Unit(rect.height).value * scale_factor
q_image = QtGui.QImage(pix_width, pix_height,
QtGui.QImage.Format_ARGB32)
q_image.setDotsPerMeterX(dpm)
q_image.setDotsPerMeterY(dpm)
q_color = color_to_q_color(bg_color)
q_image.fill(q_color)
painter = QtGui.QPainter()
painter.begin(q_image)
target_rect = QtCore.QRectF(q_image.rect())
source_rect = rect_to_qt_rect_f(rect)
self.scene.render(painter, target=target_rect, source=source_rect)
painter.end()
if autocrop:
q_image = images.autocrop(q_image, q_color)
success = q_image.save(image_path, quality=quality)
if not success:
raise ImageExportError(
'Unknown error occurred when exporting image to ' + image_path)