我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt4.QtGui.QImage()。
def pixmap_from_colors(self,images,colors,axisval): if axisval == 2: image = [np.sum(_, axis=axisval) for _ in images] else: image = [np.transpose(np.sum(_, axis=axisval)) for _ in images] image = np.array([self.scale_contrast(_) for _ in image]) Y, X = image.shape[1:] bgra = np.zeros((Y, X, 4), dtype=np.float32) for color, image in zip(colors, image): bgra[:, :, 0] += color[2] * image bgra[:, :, 1] += color[1] * image bgra[:, :, 2] += color[0] * image bgra = np.minimum(bgra, 1) self._bgra = self.to_8bit(bgra) qimage = QtGui.QImage(self._bgra.data, X, Y, QtGui.QImage.Format_RGB32) qimage = qimage.scaled(self.viewxy.width(), np.round(self.viewxy.height()*Y/X), QtCore.Qt.KeepAspectRatioByExpanding) pixmap = QtGui.QPixmap.fromImage(qimage) return pixmap
def getQImageFromData(image_data): img = QtGui.QImage() success = img.loadFromData( image_data ) if not success: try: if pil_available: # Qt doesn't understand the format, but maybe PIL does # so try to convert the image data to uncompressed tiff format im = Image.open(StringIO.StringIO(image_data)) output = StringIO.StringIO() im.save(output, format="TIFF") img.loadFromData( output.getvalue() ) success = True except Exception as e: pass # if still nothing, go with default image if not success: img.load(ComicTaggerSettings.getGraphic('nocover.png')) return img
def save_page(self,finished): #print finished if finished: print u"?????" size = self.webpage.mainFrame().contentsSize() print u"????%d?????%d" % (size.width(),size.height()) self.webpage.setViewportSize(QtCore.QSize(size.width()+16,size.height())) img = QtGui.QImage(size, QtGui.QImage.Format_ARGB32) painter = QtGui.QPainter(img) self.webpage.mainFrame().render(painter) painter.end() filename= self.filename; if img.save(filename): filepath = os.path.join(os.path.dirname(__file__), filename) print u"?????%s" % filepath else: print u"????"; else: print u"???????" self.close()
def histtoImage(self, image): cmap = np.uint8(np.round(255 * plt.get_cmap('magma')(np.arange(256)))) image /= image.max() image = np.minimum(image, 1.0) image = np.round(255 * image).astype('uint8') Y, X = image.shape self._bgra = np.zeros((Y, X, 4), dtype=np.uint8, order='C') self._bgra[..., 0] = cmap[:, 2][image] self._bgra[..., 1] = cmap[:, 1][image] self._bgra[..., 2] = cmap[:, 0][image] qimage = QtGui.QImage(self._bgra.data, X, Y, QtGui.QImage.Format_RGB32) qimage = qimage.scaled(self.viewxy.width(), np.round(self.viewxy.height()*Y/X), QtCore.Qt.KeepAspectRatioByExpanding) pixmap = QtGui.QPixmap.fromImage(qimage) return pixmap
def open_file(self, fileName): image = QtGui.QImage(fileName) if image.isNull(): QtGui.QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName) return self.imageLabel.setPixmap(QtGui.QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() self.show()
def open(self): fileName = QtGui.QFileDialog.getOpenFileName(self, "Open File", QtCore.QDir.currentPath()) if fileName: image = QtGui.QImage(fileName) if image.isNull(): QtGui.QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName) return self.imageLabel.setPixmap(QtGui.QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize()
def insertImage(self): # Get image file name filename = QtGui.QFileDialog.getOpenFileName(self, 'Insert image',".","Images (*.png *.xpm *.jpg *.bmp *.gif)") if filename: # Create image object image = QtGui.QImage(filename) # Error if unloadable if image.isNull(): popup = QtGui.QMessageBox(QtGui.QMessageBox.Critical, "Image load error", "Could not load image file!", QtGui.QMessageBox.Ok, self) popup.show() else: cursor = self.text.textCursor() cursor.insertImage(image,filename)
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [image.height(), image.width(), 1 if image.isGrayscale() else 3] writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt,\ imageShape, localImgPath=imagePath) bSave = False for shape in shapes: points = shape['points'] label = shape['label'] bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label) bSave = True if bSave: writer.save(targetFile = filename) return
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) #imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [image.height(), image.width(), 1 if image.isGrayscale() else 3] writer = PascalVocWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) writer.verified = self.verified for shape in shapes: points = shape['points'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult) writer.save(targetFile=filename) return
def mathTex_to_QPixmap(mathTex, fs): #---- set up a mpl figure instance ---- fig = mpl.figure.Figure() fig.patch.set_facecolor('none') fig.set_canvas(FigureCanvasAgg(fig)) renderer = fig.canvas.get_renderer() #---- plot the mathTex expression ---- ax = fig.add_axes([0, 0, 1, 1]) ax.axis('off') ax.patch.set_facecolor('none') t = ax.text(0, 0, mathTex, ha='left', va='bottom', fontsize=fs) #---- fit figure size to text artist ---- fwidth, fheight = fig.get_size_inches() fig_bbox = fig.get_window_extent(renderer) text_bbox = t.get_window_extent(renderer) tight_fwidth = text_bbox.width * fwidth / fig_bbox.width tight_fheight = text_bbox.height * fheight / fig_bbox.height fig.set_size_inches(tight_fwidth, tight_fheight) #---- convert mpl figure to QPixmap ---- buf, size = fig.canvas.print_to_buffer() qimage = QtGui.QImage.rgbSwapped(QtGui.QImage(buf, size[0], size[1], QtGui.QImage.Format_ARGB32)) qpixmap = QtGui.QPixmap(qimage) return qpixmap
def mathTexToQPixMap( self ,mathTex, fs): fig = mpl.figure.Figure() fig.patch.set_facecolor('none') fig.set_canvas(FigureCanvasAgg(fig)) renderer = fig.canvas.get_renderer() #---- plot the mathTex expression ---- ax = fig.add_axes([0, 0, 1, 1]) ax.axis('off') ax.patch.set_facecolor('none') t = ax.text(0, 0, mathTex, ha='left', va='bottom', fontsize=fs) #---- fit figure size to text artist ---- fwidth, fheight = fig.get_size_inches() fig_bbox = fig.get_window_extent(renderer) text_bbox = t.get_window_extent(renderer) tight_fwidth = text_bbox.width * fwidth / fig_bbox.width tight_fheight = text_bbox.height * fheight / fig_bbox.height fig.set_size_inches(tight_fwidth, tight_fheight) #---- convert mpl figure to QPixmap ---- buf, size = fig.canvas.print_to_buffer() qimage = QtGui.QImage.rgbSwapped(QtGui.QImage(buf, size[0], size[1], QtGui.QImage.Format_ARGB32)) self.qpixmap = QtGui.QPixmap(qimage) return self.qpixmap
def draw_predictions(file_path, predictions, class_index, score_low, score_high): img = QtGui.QImage(file_path) painter = QtGui.QPainter(img) for i, pred in enumerate(predictions): if class_index > 0 and pred.class_index != class_index: continue if pred.score < score_low or pred.score > score_high: continue class_name = CLASS_NAMES[pred.class_index] x1, y1, x2, y2 = map(int, pred.bbox) # bbox painter.setPen(QtGui.QPen(PRESET_COLORS[pred.class_index], 10.0)) # painter.setPen(QtGui.QPen(QtGui.QColor(0, 116, 217), 10.0)) painter.setBrush(QtGui.QBrush()) painter.drawRect(x1, y1, x2 - x1 + 1, y2 - y1 + 1) # label background rect painter.setPen(QtGui.QPen(PRESET_COLORS[pred.class_index], 2.0)) painter.setBrush(QtGui.QBrush(PRESET_COLORS[pred.class_index])) # painter.setPen(QtGui.QPen(QtGui.QColor(0, 116, 217), 2.0)) # painter.setBrush(QtGui.QBrush(QtGui.QColor(0, 116, 217))) if class_index > 0: painter.drawRect(x1, y1, min(x2 - x1 + 1, 100), 30) else: painter.drawRect(x1, y1, min(x2 - x1 + 1, 200), 30) # label text painter.setPen(QtGui.QPen(QtGui.QColor(255, 255, 255))) painter.setBrush(QtGui.QBrush()) painter.setFont(QtGui.QFont('Arial', 20, QtGui.QFont.Bold)) if class_index > 0: painter.drawText(x1 + 4, y1 + 24, '{:.2f}'.format(pred.score)) else: painter.drawText(x1 + 4, y1 + 24, '{} {:.2f}'.format(class_name, pred.score)) return img
def setThreshold(self,val): if self.img: bw = self.img.point(lambda x: 0 if x<val else 255, '1') image = QtGui.QImage(bw.convert("RGBA").tostring("raw", "RGBA"), bw.size[0], bw.size[1], QtGui.QImage.Format_ARGB32) pix = QtGui.QPixmap.fromImage(image) self.setPixMapOnLabel(self.imgFrame,pix) self.bw = bw return val
def loadImage(self): success = False message = self.defaultStatusbar if self.images: filename = self.images[self.idx] filename = os.path.normpath( filename ) if not self.image.isNull() and filename == self.currentFile: success = True else: self.image = QtGui.QImage(filename) if self.image.isNull(): message = "Failed to read image: {0}".format( filename ) else: message = "Read image: {0}".format( filename ) self.currentFile = filename success = True # Update toolbar actions that need an image for act in self.actImage: act.setEnabled(success) for act in self.actImageNotFirst: act.setEnabled(success and self.idx > 0) for act in self.actImageNotLast: act.setEnabled(success and self.idx < len(self.images)-1) self.statusBar().showMessage(message) # Load the labels from file # Only loads if they exist # Otherwise the filename is stored and that's it
def drawZoom(self,qp,overlay): # Zoom disabled? if not self.zoom: return # No image if self.image.isNull() or not self.w or not self.h: return # No mouse if not self.mousePosOrig: return # Abbrevation for the zoom window size zoomSize = self.zoomSize # Abbrevation for the mouse position mouse = self.mousePosOrig # The pixel that is the zoom center pix = self.mousePosScaled # The size of the part of the image that is drawn in the zoom window selSize = zoomSize / ( self.zoomFactor * self.zoomFactor ) # The selection window for the image sel = QtCore.QRectF(pix.x() -selSize/2 ,pix.y() -selSize/2 ,selSize,selSize ) # The selection window for the widget view = QtCore.QRectF(mouse.x()-zoomSize/2,mouse.y()-zoomSize/2,zoomSize,zoomSize) if overlay : overlay_scaled = overlay.scaled(self.image.width(), self.image.height()) else : overlay_scaled = QtGui.QImage( self.image.width(), self.image.height(), QtGui.QImage.Format_ARGB32_Premultiplied ) # Show the zoom image qp.save() qp.drawImage(view,self.image,sel) qp.setOpacity(self.transp) qp.drawImage(view,overlay_scaled,sel) qp.restore() # Draw disparities
def texture(self, code): fil = os.path.join(os.path.dirname(__file__), 'symbologie', code+'.svg') if os.path.exists(fil): return QImage(fil) else: return QImage()
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [image.height(), image.width(), 1 if image.isGrayscale() else 3] writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt, imageShape, localImgPath=imagePath) writer.verified = self.verified for shape in shapes: points = shape['points'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) direction = shape['direction'] isRotated = shape['isRotated'] # if shape is normal box, save as bounding box # print('direction is %lf' % direction) if not isRotated: bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult) else: #if shape is rotated box, save as rotated bounding box robndbox = LabelFile.convertPoints2RotatedBndBox(shape) writer.addRotatedBndBox(robndbox[0],robndbox[1], robndbox[2],robndbox[3],robndbox[4],label,difficult) writer.save(targetFile=filename) return
def loadImage(self): success = False message = self.defaultStatusbar if self.images: filename = self.images[self.idx] filename = os.path.normpath( filename ) if not self.image.isNull() and filename == self.config.currentFile: success = True else: self.image = QtGui.QImage(filename) if self.image.isNull(): message = "Failed to read image: {0}".format( filename ) else: message = "Read image: {0}".format( filename ) self.config.currentFile = filename success = True # Update toolbar actions that need an image for act in self.actImage: act.setEnabled(success) for act in self.actImageNotFirst: act.setEnabled(success and self.idx > 0) for act in self.actImageNotLast: act.setEnabled(success and self.idx < len(self.images)-1) self.statusBar().showMessage(message) # Load the labels from file # Only loads if they exist # Otherwise the filename is stored and that's it
def convertFrame(self): """ converts frame to format suitable for QtGui """ try: height, width = self.currentFrame.shape[:2] img = QtGui.QImage(self.currentFrame, width, height, QtGui.QImage.Format_RGB888) img = QtGui.QPixmap.fromImage(img) # self.previousFrame = self.currentFrame return img except Exception, e: print "convertFrame: ", e return None
def displayPhoto(self): if len(self.analyzedPhotos) == 0: self.analyzePhotos() analyzedPhoto = self.analyzedPhotos[self.photoIndex] image = analyzedPhoto["image"] #Conversion magic to make it into PyQt.Gui form, and then display it imageQt = ImageQt(image) qiImage = QImage(imageQt) pixMap = QPixmap(qiImage) self.currentImageLabel.setPixmap(pixMap) ''' - Old OpenCV code; we now use Microsoft Cognitive Services API data = urllib.urlopen(url).read(); openCVImage = self.handleFacialRecognition(data); #image = QtGui.QImage() #image.loadFromData(data) self.currentImageLabel.setPixmap(openCVImage); ''' ########################################################### # # # LISTENERS # # # ###########################################################
def set_image(self, image): cmap = np.uint8(np.round(255 * plt.get_cmap('magma')(np.arange(256)))) image /= image.max() image = np.minimum(image, 1.0) image = np.round(255 * image).astype('uint8') Y, X = image.shape self._bgra = np.zeros((Y, X, 4), dtype=np.uint8, order='C') self._bgra[..., 0] = cmap[:, 2][image] self._bgra[..., 1] = cmap[:, 1][image] self._bgra[..., 2] = cmap[:, 0][image] qimage = QtGui.QImage(self._bgra.data, X, Y, QtGui.QImage.Format_RGB32) self._pixmap = QtGui.QPixmap.fromImage(qimage) self.set_pixmap(self._pixmap)
def translate(self, translateaxis): renderings = [render.render_hist3d(_, self.oversampling, self.t_min, self.t_min, self.t_max, self.t_max, self.z_min, self.z_max, self.pixelsize) for _ in self.locs] n_locs = sum([_[0] for _ in renderings]) images = np.array([_[1] for _ in renderings]) if translateaxis == 'x': image = [np.sum(_, axis=2) for _ in images] signalimg = [np.sum(_, axis=0) for _ in image] elif translateaxis == 'y': image = [np.sum(_, axis=2) for _ in images] signalimg = [np.sum(_, axis=1) for _ in image] elif translateaxis == 'z': image = [np.sum(_, axis=1) for _ in images] signalimg = [np.sum(_, axis=0) for _ in image] fig = plt.figure(figsize =(5,5)) ax1 = fig.add_subplot(1, 1 ,1) for element in signalimg: plt.plot(element) n_groups = self.group_index[0].shape[0] print('Translating..') for i in tqdm(range(n_groups)): self.status_bar.showMessage('Group {} / {}.'.format(i, n_groups)) self.translate_group(signalimg, i, translateaxis) fig.canvas.draw() size = fig.canvas.size() width, height = size.width(), size.height() im = QtGui.QImage(fig.canvas.buffer_rgba(), width, height, QtGui.QImage.Format_ARGB32) self.viewcp.setPixmap((QtGui.QPixmap(im))) self.viewcp.setAlignment(QtCore.Qt.AlignCenter) plt.close(fig) self.centerofmass_all() self.updateLayout() self.status_bar.showMessage('Done!')
def render_scene(self, autoscale=False, use_cache=False, cache=True, viewport=None): kwargs = self.get_render_kwargs(viewport=viewport) n_channels = len(self.locs) if n_channels == 1: self.render_single_channel(kwargs, autoscale=autoscale, use_cache=use_cache, cache=cache) else: self.render_multi_channel(kwargs, autoscale=autoscale, use_cache=use_cache, cache=cache) self._bgra[:, :, 3].fill(255) Y, X = self._bgra.shape[:2] qimage = QtGui.QImage(self._bgra.data, X, Y, QtGui.QImage.Format_RGB32) return qimage
def draw_frame(self): if self.movie is not None: frame = self.movie[self.current_frame_number] frame = frame.astype('float32') if self.contrast_dialog.auto_checkbox.isChecked(): frame -= frame.min() frame /= frame.max() else: frame -= self.contrast_dialog.black_spinbox.value() frame /= self.contrast_dialog.white_spinbox.value() frame *= 255.0 frame = np.maximum(frame, 0) frame = np.minimum(frame, 255) frame = frame.astype('uint8') height, width = frame.shape image = QtGui.QImage(frame.data, width, height, width, QtGui.QImage.Format_Indexed8) image.setColorTable(CMAP_GRAYSCALE) pixmap = QtGui.QPixmap.fromImage(image) self.scene = Scene(self) self.scene.addPixmap(pixmap) self.view.setScene(self.scene) if self.ready_for_fit: identifications_frame = self.identifications[self.identifications.frame == self.current_frame_number] box = self.last_identification_info['Box Size'] self.draw_identifications(identifications_frame, box, QtGui.QColor('yellow')) else: if self.parameters_dialog.preview_checkbox.isChecked(): identifications_frame = localize.identify_by_frame_number(self.movie, self.parameters['Min. Net Gradient'], self.parameters['Box Size'], self.current_frame_number, self.view.roi) box = self.parameters['Box Size'] self.status_bar.showMessage('Found {:,} spots in current frame.'.format(len(identifications_frame))) self.draw_identifications(identifications_frame, box, QtGui.QColor('red')) else: self.status_bar.showMessage('') if self.locs is not None: locs_frame = self.locs[self.locs.frame == self.current_frame_number] for loc in locs_frame: self.scene.addItem(FitMarker(loc.x+0.5, loc.y+0.5, 1))
def __init__(self, qlabel): self.qlabel_image = qlabel # widget/window name where image is displayed (I'm usiing qlabel) self.qimage_scaled = QImage() # scaled image to fit to the size of qlabel_image self.qpixmap = QPixmap() # qpixmap to fill the qlabel_image self.zoomX = 1 # zoom factor w.r.t size of qlabel_image self.position = [0, 0] # position of top left corner of qimage_label w.r.t. qimage_scaled self.panFlag = False # to enable or disable pan self.qlabel_image.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) self.__connectEvents()
def loadImage(self, imagePath): ''' To load and display new image.''' self.qimage = QImage(imagePath) self.qpixmap = QPixmap(self.qlabel_image.size()) if not self.qimage.isNull(): # reset Zoom factor and Pan position self.zoomX = 1 self.position = [0, 0] self.qimage_scaled = self.qimage.scaled(self.qlabel_image.width(), self.qlabel_image.height(), QtCore.Qt.KeepAspectRatio) self.update() else: self.statusbar.showMessage('Cannot open this image! Try another one.', 5000)
def __init__(self, *args): QtGui.QMainWindow.__init__(self, *args) self._i=numpy.zeros((1,1,4),dtype=numpy.uint8) self.i=QtGui.QImage(self._i.data,self._i.shape[1],self._i.shape[0],self.imgconvarray[self._i.shape[2]]) self.show()
def f(self,thearray): self._i=thearray.astype(numpy.uint8).copy('C') self.i=QtGui.QImage(self._i.data,self._i.shape[1],self._i.shape[0],self.imgconvarray[self._i.shape[2]]) self.update() qapp.processEvents()
def f(self,thearray): #print "ARRAY", #print thearray self._i=thearray.astype(numpy.uint8).copy('C') self.i=QtGui.QImage(self._i.data,self._i.shape[1],self._i.shape[0],self.imgconvarray[self._i.shape[2]]) self.update() qapp.processEvents()
def __init__(self, opencvBgrImg): depth, nChannels = opencvBgrImg.depth, opencvBgrImg.nChannels if depth != cv.IPL_DEPTH_8U or nChannels != 3: raise ValueError("the input image must be 8-bit, 3-channel") w, h = cv.GetSize(opencvBgrImg) opencvRgbImg = cv.CreateImage((w, h), depth, nChannels) # it's assumed the image is in BGR format cv.CvtColor(opencvBgrImg, opencvRgbImg, cv.CV_BGR2RGB) self._imgData = opencvRgbImg.tostring() super(OpenCVQImage, self).__init__(self._imgData, w, h, \ QtGui.QImage.Format_RGB888)
def stopVideo(self): qt_image = QtGui.QImage() self.videoSignal1.emit(qt_image) cv2.cv.DestroyAllWindows() try: del self.capture except: pass self.run_video = False
def saveImage(self): file_name = QtGui.QFileDialog.getSaveFileName(None, 'Save Image', '/home/ghostman/Pictures/', selectedFilter = '*jpg') cv2.cv.SaveImage(str(file_name)+".jpg", self.drawing) self.videoSignal2.emit(QtGui.QImage()) self.stopVideo()
def __init__(self, parent = None): super(VideoFeed, self).__init__(parent) self.image = QtGui.QImage() self.initUI()
def __init__(self, parent = None): super(PaintPanel, self).__init__(parent) self.image = QtGui.QImage() self.initUI()
def __init__(self, parent=None): super(SvgView, self).__init__(parent) self.svgItem = None self.image = QtGui.QImage() self.setScene(QtGui.QGraphicsScene(self)) self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse) self.setDragMode(QtGui.QGraphicsView.ScrollHandDrag)
def cvtrgb2qtimage(arr): H, W = arr.shape[0], arr.shape[1] return QtGui.QImage(arr, W, H, W * 3, QtGui.QImage.Format_RGB888)