def show(self): self.view = QWidget() mainLayout = QVBoxLayout() self.view.setLayout(mainLayout) transformsLayout = QHBoxLayout() mainLayout.addLayout(transformsLayout) for key, value in self.transforms.iteritems(): transrormLayout = QVBoxLayout() transformsLayout.addLayout(transrormLayout) header = QLabel(key) image = QLabel() image.setPixmap(QPixmap.fromImage(Ipl2QIm(value))) transrormLayout.addWidget(header) transrormLayout.addWidget(image) for symbol in self.symbols: transformsLayout = QHBoxLayout() mainLayout.addLayout(transformsLayout) for key, value in symbol.transforms.iteritems(): transrormLayout = QVBoxLayout() transformsLayout.addLayout(transrormLayout) header = QLabel(key) image = QLabel() image.setPixmap(QPixmap.fromImage(Ipl2QIm(value))) transrormLayout.addWidget(header) transrormLayout.addWidget(image) self.view.show()
def fileOpen(self): """ open a HDF5 file, show pictures as tabs """ fname = QFileDialog.getOpenFileName(self, "Open data file", ".", "HDF5 files (*.h5, *.hdf5)") if not fname: return import h5py f = h5py.File(str(fname), "r") for grp in f.keys(): for img in f[grp].keys(): ds1 = f[grp][img] # if ds1.get('attr', None) is None: continue if ds1.attrs.get("CLASS", None) != "IMAGE": continue # the fourth alpha, needs be 255. d1 = np.ones(ds1.shape[:2] + (4,), dtype=np.uint8) * 255 d1[:, :, :3] = np.asarray(ds1) wid = QWidget() l = QVBoxLayout(wid) imageLabel = QLabel(self) imageLabel.setText("Text") # imageLabel im1 = Image.fromarray(d1) pxm = QPixmap.fromImage(ImageQt.ImageQt(im1)) # pxm.save("j.png") imageLabel.setPixmap(pxm) imageLabel.adjustSize() l.addWidget(imageLabel) self.widtab.addTab(wid, "%s:%s" % (grp, img)) f.close()
def __init__(self, parent, color, shape): super(Piece, self).__init__(parent) self.color = color self.shape = shape cells = [QRect(11*x, 11*y, 11, 11) for x,y in self.cellCoor[self.shape]] self.setFixedSize(QSize(100, 100)) self.setCheckable(True) self.i = QImage(56, 56, QImage.Format_ARGB32) self.i.fill(0x000000FF) p = QPainter(self.i) p.setBrush(self.colors[self.color]) p.setPen(QColor(255, 255, 255, 255)) p.drawRects(cells) self.setIconSize(QSize(56, 56)) self.setIcon(QIcon(QPixmap.fromImage(self.i))) self.fliped = False self.rotated = 0 self.d = QImage(256, 256, QImage.Format_ARGB32) self.updateImage()
def __init__(self, images, scales, images_path, *args): QDialog.__init__(self, *args) cache = image_cache.cache self.ui = Ui_EditResDlg() self.ui.setupUi(self) icons = [] for pth in images_path: ico = QIcon(QPixmap.fromImage(cache.image(pth).scaled(QSize(64, 64), Qt.KeepAspectRatio))) icons.append(ico) self.model = ScaleModel(icons, images, scales) self.ui.pixelSizes.setModel(self.model) self.ui.pixelSizes.resizeColumnToContents(0) self.ui.pixelSizes.resizeColumnToContents(1) self.ui.pixelSizes.resizeColumnToContents(2) self.item_delegate = QItemDelegate() self.item_delegate.setItemEditorFactory(ScaleEditorFactory()) self.ui.pixelSizes.setItemDelegate(self.item_delegate) self.ui.width.setValidator(QDoubleValidator(0, 1e300, 100, self)) self.ui.height.setValidator(QDoubleValidator(0, 1e300, 100, self)) # Find smallest scale minx = inf miny = inf for img in scales: sc = scales[img] if sc[0] > 0 and sc[0] < minx: minx = sc[0] if sc[1] > 0 and sc[1] < miny: miny = sc[1] if minx == inf: minx = 1e-6 if miny == inf: miny = 1e-6 # And set the default unit self.ui.unit.setCurrentIndex(self.model.findUnit(min(minx, miny)))
def __init__(self, *a, **kw): super(EmzedDialog, self).__init__(*a, **kw) data = pkg_resources.resource_string("emzed.workbench", "icon64.png") img = QImage() img.loadFromData(data) pixmap = QPixmap.fromImage(img) self.setWindowIcon(QIcon(pixmap))
def pixmap(name, size, mode, state): """Returns a (possibly cached) pixmap of the name and size with the default text color. The state argument is ignored for now. """ if mode == QIcon.Selected: color = QApplication.palette().highlightedText().color() else: color = QApplication.palette().text().color() key = (name, size.width(), size.height(), color.rgb(), mode) try: return _pixmaps[key] except KeyError: i = QImage(size, QImage.Format_ARGB32_Premultiplied) i.fill(0) painter = QPainter(i) # render SVG symbol QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter) # recolor to text color painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(i.rect(), color) painter.end() # let style alter the drawing based on mode, and create QPixmap pixmap = QApplication.style().generatedIconPixmap(mode, QPixmap.fromImage(i), QStyleOption()) _pixmaps[key] = pixmap return pixmap
def pix(self, pix): self.ui.imageView.setEnabled(True) self._pix = pix if self.pix_item is not None: self.scene.removeItem(self.pix_item) self.pix_item = self.scene.addPixmap(QPixmap.fromImage(pix)) self.scene.setSceneRect(QRectF(self.pix.rect())) if self.show_pic_w: self.show_pic_w.close() self.show_pic_w = None if self.pic_w: self.show_pic_w = QLabel(self, Qt.Window) #self.show_pic_w.setAttribute(Qt.WA_DeleteOnClose) self.show_pic_w.setPicture(self.pic_w) self.show_pic_w.show() self.show_pic_w.raise_() if self.show_pic_c: self.show_pic_c.close() self.show_pic_c = None if self.pic_c: self.show_pic_c = QLabel(self, Qt.Window) #self.show_pic_c.setAttribute(Qt.WA_DeleteOnClose) self.show_pic_c.setPicture(self.pic_c) self.show_pic_c.show() self.show_pic_c.raise_() log_debug("Received image")
def rotate(self, angle): matrix = QMatrix() matrix.rotate(angle) self.currentImage = self.currentImage.transformed(matrix) self.baseImage = self.baseImage.transformed(matrix) self.setPixmap(QPixmap.fromImage(self.currentImage)) self.adjustSize()
def __init__(self, parent, canvasLayer): QTreeWidgetItem.__init__(self) self.legend = parent self.canvasLayer = canvasLayer self.canvasLayer.layer().setLayerName( self.legend.normalizeLayerName( unicode( self.canvasLayer.layer().name() ) ) ) self.setText(0, self.canvasLayer.layer().name()) self.isVect = (self.canvasLayer.layer().type() == 0) # 0: Vector, 1: Raster self.layerId = self.canvasLayer.layer().id() self.setSizeHint(0, QSize(24, 24)) self.setCheckState(0, Qt.Checked) pm = QPixmap(22, 22) icon = QIcon() if self.isVect: renderer = self.canvasLayer.layer().rendererV2() sym = renderer.symbols()[0] img = QImage(sym.asImage(QSize(22, 22))) pix = pm.fromImage(img) icon.addPixmap(pix, QIcon.Normal, QIcon.On) self.vectorLayerSymbology(self.canvasLayer.layer()) else: pm = self.canvasLayer.layer().previewAsPixmap(QSize(22, 22)) icon.addPixmap(pm) self.rasterLayerSymbology(self.canvasLayer.layer()) self.setIcon(0, icon) self.setToolTip(0, self.canvasLayer.layer().attribution()) layerFont = QFont() layerFont.setBold(True) self.setFont(0, layerFont)
def reinit(self, sliceSize): self.imagesize = QSize(int(sliceSize[0] * self.grid[0]), int(sliceSize[1] * self.grid[1])) self.slice_size = sliceSize self.ctslice_rgba = None self.seeds = None self.contours = None self.contours_old = None self.mask_points = None self.image = QImage(self.imagesize, QImage.Format_RGB32) self.setPixmap(QPixmap.fromImage(self.image)) self.setScaledContents(True) # def set_data(self, data, type): # self.data = data # self.n_slices, self.n_rows, self.n_cols = data.shape # self.type = type # # self.imagesize = QSize(int(self.n_rows * self.grid[0]), # int(self.n_cols * self.grid[1])) # self.slice_size = (self.n_rows, self.n_cols) # def set_slice_size(self, sliceSize): # self.imagesize = QSize(sliceSize[0], sliceSize[1]) # self.slice_size = sliceSize # # self.seeds = None # self.contours = None # self.contours_old = None # self.mask_points = None # # self.image = QImage(self.imagesize, QImage.Format_RGB32) # self.setPixmap(QPixmap.fromImage(self.image)) self.setScaledContents(True)
def _setThumbnail(self, item, cat, aTuple): image, adding = aTuple icon = QIcon(QPixmap.fromImage(image)) item.setData(QVariant(icon), Qt.DecorationRole) self._categoryIcons[cat] = icon if adding: self.categoriesChanged.emit()
def update_webcam_image(self): if not self.isVisible(): if self.cap is not None: self.cap.release() self.cap = None return if self.cap is None: # Try capture devices in LIFO order for dev in range(5, -1, -1): cap = self.cap = cv2.VideoCapture(dev) if cap.isOpened(): break cap = self.cap self.capture_button.setDisabled(not cap.isOpened()) success, frame = cap.read() if not cap.isOpened() or not success: self.Error.no_webcam() return else: self.Error.no_webcam.clear() if self.snapshot_flash > 0: np.clip(frame.astype(np.int16) + self.snapshot_flash, 0, 255, out=frame) self.snapshot_flash -= 15 image = QImage(frame if self.avatar_filter else self.bgr2rgb(frame), frame.shape[1], frame.shape[0], QImage.Format_RGB888) pix = QPixmap.fromImage(image).scaled(self.imageLabel.size(), Qt.KeepAspectRatio | Qt.FastTransformation) self.imageLabel.setPixmap(pix)
def getProtoStatusIcon(name, proto_int=None): """Creates a nice little overlay of the status and the protocol icon. Returns QIcon""" status_icon = getIcon(name) if not proto_int: return status_icon else: ret = _status_icon_cache.get((name, proto_int), None) if ret: return ret proto_name, _ = proto_name_int(proto_int, _PROTO_INT) status_pixmap = status_icon.pixmap(QSize(16,16)) proto_pixmap = getIcon(proto_name).pixmap(QSize(16,16)) combined_pixmap = QImage(28,20, QImage.Format_ARGB32_Premultiplied) painter = QPainter(combined_pixmap) painter.setCompositionMode(painter.CompositionMode_Source) painter.fillRect(combined_pixmap.rect(), Qt.transparent) painter.setCompositionMode(painter.CompositionMode_Source) painter.drawPixmap(QPoint(0,0), status_pixmap) painter.setCompositionMode(painter.CompositionMode_SourceOver) painter.drawPixmap(QPoint(12,4), proto_pixmap) painter.end() #add cache _status_icon_cache[(name, proto_int)] = QIcon(QPixmap.fromImage(combined_pixmap)) return _status_icon_cache[(name, proto_int)]
def __init__( self ): QDialog.__init__( self ) self.ui = Ui_Dialog() self.ui.setupUi( self ) self.cb = self.ui.exerciseComboBox self.sb = self.ui.weightSpinBox self.table = self.ui.exerciseTable self.splitbox = self.ui.splitplanComboBox self.ui.cancelButton.clicked.connect( self.reject ) self.ui.okButton.clicked.connect( self.commit ) self.ui.addButton.clicked.connect( self.addExerciseItem ) self.ui.deleteButton.clicked.connect( self.deleteItem ) self.splitbox.currentIndexChanged.connect( self.fillSplitTable ) self.ui.updateButton.clicked.connect( self.fillSplitTable ) self.ui.dateTimeEdit.setDateTime( QDateTime.currentDateTime() ) self.weightPlot = QImage( "data/weight_plot.png" ) self.ui.imageLabel = QLabel() self.ui.imageLabel.setPixmap( QPixmap.fromImage( self.weightPlot ) ) self.ui.scrollArea.setWidget( self.ui.imageLabel ) self.con = sqlite3.connect( "data/db" ) self.con.row_factory = sqlite3.Row self.con.isolation_level = None self.cur = self.con.cursor() self.dbExercises() self.dbSplit() layout = QVBoxLayout(self) layout.addWidget(self.ui.tabWidget)
def __init__(self, weboob, backend, parent=None): QFrame.__init__(self, parent) self.setFrameShape(QFrame.StyledPanel) self.setFrameShadow(QFrame.Raised) self.weboob = weboob self.backend = backend self.setLayout(QVBoxLayout()) self.timer = None head = QHBoxLayout() headw = QWidget() headw.setLayout(head) self.title = QLabel(u'<h1>%s — %s</h1>' % (backend.name, backend.DESCRIPTION)) self.body = QLabel() if backend.ICON: self.icon = QLabel() img = QImage(backend.ICON) self.icon.setPixmap(QPixmap.fromImage(img)) head.addWidget(self.icon) head.addWidget(self.title) head.addStretch() self.layout().addWidget(headw) if backend.has_caps(ICapAccount): self.body.setText(u'<i>Waiting...</i>') self.layout().addWidget(self.body) self.timer = self.weboob.repeat(60, self.updateStats)
def data(self, index, role): if role == Qt.EditRole and index.column() == self.ColumnID.Color: return (self._elements[index.row()].brushColor(), self._elements[index.row()].pmapColor()) elif role == Qt.ToolTipRole and index.column() == self.ColumnID.Color: return ("Hex code : {}\nDouble click to change".format( self._elements[index.row()].brushColor().name())) elif role == Qt.DecorationRole and index.column() == self.ColumnID.Color: row = index.row() value = self._elements[row] if value.brushColor == value.pmapColor(): pixmap = QPixmap(_NPIXELS, _NPIXELS) pixmap.fill(value.brushColor) else: a = value.brushColor().rgba() b = value.pmapColor().rgba() img = QImage(_NPIXELS,_NPIXELS, QImage.Format_RGB32) for i in range(_NPIXELS): for j in range(0, _NPIXELS - i): img.setPixel(i, j, a) for i in range(_NPIXELS): for j in range(_NPIXELS - i, _NPIXELS): img.setPixel(i, j, b) pixmap = QPixmap.fromImage(img) icon = QIcon(pixmap) return icon else: return ListModel.data(self,index,role)
def addTestImage(self, color_image): self.ocr_areas = OCRAreasFinder(color_image, self.settings["contrast"]) self.market_width = self.ocr_areas.market_width self.valid_market = self.ocr_areas.valid if self.settings['gray_preview']: img = cv2.imread(unicode(self.hiddentext).encode(sys.getfilesystemencoding()), 0) img = array2qimage(img) pix = QPixmap.fromImage(img) else: pix = QPixmap(self.hiddentext) width = pix.width() height = pix.height() if height > 0: aspect_ratio = float(width)/height if aspect_ratio > 1.78: new_w = int(1.77778*height) rect = QRect((width-new_w)/2, 0, new_w, height) pix = pix.copy(rect) if self.valid_market: points = self.ocr_areas.market_table self.market_offset = (points[0][0], points[0][1]) station = self.ocr_areas.station_name self.station_offset = (station[0][0], station[0][1]) rect = QRect(0, 0, points[1][0] + 20, points[1][1] + 20) cut = pix.copy(rect) return cut else: self.market_offset = (0, 0) self.station_offset = (0, 0) return pix
def gotThumbnail(self): if empty(self.movie.thumbnail_url) and self.movie.thumbnail_url != NotAvailable: self.backend.fill_movie(self.movie, ('thumbnail_url')) if not empty(self.movie.thumbnail_url): data = urllib.urlopen(self.movie.thumbnail_url).read() img = QImage.fromData(data) self.ui.imageLabel.setPixmap(QPixmap.fromImage(img).scaledToHeight(100,Qt.SmoothTransformation))
def updateImage(self): if self.image_group == -1: return super(MWTrackerViewerSingle_GUI,self).readImage() self.img_h_ratio = self.frame_qimg.height()/self.image_height; self.img_w_ratio = self.frame_qimg.width()/self.image_width; #read the data of the particles that exists in the frame if isinstance(self.traj_time_grouped, pd.core.groupby.DataFrameGroupBy): try: self.frame_data = self.traj_time_grouped.get_group(self.frame_number) self.frame_data = self.frame_data[self.frame_data[self.worm_index_type] >= 0] except KeyError: self.frame_data = -1 #draw the boxes in each of the trajectories found if self.ui.checkBox_showLabel.isChecked(): self.drawROIBoxes(self.frame_qimg) #create the pixmap for the label pixmap = QPixmap.fromImage(self.frame_qimg) self.ui.imageCanvas.setPixmap(pixmap); self.updateROIcanvasN(1) self.updateROIcanvasN(2)
def display_photo(self): if not self.housing.photos: self.ui.photosFrame.hide() return if self.displayed_photo_idx >= len(self.housing.photos): self.displayed_photo_idx = len(self.housing.photos) - 1 if self.displayed_photo_idx < 0: self.ui.photosFrame.hide() return self.ui.photosFrame.show() photo = self.housing.photos[self.displayed_photo_idx] if photo.data: data = photo.data if photo.id in self.process_photo: self.process_photo.pop(photo.id) else: self.process_photo[photo.id] = QtDo(self.weboob, lambda b,p: self.display_photo()) self.process_photo[photo.id].do('fillobj', photo, ['data'], backends=self.housing.backend) return img = QImage.fromData(data) img = img.scaledToWidth(self.width()/3) self.ui.photoLabel.setPixmap(QPixmap.fromImage(img)) if photo.url is not NotLoaded: text = '<a href="%s">%s</a>' % (photo.url, photo.url) self.ui.photoUrlLabel.setText(text)
def display_photo(self): if self.displayed_photo_idx >= len(self.contact.photos): self.displayed_photo_idx = len(self.contact.photos) - 1 if self.displayed_photo_idx < 0: self.ui.photoUrlLabel.setText('') return photo = self.contact.photos.values()[self.displayed_photo_idx] if photo.data: data = photo.data if photo.id in self.process_photo: self.process_photo.pop(photo.id) else: self.process_photo[photo.id] = QtDo(self.weboob, lambda b,p: self.display_photo()) self.process_photo[photo.id].do('fillobj', photo, ['data'], backends=self.contact.backend) if photo.thumbnail_data: data = photo.thumbnail_data else: return img = QImage.fromData(data) img = img.scaledToWidth(self.width()/3) self.ui.photoLabel.setPixmap(QPixmap.fromImage(img)) if photo.url is not NotLoaded: text = '<a href="%s">%s</a>' % (photo.url, photo.url) if photo.hidden: text += '<br /><font color=#ff0000><i>(Hidden photo)</i></font>' self.ui.photoUrlLabel.setText(text)
def QIcon_from_Icon(icon): """ Convert the given Enaml Icon into a QIcon. Parameters ---------- icon : Icon The Enaml Icon object. Returns ------- result : QIcon The QIcon instance for the given Enaml icon. """ qicon = QIcon() for icon_image in icon.images: image = icon_image.image if not image: continue mode = ICON_MODE[icon_image.mode] state = ICON_STATE[icon_image.state] qimage = get_cached_qimage(image) qpixmap = QPixmap.fromImage(qimage) qicon.addPixmap(qpixmap, mode, state) return qicon
def gotThumbnail(self, backend, video): if not backend: return if video.thumbnail and video.thumbnail.data: img = QImage.fromData(video.thumbnail.data) self.ui.imageLabel.setPixmap(QPixmap.fromImage(img))
def show_image(self, item): """"Display the selected image""" self.current_index = self.list_view.indexFromItem(item).row() self.scene.addPixmap((QPixmap.fromImage(QImage(item.text()))).scaled(self.viewer.size())) self.stackedWidget.setCurrentIndex(1) self.mode = "viewer"
def update_preview_size(self): if self.preview_image.isNull(): return label_size = self.lbl_image_preview.size() resized_pixmap = QPixmap.fromImage(self.preview_image).scaled(label_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.lbl_image_preview.setPixmap(resized_pixmap)
def _setImage(self, selectedFile, label): from PyQt4.QtGui import QImage, QPixmap from PyQt4.QtCore import Qt from avatar.l_avatar import l_avatar qimg = QImage(selectedFile) pixmap = QPixmap.fromImage(qimg).scaled(l_avatar.width,l_avatar.height,Qt.KeepAspectRatio,Qt.SmoothTransformation) label.setPixmap(pixmap) label.setToolTip(selectedFile)
def updateTransforms(self): if not self.baseImage.isNull(): self.currentImage = self.baseImage.transformed(self.matrix).scaled(QSize(self.curWidth, self.curHeight), Qt.KeepAspectRatio, Qt.FastTransformation) self.setPixmap(QPixmap.fromImage(self.currentImage)) else: self.clear() self.setText("File is too big to be processed") self.adjustSize()
def updateAvatar(self, avatarData): image = QImage.fromData(avatarData) pixmap = QPixmap.fromImage(image) if pixmap.isNull(): return False scaledAvatar = pixmap.scaled(32, 32) self.avatarLabel.setPixmap(scaledAvatar) return True
def showimage(self): if self.cam is None: return img = self.cam.getImage() self.image = ImageQt(img) pixmap = QPixmap.fromImage(self.image) self.cameralabel.setPixmap(pixmap)
def pixmap(self, size): """Returns (and caches) a scaled pixmap for the image.""" if self._pixmapsize == size: return self._pixmap self._pixmap = QPixmap.fromImage( self._image.scaled(size, Qt.KeepAspectRatio, Qt.SmoothTransformation)) self._pixmapsize = size return self._pixmap
def btnConfirmClicked(self): # check if PIN code corresponds to PIN code stored in database (use SHA-256 to hash passwords!) cursor = self._mysqldb_connection.cursor() query_str = "select * from tblUser where userID='" + self._rfid + "'" cursor.execute(query_str) if cursor.rowcount != 1: self.lblWrongPINCode.setVisible(True) cursor.close() return # fetch (only) matching row from DB tblUser_row = cursor.fetchone() # hash pin entered by user with salt string from DB pincode_hash = SHA256.new(str(self.lnPINCode.text()) + str(tblUser_row[4])).hexdigest().upper() #print pincode_hash if pincode_hash == tblUser_row[3]: # permit access to user and enable widgets accordingly self.lblWrongPINCode.setVisible(False) self.tabWidget.setTabEnabled(1, True) self.tabWidget.setTabEnabled(2, True) self.tabWidget.setTabEnabled(3, True) self.tabWidget.setTabEnabled(4, True) self.lblAuth.setEnabled(False) self.lblPINCode.setEnabled(False) self.lnPINCode.setEnabled(False) self.btnConfirm.setEnabled(False) self.lblHelloMsg.setVisible(True) self.lblHelloMsg.setText("Welcome back, " + tblUser_row[2] + "!") self.lblRemove.setVisible(True) self.grProfilePicture.setVisible(True) self.grProfilePicture.setEnabled(True) scene = QGraphicsScene() qimg = QtGui.QImage.fromData(tblUser_row[6]) pixmap = QGraphicsPixmapItem(QPixmap.fromImage(qimg), None, scene) self.grProfilePicture.setScene(scene) self.grProfilePicture.fitInView(scene.sceneRect(), Qt.KeepAspectRatio) self.grProfilePicture.setVisible(True) self._encourager.say("Welcome back, " + tblUser_row[2] + "!") self._encourager.show_emotion("happy") ### HARDCODED: display different information depending on user connected ### if self._rfid == "3BEA00008131FE450031C573C0014000900077": self.slNbrBlocks.setValue(3) self.spnNbrRepetitions.setValue(25) self.chkQualitative.setChecked(False) self.chkQuantitative.setChecked(True) self.spnQuantEncRep.setEnabled(True) self.cmbQualiEnc.setEnabled(False) self.spnQuantEncRep.setValue(3) else: self.slNbrBlocks.setValue(2) self.spnNbrRepetitions.setValue(15) self.chkQualitative.setChecked(True) self.chkQuantitative.setChecked(True) self.spnQuantEncRep.setEnabled(True) self.spnQuantEncRep.setValue(2) self.cmbQualiEnc.setEnabled(True) self.cmbQualiEnc.setCurrentIndex(1) #launch_params = ['roslaunch', 'simple_image_cyphering', 'one_node_decryption.launch'] #self._decryption_node = Popen(launch_params) else: self.lblWrongPINCode.setVisible(True) cursor.close()
def __init__(self, geoservice, image_ba, parent=None): QWidget.__init__(self, parent) self.layout = QHBoxLayout(self) # self.layout.addSpacing(0) self.layout.setContentsMargins(5, 10, 5, 10) self.setLayout(self.layout) self.service_icon = QLabel(self) self.service_icon.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.service_icon.resize(24, 24) qimg = QImage.fromData(image_ba) pixmap = QPixmap.fromImage(qimg) self.service_icon.setPixmap(pixmap) self.layout.addWidget(self.service_icon) self.service_desc_layout = QGridLayout(self) self.service_desc_layout.setSpacing(0) self.layout.addLayout(self.service_desc_layout) self.service_name = QLabel(self) self.service_name.setTextFormat(Qt.RichText) self.service_name.setWordWrap(True) self.service_name.setText(u" <strong> {} </strong>".format( geoservice.get('name', u""))) self.service_desc_layout.addWidget(self.service_name, 0, 0, 1, 3) self.service_type = QLabel(self) self.service_type.setTextFormat(Qt.RichText) self.service_type.setWordWrap(True) self.service_type.setText(geoservice.get('type', u"").upper() + " ") self.service_desc_layout.addWidget(self.service_type, 1, 0) self.service_deteils = QLabel(self) self.service_deteils.setTextFormat(Qt.RichText) self.service_deteils.setWordWrap(True) self.service_deteils.setOpenExternalLinks(True) self.service_deteils.setText(u"<a href=\"{}\">details</a>, ".format( Client().geoservice_info_url(geoservice.get('id', u"")))) self.service_desc_layout.addWidget(self.service_deteils, 1, 1) self.service_report = QLabel(self) self.service_report.setTextFormat(Qt.RichText) self.service_report.setWordWrap(True) self.service_report.setOpenExternalLinks(True) self.service_report.setText( u"<a href=\"{}\">report a problem</a><div/>".format( Client().geoservice_report_url(geoservice.get('id', u"")))) self.service_desc_layout.addWidget(self.service_report, 1, 2) self.service_desc_layout.setColumnStretch(2, 1) # self.service_desc = QLabel(self) # self.service_desc.setTextFormat(Qt.RichText) # self.service_desc.setOpenExternalLinks(True) # self.service_desc.setWordWrap(True) # self.service_desc.setText( # u"<strong> {} </strong><div style=\"margin-top: 3px\">{}, <a href=\"{}\">details</a>, <a href=\"{}\">report</a><div/>".format( # # "{}<div style=\"margin-top: 3px\"> <em> {} </em>, <a href=\"{}\"> details <a/> <div/>".format( # geoservice.get('name', u""), # geoservice.get('type', u"").upper(), # Client().geoservice_info_url(geoservice.get('id', u"")), # Client().geoservice_report_url(geoservice.get('id', u"")) # ) # ) # self.layout.addWidget(self.service_desc) self.addButton = QToolButton() self.addButton.setText("Add") self.addButton.clicked.connect(self.addToMap) self.layout.addWidget(self.addButton) self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum) self.geoservice = geoservice self.image_ba = image_ba
def video_input(self, image): self.label.setPixmap(QPixmap.fromImage(image))
def show_fullscreen_image(self, image): """:param image: a QImage""" pixmap = QPixmap.fromImage(image) item = QGraphicsPixmapItem(pixmap) self.show_fullscreen_item(item)
def set_image(self, frame): img = QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888) pix = QPixmap.fromImage(img) self.label_image.setPixmap(pix)
def setupScene(self): self.error() if self.data: attr = self.stringAttrs[self.imageAttr] titleAttr = self.allAttrs[self.titleAttr] instances = [inst for inst in self.data if numpy.isfinite(inst[attr])] assert self.thumbnailView.count() == 0 size = QSizeF(self.imageSize, self.imageSize) for i, inst in enumerate(instances): url = self.urlFromValue(inst[attr]) title = str(inst[titleAttr]) thumbnail = GraphicsThumbnailWidget(QPixmap(), title=title) thumbnail.setThumbnailSize(size) thumbnail.setToolTip(url.toString()) thumbnail.instance = inst self.thumbnailView.addThumbnail(thumbnail) if url.isValid() and url.isLocalFile(): reader = QImageReader(url.toLocalFile()) image = reader.read() if image.isNull(): error = reader.errorString() thumbnail.setToolTip( thumbnail.toolTip() + "\n" + error) self._errcount += 1 else: pixmap = QPixmap.fromImage(image) thumbnail.setPixmap(pixmap) self._successcount += 1 future = Future() future.set_result(image) future._reply = None elif url.isValid(): future = self.loader.get(url) @future.add_done_callback def set_pixmap(future, thumb=thumbnail): if future.cancelled(): return assert future.done() if future.exception(): # Should be some generic error image. pixmap = QPixmap() thumb.setToolTip(thumb.toolTip() + "\n" + str(future.exception())) else: pixmap = QPixmap.fromImage(future.result()) thumb.setPixmap(pixmap) self._noteCompleted(future) else: future = None self.items.append(_ImageItem(i, thumbnail, url, future)) if any(it.future is not None and not it.future.done() for it in self.items): self.info.setText("Retrieving...\n") else: self._updateStatus()
img_array = np.zeros([height, width, 4], dtype=np.uint8) #for some strange reason PyQt4 needs to use RGB as BGR img_array[:, :, 0:1] = np_img_array[:, :, 2:3] img_array[:, :, 1:2] = np_img_array[:, :, 1:2] img_array[:, :, 2:3] = np_img_array[:, :, 0:1] print "end of np generator" return img_array #building array arr_i = img_arr_n_cpp() #converting to QImage print "before QImage generator" q_img = QImage(arr_i.data, np.size(arr_i[0:1, :, 0:1]), np.size(arr_i[:, 0:1, 0:1]), QImage.Format_RGB32) print "after QImage generator" #building app with IMG app = QApplication([]) pix = QPixmap.fromImage(q_img) lbl = QLabel() lbl.setPixmap(pix) lbl.show() app.exec_()
def updateImage(self): self.readImage() self.drawSkelResult() self.pixmap = QPixmap.fromImage(self.frame_qimg) self.ui.imageCanvas.setPixmap(self.pixmap)
def gotThumbnail(self): if not empty(self.person.thumbnail_url): data = urllib.urlopen(self.person.thumbnail_url).read() img = QImage.fromData(data) self.ui.imageLabel.setPixmap(QPixmap.fromImage(img).scaledToWidth(220,Qt.SmoothTransformation))
def resize(self, zoomer): w = self.currentImage.width() * zoomer self.currentImage = self.baseImage.scaled(QSize(w, w), Qt.KeepAspectRatio, Qt.FastTransformation) self.setPixmap(QPixmap.fromImage(self.currentImage)) self.adjustSize()
def create_rows(self, layout, sarea): u"""Build the rows of the dialog box""" play_button_group = QButtonGroup(sarea) old_play_button_group = QButtonGroup(sarea) for num, entry in enumerate(self.entries_list, 2): tt_text = self.build_text_help_label(entry) ico_label = QLabel('', sarea) ico_label.setToolTip(tt_text) if entry.icon: ico_label.setPixmap(QPixmap.fromImage(entry.icon)) layout.addWidget(ico_label, num, 0) tt_label = QLabel(entry.display_word, sarea) tt_label.setToolTip(tt_text) layout.addWidget(tt_label, num, 1) if self.hide_text: tt_label.hide() # Play button. t_play_button = QPushButton(sarea) play_button_group.addButton(t_play_button, num-2) t_play_button.setToolTip(self.play_help) t_play_button.setIcon(QIcon(os.path.join(icons_dir, 'play.png'))) layout.addWidget(t_play_button, num, self.play_column) if self.note[entry.audio_field_name]: t_play_old_button = QPushButton(sarea) old_play_button_group.addButton(t_play_old_button, num-2) t_play_old_button.setIcon( QIcon(os.path.join(icons_dir, 'play.png'))) if not self.hide_text: t_play_old_button.setToolTip( self.note[entry.audio_field_name]) else: t_play_old_button.setToolTip(self.play_old_help_short) layout.addWidget(t_play_old_button, num, self.play_old_column) else: dummy_label = QLabel('', sarea) dummy_label.setToolTip(self.play_old_empty_line_help) layout.addWidget(dummy_label, num, self.play_old_column) # The group where we later look what to do: t_button_group = QButtonGroup(sarea) t_button_group.setExclusive(True) # Now the four buttons t_add_button = QPushButton(sarea) t_add_button.setCheckable(True) t_add_button.setFlat(True) t_add_button.setToolTip(self.add_help_text_short) t_add_button.setIcon(QIcon(os.path.join(icons_dir, 'add.png'))) layout.addWidget(t_add_button, num, self.add_column) t_button_group.addButton(t_add_button, Action.Add) t_keep_button = QPushButton(sarea) t_keep_button.setCheckable(True) t_keep_button.setFlat(True) t_keep_button.setToolTip(self.keep_help_text_short) t_keep_button.setIcon(QIcon(os.path.join(icons_dir, 'keep.png'))) layout.addWidget(t_keep_button, num, self.keep_column) t_button_group.addButton(t_keep_button, Action.Keep) t_delete_button = QPushButton(sarea) t_delete_button.setCheckable(True) t_delete_button.setFlat(True) t_delete_button.setToolTip(self.delete_help_text_short) t_delete_button.setIcon( QIcon(os.path.join(icons_dir, 'delete.png'))) layout.addWidget(t_delete_button, num, self.delete_column) t_button_group.addButton(t_delete_button, Action.Delete) t_blacklist_button = QPushButton(sarea) t_blacklist_button.setCheckable(True) t_blacklist_button.setFlat(True) t_blacklist_button.setToolTip(self.blacklist_help_text_short) t_blacklist_button.setIcon( QIcon(os.path.join(icons_dir, 'blacklist.png'))) if entry.entry_hash: layout.addWidget( t_blacklist_button, num, self.blacklist_column) else: t_blacklist_button.hide() dummy_label_bl = QLabel('', sarea) dummy_label_bl.setToolTip(self.blacklist_empty_line_help) layout.addWidget(dummy_label_bl, num, self.blacklist_column) t_button_group.button(entry.action).setChecked(True) # New: check a button based on how good the downloader is. t_button_group.addButton(t_blacklist_button, Action.Blacklist) self.buttons_groups.append(t_button_group) play_button_group.buttonClicked.connect( lambda button: play( self.entries_list[play_button_group.id(button)].file_path)) # N.B.: anki.sound.play() plays files from anywhere, not just # from the colection.media folder. We should be good, # here. (This behaviour may be a security risk, idk.) old_play_button_group.buttonClicked.connect( lambda button: playFromText( self.note[ self.entries_list[ old_play_button_group.id(button)].audio_field_name]))
def punchcard(ui, repo, *pats, **opts): """Generate a "punch card" graph of commit times. For drawing the graph, either PyQt4 or matplotlib can be used. The default is PyQt4, unless the --mpl option is given. Normally, all commits are registered in local time, so that commits at 10 AM local time in Europe and the USA show up on the same punch card entry. If --utc is given, all commit times are converted to UTC before registered. """ if pats: raise util.Abort('no argument allowed') filename = opts['filename'] if opts['datemin']: datemin = datetime.strptime(opts['datemin'], '%Y-%m-%d') else: datemin = None if opts['datemax']: datemax = datetime.strptime(opts['datemax'], '%Y-%m-%d') else: datemax = None users_include = set(opts['user']) users_exclude = set(opts['notuser']) user_filter = bool(users_include or users_exclude) title = opts.get('title') font = opts.get('font') or 'Arial' utc = opts.get('utc') data = [[0] * 24 for i in range(7)] cl = repo.changelog n = 0 ui.status('filtering changesets\n') for i in xrange(len(cl)): node = cl.read(cl.node(i)) # node[2] is a tuple of the date in UTC and the timezone offset. # If --utc is given, the offset can be ignored; otherwise if utc: date = datetime.utcfromtimestamp(node[2][0]) else: date = datetime.utcfromtimestamp(node[2][0] - node[2][1]) if (datemin and date < datemin) or (datemax and date > datemax): continue if user_filter: user = node[1] if users_include and user not in users_include: continue if user in users_exclude: continue day = (int(date.strftime('%w')) - 1) % 7 data[day][date.hour] += 1 n += 1 if n == 0: raise util.Abort('no matching changesets found') else: ui.status('punched %d changesets\n' % n) maxvalue = max(max(i) for i in data) or 1 xs, ys, rs, ss = [], [], [], [] for y, d in enumerate(data): for x, n in enumerate(d): xs.append(x) ys.append(y) rs.append(13. * n / maxvalue) ss.append(4. * n**2 / maxvalue) try: if opts.get('mpl') or opts.get('svg'): raise ImportError from PyQt4.QtCore import Qt, QPointF, QRectF from PyQt4.QtGui import QApplication, QColor, QFont, QImage, QLabel, \ QMainWindow, QPainter, QPixmap except ImportError: try: if opts.get('svg'): raise ImportError from matplotlib import pyplot except ImportError: if not opts.get('svg'): ui.status('Writing as SVG since neither PyQt4 nor ' 'matplotlib is available\n') if filename.endswith('.png'): filename = filename[:-4] + '.svg' f = open(filename, 'w') f.write('<?xml version="1.0" standalone="no"?>\n') f.write('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ' '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n') o = title and 30 or 0 # y coordinate offset f.write('<svg width="800" height="{0}" version="1.1" ' 'xmlns="http://www.w3.org/2000/svg">\n'.format(300 + o)) f.write('<style type="text/css"> circle {{fill: black;}} ' 'text {{font-family:{0};font-size:12;}} ' '.label{{font-size:12px;}}</style>\n'.format(font)) f.write('<rect x="0" y="0" width="800" height="{0}" ' 'style="fill:#efefef;"/>\n'.format(300 + o)) f.write('<line x1="35.5" y1="{0}" x2="{1}" y2="{0}" ' 'style="stroke:black;stroke-width:2"/>\n'.format( 264.5 + o, 45.5 + 24 * 31)) f.write('<line x1="35.5" y1="{0}" x2="35.5" y2="{1}" ' 'style="stroke:black;stroke-width:2"/>\n'.format( 14.5 + o, 264.5 + o)) for i, text in enumerate(days): f.write( '<text class="label" x="7.5" y="{0}">{1}</text>\n'.format( 34.5 + i * 34 + o, text)) for i in range(24): f.write('<text class="label" x="{0}" y="{1}">{2:02}</text>\n'. format(53.5 + i * 31, 280.5 + o, i)) for x, y, r in zip(xs, ys, rs): f.write('<circle cx="{0}" cy="{1}" r="{2}" fill="black"/>\n'. format(58.5 + x * 31, 30.5 + y * 34 + o, r)) if title: f.write('<text x="400" y="20" style="text-anchor:middle;">' '{0}</text>\n'.format(title)) f.write('</svg>') f.close() ui.status('created punch card in %s\n' % filename) else: pyplot.rc('font', family=font) # create a figure an axes with the same background color fig = pyplot.figure(figsize=(8, title and 3 or 2.5), facecolor='#efefef') ax = fig.add_subplot('111', axisbg='#efefef') # make the figure margins smaller if title: fig.subplots_adjust(left=0.06, bottom=0.04, right=0.98, top=0.95) ax.set_title(title, y=0.96).set_color('#333333') else: fig.subplots_adjust(left=0.06, bottom=0.08, right=0.98, top=0.99) # don't display the axes frame ax.set_frame_on(False) # plot the punch card data ax.scatter(xs, ys[::-1], s=ss, c='#333333', edgecolor='#333333') # hide the tick lines for line in ax.get_xticklines() + ax.get_yticklines(): line.set_alpha(0.0) # draw x and y lines (instead of axes frame) dist = -0.8 ax.plot([dist, 23.5], [dist, dist], c='#555555') ax.plot([dist, dist], [dist, 6.4], c='#555555') # select new axis limits ax.set_xlim(-1, 24) ax.set_ylim(-0.9, 6.9) # set tick labels and draw them smaller than normal ax.set_yticks(range(7)) for tx in ax.set_yticklabels(days[::-1]): tx.set_color('#555555') tx.set_size('x-small') ax.set_xticks(range(24)) for tx in ax.set_xticklabels(['%02d' % x for x in range(24)]): tx.set_color('#555555') tx.set_size('x-small') # get equal spacing for days and hours ax.set_aspect('equal') fig.savefig(filename) ui.status('created punch card in %s\n' % filename) if opts.get('display'): pyplot.show() else: app = QApplication([]) o = title and 30 or 0 # y coordinate offset image = QImage(800, 300 + o, QImage.Format_RGB32) painter = QPainter(image) painter.setRenderHints(QPainter.Antialiasing) painter.fillRect(0, 0, 800, 300 + o, QColor('#efefef')) painter.setPen(QColor('#555555')) painter.drawLine(QPointF(35.5, 264.5 + o), QPointF(45.5 + 24 * 31, 264.5 + o)) painter.drawLine(QPointF(35.5, 14.5 + o), QPointF(35.5, 264.5 + o)) painter.setFont(QFont(font, 8)) for i, text in enumerate(days): painter.drawText(QPointF(7.5, 34.5 + i * 34 + o), text) for i in range(24): text = '%02d' % i painter.drawText(QPointF(53.5 + i * 31, 280.5 + o), text) painter.setBrush(QColor('#333333')) painter.setPen(QColor('#333333')) for x, y, r in zip(xs, ys, rs): painter.drawEllipse(QPointF(58.5 + x * 31, 30.5 + y * 34 + o), r, r) if title: painter.setFont(QFont(font, 12)) painter.drawText(QRectF(0, 15, 800, 20), Qt.AlignCenter, title) painter.end() image.save(filename) ui.status('created punch card in %s\n' % filename) if opts.get('display'): win = QMainWindow() win.setWindowTitle('punchcard display') win.resize(800, 300 + o) lbl = QLabel(win) lbl.resize(800, 300 + o) lbl.setPixmap(QPixmap.fromImage(image)) win.show() app.exec_()
def setImage(self, image): self.displayFrame.setPixmap(QPixmap.fromImage(image))
def resizeEvent(self, evt): width = self.width() pm = QPixmap.fromImage(self.img) self.pm = pm.scaledToWidth(width) self.setPixmap(self.pm)
def convertImage(self, image): qimg = QImage(image, image.shape[1], image.shape[0], QImage.Format_RGB888) return QPixmap.fromImage(qimg)
def setFrame(self,frame): pixmap = QPixmap.fromImage(frame) self.label_img.setPixmap(pixmap)
def process(self, node): for idx in xrange(0, self.tabs.count()): widget = self.tabs.widget(idx) del widget self.tabs.clear() self.node = node file = self.node.open() tags = EXIF.process_file(file) if len(tags) == 0: self.nometa.setSizePolicy(self.tabs.sizePolicy()) self.tabs.hide() self.nometa.show() else: self.tabs.show() self.nometa.hide() sortedTags = {} for tag in tags.keys(): if tag not in ('JPEGThumbnail', 'TIFFThumbnail', 'Filename', 'EXIF MakerNote'): spaceidx = tag.find(" ") ifd = tag[:spaceidx].strip() if ifd == "Image": ifd = "IFD 0 (Image)" if ifd == "Thumbnail": ifd = "IFD 1 (Thumbnail)" key = tag[spaceidx:].strip() try: val = str(tags[tag]) except: val = "cannot be decoded" if ifd not in sortedTags.keys(): sortedTags[ifd] = [] sortedTags[ifd].append((key, val)) for ifd in sortedTags.keys(): table = QTableWidget(len(sortedTags[ifd]), 2) table.setShowGrid(False) table.setAlternatingRowColors(True) table.verticalHeader().hide() table.horizontalHeader().setClickable(False) table.horizontalHeader().setStretchLastSection(True) table.setHorizontalHeaderLabels(["Tag", "Value"]) table.setSelectionBehavior(QAbstractItemView.SelectRows) self.tabs.addTab(table, ifd) row = 0 for res in sortedTags[ifd]: key = QTableWidgetItem(res[0]) key.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) val = QTableWidgetItem(res[1]) val.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) table.setItem(row, 0, key) table.setItem(row, 1, val) row += 1 if 'JPEGThumbnail' in tags.keys(): label = QLabel() img = QImage() img.loadFromData(tags['JPEGThumbnail']) label.setPixmap(QPixmap.fromImage(img)) label.setAlignment(Qt.AlignCenter) self.tabs.addTab(label, "Embedded Thumbnail") if 'TIFFThumbnail' in tags.keys(): label = QLabel() img = QImage() img.loadFromData(tags['TIFFThumbnail']) label.setPixmap(QPixmap.fromImage(img)) label.setAlignment(Qt.AlignCenter) self.tabs.addTab(label, "Embedded Thumbnail") file.close()
def pixmap(self): return QPixmap.fromImage(self.image)
def setImage(self, image): self.label.setPixmap(QPixmap.fromImage(image))
def render_cell(self): logger.info('render_cell') logger.debug('self.current_sample_id: %d' % self.current_sample_id) if len(self.samples) == 0: raise Exception('no samples to show!') sample = [s for s in self.samples if s['id'] == self.current_sample_id][0] cell = sample['cell'] nucleus = sample['nucleus'] self.renderingMutex.lock() if self.renderingThread.isRunning(): logger.debug('terminating rendering thread') self.renderingThread.quit() else: self.renderingThread.setIndividual(self.current_sample_id, sample) self.trigger_render() self.renderingMutex.unlock() c, r = nucleus.boundary.xy r_n, c_n = draw.polygon(r, c) logger.debug('feat id: %d' % sample['id']) self.mplEduHist.hide() self.imgEdu.clear() self.imgCell.clear() self.imgPericentrin.clear() self.imgTubulin.clear() self.lblEduMin.setText('min ' + m.eng_string(self.edu[r_n, c_n].min(), format='%0.1f', si=True)) self.lblEduMax.setText('max ' + m.eng_string(self.edu[r_n, c_n].max(), format='%0.1f', si=True)) self.lblEduAvg.setText('avg ' + m.eng_string(self.edu[r_n, c_n].mean(), format='%0.1f', si=True)) self.lblTubMin.setText('min ' + m.eng_string(self.tubulin[r_n, c_n].min(), format='%0.1f', si=True)) self.lblTubMax.setText('max ' + m.eng_string(self.tubulin[r_n, c_n].max(), format='%0.1f', si=True)) self.lblTubAvg.setText('avg ' + m.eng_string(self.tubulin[r_n, c_n].mean(), format='%0.1f', si=True)) self.lblCentr_n.setText('%d' % len([s for s in sample['centrosomes'] if s is not None])) self.lblId.setText('id %d' % sample['id']) # self.lblOK.setText('OK' if valid else 'no OK') fig = Figure((self.imgCentrCloseup.width() / mydpi, self.imgCentrCloseup.height() / mydpi), subplotpars=sp, dpi=mydpi) canvas = FigureCanvas(fig) ax = fig.gca() ax.set_aspect('equal') ax.set_axis_off() l, b, w, h = fig.bbox.bounds c1 = sample['centrosomes'][0]['pt'] c2 = sample['centrosomes'][1]['pt'] self.lblDist_nc.setText('%0.2f' % nucleus.centroid.distance(c1)) self.lblDist_nb.setText('%0.2f' % nucleus.exterior.distance(c1)) self.lblDist_cc.setText('%0.2f' % cell.centroid.distance(c1)) self.lblDist_cb.setText('%0.2f' % cell.exterior.distance(c1)) ax.imshow(self.pericentrin, cmap='gray') if c1 is not None: c = plt.Circle((c1.x, c1.y), radius=5, facecolor='none', edgecolor='r', linestyle='--', linewidth=1, zorder=5) ax.add_artist(c) if c2 is not None: c = plt.Circle((c2.x, c2.y), radius=5, facecolor='none', edgecolor='b', linestyle='--', linewidth=1, zorder=5) ax.add_artist(c) ax.set_xlim(c1.x - w / 8, c1.x + w / 8) ax.set_ylim(c1.y - h / 8, c1.y + h / 8) qimg_closeup = ImageQt(utils.canvas_to_pil(canvas)) self.imgCentrCloseup.setPixmap(QPixmap.fromImage(qimg_closeup)) self.update()
def update_image(self): width = self.width() pm = QPixmap.fromImage(self.img) pm = pm.scaledToWidth(width) self.setPixmap(pm)
def setImage(self, rgb_image, depth_image): if (self.ui.radioVideo.isChecked()): self.ui.videoDisplay.setPixmap(QPixmap.fromImage(rgb_image)) if (self.ui.radioDepth.isChecked()): self.ui.videoDisplay.setPixmap(QPixmap.fromImage(depth_image))
def get_icon_cache(self, path): if path not in self.icon_cache: img = QImage(path) self.icon_cache[path] = QIcon(QPixmap.fromImage(img)) return self.icon_cache[path]
def create_rows(self, layout): u"""Build one row of the dialog box""" play_button_group = QButtonGroup(self) old_play_button_group = QButtonGroup(self) for num, (source, dest, text, dl_fname, dl_hash, extras, icon)\ in enumerate(self.list, 3): tt_text = self.build_text_help_label(text, source, extras) ico_label = QLabel('', self) ico_label.setToolTip(tt_text) if icon: ico_label.setPixmap(QPixmap.fromImage(icon)) layout.addWidget(ico_label, num, 0) tt_label = QLabel(text, self) tt_label.setToolTip(tt_text) layout.addWidget(tt_label, num, 1) if self.hide_text: tt_label.hide() # Play button. t_play_button = QPushButton(self) play_button_group.addButton(t_play_button, num - 3) t_play_button.setToolTip(self.play_help) t_play_button.setIcon(QIcon(os.path.join(icons_dir, 'play.png'))) layout.addWidget(t_play_button, num, self.play_column) if self.note[dest]: t_play_old_button = QPushButton(self) old_play_button_group.addButton(t_play_old_button, num - 3) t_play_old_button.setIcon( QIcon(os.path.join(icons_dir, 'play.png'))) if not self.hide_text: t_play_old_button.setToolTip(self.note[dest]) else: t_play_old_button.setToolTip(self.play_old_help_short) layout.addWidget(t_play_old_button, num, self.play_old_column) else: dummy_label = QLabel('', self) dummy_label.setToolTip(self.play_old_empty_line_help) layout.addWidget(dummy_label, num, self.play_old_column) # The group where we later look what to do: t_button_group = QButtonGroup(self) t_button_group.setExclusive(True) # Now the four buttons t_add_button = QPushButton(self) t_add_button.setCheckable(True) t_add_button.setChecked(True) t_add_button.setFlat(True) t_add_button.setToolTip(self.add_help_text_short) t_add_button.setIcon(QIcon(os.path.join(icons_dir, 'add.png'))) layout.addWidget(t_add_button, num, self.add_column) t_button_group.addButton(t_add_button, action['add']) t_keep_button = QPushButton(self) t_keep_button.setCheckable(True) t_keep_button.setFlat(True) t_keep_button.setToolTip(self.keep_help_text_short) t_keep_button.setIcon(QIcon(os.path.join(icons_dir, 'keep.png'))) layout.addWidget(t_keep_button, num, self.keep_column) t_button_group.addButton(t_keep_button, action['keep']) t_delete_button = QPushButton(self) t_delete_button.setCheckable(True) t_delete_button.setFlat(True) t_delete_button.setToolTip(self.delete_help_text_short) t_delete_button.setIcon( QIcon(os.path.join(icons_dir, 'delete.png'))) layout.addWidget(t_delete_button, num, self.delete_column) t_button_group.addButton(t_delete_button, action['delete']) t_blacklist_button = QPushButton(self) t_blacklist_button.setCheckable(True) t_blacklist_button.setFlat(True) t_blacklist_button.setToolTip(self.blacklist_help_text_short) t_blacklist_button.setIcon( QIcon(os.path.join(icons_dir, 'blacklist.png'))) if self.show_skull_and_bones: layout.addWidget(t_blacklist_button, num, self.blacklist_column) else: t_blacklist_button.hide() t_button_group.addButton(t_blacklist_button, action['blacklist']) self.buttons_groups.append(t_button_group) play_button_group.buttonClicked.connect( lambda button: play(self.list[play_button_group.id(button)][3])) old_play_button_group.buttonClicked.connect( lambda button: playFromText(self.note[self.list[ old_play_button_group.id(button)][1]]))
def setImage3(self, image): self.videoCom3.setPixmap(QPixmap.fromImage(image))
def _renderimage(self): image = self.renderjob.renderedImage() self.previewImage.setPixmap(QPixmap.fromImage(image))
def fitbest(self): self.currentImage = self.baseImage.scaled(QSize(self.imgWidth, self.imgWidth), Qt.KeepAspectRatio, Qt.FastTransformation) self.setPixmap(QPixmap.fromImage(self.currentImage)) self.adjustSize()
def show_fullscreen_image(self, image): """:param image: a QImage""" pixmap = QPixmap.fromImage(image) self.show_fullscreen_pixmap(pixmap)
import os, sys from qtpuzzle.render_outline import outline from PyQt4.QtGui import QApplication, QImage, QPixmap, QLabel a = QApplication(sys.argv) myImage = QImage() myImage.load("puzzles/outtest/pieces/piece15.png") outline(myImage, illum_angle=-30) w, h = myImage.width(), myImage.height() myLabel = QLabel() myLabel.setPixmap(QPixmap.fromImage(myImage.scaled(5 * w, 5 * h))) myLabel.show() a.exec_()
def _mirrored(icon): return QPixmap.fromImage( QImage(QPixmap(icon)).mirrored(True, False))