def convert_bitmap(image, width=None, height=None): pix = None if isinstance(image, ImageResource): pix = traitsui_convert_bitmap(image) elif isinstance(image, Image): # image = image.convert('RGBA') data = image.tostring('raw', 'RGBA') im = QImage(data, image.size[0], image.size[1], QImage.Format_ARGB32) pix = QPixmap.fromImage(QImage.rgbSwapped(im)) else: s = image.shape if len(s) >= 2: # im = QImage(image.tostring(),s[1], s[0], QImage.Format_RGB888) im = QImage(image, s[1], s[0], QImage.Format_RGB888) pix = QPixmap.fromImage(QImage.rgbSwapped(im)) else: pix = QPixmap() if pix: if width > 0 and height > 0: pix = pix.scaled(width, height) elif width > 0: pix = pix.scaledToWidth(width) if height > 0: pix = pix.scaledToHeight(height) return pix
def _wait_for_frame(self): if self.camera.wait_for_frame(0): data = self.camera.image_buffer() bpl = self.camera.bytes_per_line format = QImage.Format_RGB32 image = QImage(data, self.camera.width, self.camera.height, bpl, format) if self.pixmapitem is None: self.pixmapitem = self.scene.addPixmap(QPixmap.fromImage(image)) else: self.pixmapitem.setPixmap(QPixmap.fromImage(image))
def _wait_for_frame(self): if self.camera.wait_for_frame(0): data = self.camera.get_image_buffer() bpl = self.camera.bytes_per_line format = QImage.Format_RGB32 image = QImage(data, self.camera.width, self.camera.height, bpl, format) if self.pixmapitem is None: self.pixmapitem = self.scene.addPixmap( QPixmap.fromImage(image)) else: self.pixmapitem.setPixmap(QPixmap.fromImage(image))
def _set_pixmap_from_array(self, arr): bpl = arr.strides[0] is_rgb = len(arr.shape) == 3 if is_rgb and arr.dtype == np.uint8: format = QImage.Format_RGB32 image = QImage(arr.data, self.camera.width, self.camera.height, bpl, format) elif not is_rgb and arr.dtype == np.uint8: # TODO: Somehow need to make sure data is ordered as I'm assuming format = QImage.Format_Indexed8 image = QImage(arr.data, self.camera.width, self.camera.height, bpl, format) self._saved_img = arr elif not is_rgb and arr.dtype == np.uint16: if not self._cmax: self._cmax = arr.max() # Set cmax once from first image arr = scipy.misc.bytescale(arr, self._cmin, self._cmax) format = QImage.Format_Indexed8 w, h = self.camera.width, self.camera.height image = QImage(arr.data, w, h, w, format) self._saved_img = arr # Save a reference to keep Qt from crashing else: raise Exception("Unsupported color mode") self.setPixmap(QPixmap.fromImage(image)) pixmap_size = self.pixmap().size() if pixmap_size != self.size(): self.setMinimumSize(self.pixmap().size())
def pixmap_from_hicon(hicon): if not hicon: return screen_device = GetDC(None) hdc = CreateCompatibleDC(screen_device) ReleaseDC(None, screen_device) icon_info = ICONINFO() if not GetIconInfo(hicon, byref(icon_info)): raise WindowsError('call to GetIconInfo failed') width = icon_info.xHotspot * 2 height = icon_info.yHotspot * 2 bitmap_header = BITMAPINFOHEADER() bitmap_header.biSize = sizeof(bitmap_header) bitmap_header.biWidth = width bitmap_header.biHeight = height bitmap_header.biPlanes = 1 bitmap_header.biBitCount = 32 bitmap_header.biCompression = BI_RGB bitmap_header.biSizeImage = 0 bitmap_header.biXPelsPerMeter = 0 bitmap_header.biYPelsPerMeter = 0 bitmap_header.biClrUsed = 0 bitmap_header.biClrImportant = 0 bits = c_void_p() win_bitmap = CreateDIBSection(hdc, byref(bitmap_header), DIB_RGB_COLORS, byref(bits), None, 0); old_hdc = SelectObject(hdc, win_bitmap) DrawIconEx(hdc, 0, 0, hicon, width, height, 0, None, DI_NORMAL) image = image_from_hbitmap(hdc, win_bitmap, width, height) # do the alpha shit DeleteObject(icon_info.hbmMask) DeleteObject(icon_info.hbmColor) SelectObject(hdc, old_hdc) DeleteObject(win_bitmap) DeleteDC(hdc) return QPixmap.fromImage(image)
def _set_pixmap_from_camera(self): bpl = self.camera.bytes_per_line arr = self.camera.image_array() if self.camera.color_mode == 'RGB32': buf = self.camera.image_buffer() # TODO: Fix to use image_array() instead format = QImage.Format_RGB32 image = QImage(buf, self.camera.width, self.camera.height, bpl, format) elif self.camera.color_mode == 'mono8': # TODO: Somehow need to make sure data is ordered as I'm assuming format = QImage.Format_Indexed8 image = QImage(arr.data, self.camera.width, self.camera.height, bpl, format) self._saved_img = arr elif self.camera.color_mode == 'mono16': pil_img = scipy.misc.toimage(arr) # Normalize values to fit in uint8 format = QImage.Format_Indexed8 data = pil_img.tostring() image = QImage(data, pil_img.size[0], pil_img.size[1], pil_img.size[0], format) self._saved_img = data # Save a reference to keep Qt from crashing elif self.camera.color_mode==None: buf = self.camera.image_buffer() # TODO: Fix to use image_array() instead format = QImage.Format_RGB32 image = QImage(buf, self.camera.width, self.camera.height, bpl, format) else: raise Exception("Unsupported color mode '{}'".format(self.camera.color_mode)) self.setPixmap(QPixmap.fromImage(image)) pixmap_size = self.pixmap().size() if pixmap_size != self.size(): self.setMinimumSize(self.pixmap().size())
def drawIconWithShadow(icon, rect, p, iconMode, radius, color, offset): cache = QPixmap() pixmapName = "icon {0} {1} {2}".format(icon.cacheKey(), iconMode, rect.height()) if not QPixmapCache.find(pixmapName, cache): px = icon.pixmap(rect.size()) cache = QPixmap(px.size() + QSize(radius * 2, radius * 2)) cache.fill(Qt.transparent) cachePainter = QPainter(cache) if iconMode == QIcon.Disabled: im = px.toImage().convertToFormat(QImage.Format_ARGB32) for y in range(im.height()): scanLine = im.scanLine(y) for x in range(im.width()): pixel = scanLine intensity = qGray(pixel) scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel)) scanLine += 1 px = QPixmap.fromImage(im) # Draw shadow tmp = QImage(px.size() + QSize(radius * 2, radius * 2 + 1), QImage.Format_ARGB32_Premultiplied) tmp.fill(Qt.transparent) tmpPainter = QPainter(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_Source) tmpPainter.drawPixmap(QPoint(radius, radius), px) tmpPainter.end() # blur the alpha channel blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied) blurred.fill(Qt.transparent) blurPainter = QPainter(blurred) # todo : blur image blurPainter.end() tmp = blurred # blacken the image tmpPainter.begin(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmpPainter.fillRect(tmp.rect(), color) tmpPainter.end() tmpPainter.begin(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmpPainter.fillRect(tmp.rect(), color) tmpPainter.end() # draw the blurred drop shadow... cachePainter.drawImage(QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp) # Draw the actual pixmap... cachePainter.drawPixmap(QPoint(radius, radius) + offset, px) QPixmapCache.insert(pixmapName, cache) targetRect = cache.rect() targetRect.moveCenter(rect.center()) p.drawPixmap(targetRect.topLeft() - offset, cache)
def _set_pixmap_from_camera(self): data = self.camera.get_image_buffer() bpl = self.camera.bytes_per_line format = QImage.Format_RGB32 image = QImage(data, self.camera.width, self.camera.height, bpl, format) self.setPixmap(QPixmap.fromImage(image))
def image(self): if self._image_as_pixmap is None and self.picture_data: # Caution ! QImage and stuff work only if QApplication has been initialized ! image = QImage.fromData(QByteArray(self.picture_data)) self._image_as_pixmap = QPixmap.fromImage(image.convertToFormat(QImage.Format_RGB16, Qt.MonoOnly).scaledToHeight(128)) return self._image_as_pixmap
def convertTextureSize(texturePath): if int(cmds.about(v=1)) < 2017: from PySide import QtCore from PySide.QtGui import QPixmap, QImage from PySide.QtCore import QFile, QIODevice else: from PySide2 import QtCore from PySide2.QtGui import QPixmap, QImage from PySide2.QtCore import QFile, QIODevice folder, fileName = ntpath.split(texturePath) origFileName = fileName if fileName[: 8] != 'resized_' else fileName[ 8:] origPath = folder + '/' + origFileName if not os.path.exists(origPath): cmds.warning("original is not exists : %s" % texturePath) return convertedFileName = 'resized_%d_' % ( int(resolusion)) + origFileName renamedPath = folder + "/" + convertedFileName ext = os.path.splitext(fileName)[-1] img = QImage(origPath) pixmap = QPixmap() pixmap = pixmap.fromImage( img.scaled(int(resolusion), int(resolusion), QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.FastTransformation)) qfile = QFile(renamedPath) qfile.open(QIODevice.WriteOnly) pixmap.save(qfile, ext[1:], 100) qfile.close() return renamedPath
def mouseMoveEvent(self, e): """Creates a QDrag object with a LabelTextMime containing this label's text. """ drag = QDrag(self) drag.setMimeData(LabelTextMime(self.text)) drag.setPixmap(QPixmap.fromImage(self.createPixmap())) dropAction = drag.start(Qt.MoveAction)
def sendMediaVideoFile(self,jid,video,image): self._d("creating VIDEO MMS for " +jid + " - file: " + video) fmsg = WAXMPP.message_store.createMessage(jid); if image == "NOPREVIEW": m = hashlib.md5() url = QtCore.QUrl(video).toEncoded() m.update(url) image = WAConstants.THUMBS_PATH + "/screen/" + m.hexdigest() + ".jpeg" else: image = image.replace("file://","") user_img = QImage(image) if user_img.height() > user_img.width(): preimg = QPixmap.fromImage(QImage(user_img.scaledToWidth(64, Qt.SmoothTransformation))) elif user_img.height() < user_img.width(): preimg = QPixmap.fromImage(QImage(user_img.scaledToHeight(64, Qt.SmoothTransformation))) else: preimg = QPixmap.fromImage(QImage(user_img.scaled(64, 64, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation))) preimg.save(WAConstants.CACHE_PATH+"/temp2.png", "PNG") f = open(WAConstants.CACHE_PATH+"/temp2.png", 'r') stream = base64.b64encode(f.read()) f.close() mediaItem = WAXMPP.message_store.store.Media.create() mediaItem.mediatype_id = 4 mediaItem.local_path = video.replace("file://","") mediaItem.transfer_status = 0 mediaItem.preview = stream try: mediaItem.size = os.path.getsize(mediaItem.local_path) except: pass fmsg.content = QtCore.QCoreApplication.translate("WAEventHandler", "Video") fmsg.Media = mediaItem if fmsg.Conversation.type == "group": contact = WAXMPP.message_store.store.Contact.getOrCreateContactByJid(self.conn.jid) fmsg.setContact(contact); fmsg.setData({"status":0,"content":fmsg.content,"type":1}) WAXMPP.message_store.pushMessage(jid,fmsg)
def colorbarChange(self, ind): """Handles a selection of a different colormap.""" indx = self.mapCombo.currentIndex() self.color_map_name = map_names[indx] self.color_map = getMap(self.color_map_name) self.colorbar.setPixmap(QPixmap.fromImage(ColorBarImage( self.color_map, 180, 12))) self.changeSignal.emit(ColorMap(self.color_map_name, self.color_step, self.step_size), self.tag)
def __webcam(self): capture = cv.CaptureFromCAM(-1) for i in range(10): frame = cv.QueryFrame(capture) if not frame: return arr = self.__cv2array(frame) image = self.__toQImage(arr) image = image.rgbSwapped() self.__ui.photo_label.setPixmap(QPixmap.fromImage(image).scaled(self.__ui.photo_label.size(),Qt.KeepAspectRatio))
def colorbarChange(self, ind): """Handles a selection of a different colormap.""" indx = self.mapCombo.currentIndex() self.color_map_name = map_names[indx] self.color_map = getMap(self.color_map_name) self.colorbar.setPixmap( QPixmap.fromImage(ColorBarImage(self.color_map, 180, 12))) self.changeSignal.emit( ColorMap(self.color_map_name, self.color_step, self.step_size), self.tag)
def drawBaseImage(self, viewIndex=(0, 1, 2), eraseOthers=True): for i in viewIndex: imageArray3d = self.get2D(i) height, width, bytesPerComponent = imageArray3d.shape imageArray = imageArray3d.flatten() bytesPerLine = bytesPerComponent * width image = QImage(imageArray, width, height, bytesPerLine, QImage.Format_RGB888) #image = image.scaled( int(width*self.zoomFactors[i]), int(height*self.zoomFactors[i]), Qt.KeepAspectRatio, Qt.SmoothTransformation) image = image.scaled(int(width * self.zoomFactors[i]), int(height * self.zoomFactors[i]), QtCore.Qt.KeepAspectRatio) if self.sceneItems[i] is not None: #self.scenes[i].removeItem(self.sceneItems[i]) self.sceneItems[i].setPixmap(QPixmap.fromImage(image)) if False: items = self.scenes[i].items() for item in items: self.scenes[i].removeItem(item) self.sceneItems[i] = self.scenes[i].addPixmap( QPixmap.fromImage(image)) for item in items[1:]: self.scenes[i].additem(item) del items else: self.sceneItems[i] = self.scenes[i].addPixmap( QPixmap.fromImage(image)) if eraseOthers: for item in self.scenes[i].items(): if item != self.sceneItems[i]: self.scenes[i].removeItem(item) # TODO: where to put this self.drawHbPts(self.hbRight) self.drawHb(self.hbRight) self.drawHbPts(self.hbLeft) self.drawHb(self.hbLeft)
def setup_video_frames(self): ''' set up spots for playing video frames ''' filler_frame = np.zeros((360, 540, 3)) filler_frame = qimage2ndarray.array2qimage(filler_frame) self.raw_frame = QFrame(self) self.raw_label = QLabel() self.raw_label.setText('raw') self.raw_frame.setGeometry( QRect(self.window_width * .01, self.window_height * .15, self.video_width, self.video_height)) self.raw_frame raw_layout = QVBoxLayout() self.raw_frame.setLayout(raw_layout) raw_layout.addWidget(self.raw_label) self.threshed_frame = QFrame(self) self.threshed_label = QLabel() self.threshed_label.setText('Threshed') self.threshed_frame.setGeometry( QRect(self.window_width * .51, self.window_height * .15, self.video_width, self.video_height)) threshed_layout = QVBoxLayout() self.threshed_frame.setLayout(threshed_layout) threshed_layout.addWidget(self.threshed_label) self.label_frame = QFrame(self) self.label_frame.setGeometry( QRect(self.window_width * .01, self.window_height * .11, self.video_width * 2, 50)) self.label_rawlabel = QLabel() self.label_rawlabel.setText('Raw Video') self.label_threshedlabel = QLabel() self.label_threshedlabel.setText('Threshold View') label_layout = QHBoxLayout() self.label_frame.setLayout(label_layout) label_layout.addWidget(self.label_rawlabel) label_layout.addWidget(self.label_threshedlabel) self.raw_label.setPixmap(QPixmap.fromImage(filler_frame)) self.threshed_label.setPixmap(QPixmap.fromImage(filler_frame))
def __init__(self, svgImage, width, height, parent=None): super(SvgButton, self).__init__(parent) svg_renderer = QSvgRenderer(svgImage) image = QImage(width, height, QImage.Format_ARGB32) # Set the ARGB to 0 to prevent rendering artifacts image.fill(0x00000000) svg_renderer.render(QPainter(image)) pixmap = QPixmap.fromImage(image) icon = QIcon(pixmap) self.setIcon(icon) self.setIconSize(QSize(width, height))
def transformAction(self): try: #three algorithm if self.transform == 'Morphing': self.oriImg = np.array(Image.open(self.oriPath)) self.protoImg = np.array(Image.open(self.protoPath)) newImg = morphingAction((self.oriPath).encode('utf-8'), self.protoPath.encode('utf-8'), self.oriPointsPath.encode('utf-8'), self.protoPointsPath.encode('utf-8'), self.alpha) else: localParas, points = preprocess(self.oriPath, self.protoPath, self.oriPointsPath, self.protoPointsPath, self.regionsPath, 'L2') if points == None: QtGui.QMessageBox.information(self, "Error", localParas) return self.oriImg, self.protoImg, self.regionsPoints, self.is_in_regions_fun, self.distance_funs, self.affine_funs = localParas self.oriPlotDict, self.protoPlotDict, self.oriPoints, self.protoPoints = points if self.oriImg.shape[len(self.oriImg.shape) - 1] != self.protoImg.shape[ len(self.protoImg.shape) - 1]: QtGui.QMessageBox.information( self, "Error", "The type of the figures is not the same, please choose another figure" ) return if self.transform == 'Local Affine Transformation': newImg = local_affine(self.oriImg, self.protoImg, self.e, self.regionsPoints, self.is_in_regions_fun, self.distance_funs, self.affine_funs) elif self.transform == "Moving Least Squares": newImg = MLS(self.oriImg, self.protoImg, self.oriPoints, self.protoPoints, self.alpha) except BaseException: QtGui.QMessageBox.information( self, "Error", "There are error in the point choice or other things.") newImg = morphingAction((self.oriPath).encode('utf-8'), self.protoPath.encode('utf-8'), self.oriPointsPath.encode('utf-8'), self.protoPointsPath.encode('utf-8'), self.alpha) self.newImg = np.uint8(newImg) newImg = rgb2bgr(np.uint8(newImg)) qimage = QImage(newImg, newImg.shape[1], newImg.shape[0], QImage.Format_ARGB32) pixmap_array = QPixmap.fromImage(qimage) self.transLabel.setPixmap(pixmap_array)
def _set_image(self, color1, color2): xpm = ['17 17 3 1', # width height ncolors chars_per_pixel '0 c None', 'X c {}'.format(color1.name()), '- c {}'.format(color2.name()) ] xpm += [s.strip() for s in self.ascii_led.splitlines()] qim = QImage(xpm) pix = QPixmap.fromImage(qim) self.setPixmap(pix)
def __init__(self, parent=None): self.hamburger = QImage(128, 128, QImage.Format_ARGB32) QPushButton.__init__(self, parent) self.svgrenderer = QSvgRenderer("icons\\hamburger.svg") paint = QPainter(self.hamburger) paint.setRenderHint(QPainter.HighQualityAntialiasing) paint.setRenderHint(QPainter.SmoothPixmapTransform) self.svgrenderer.render(paint) paint.end() pixmap = QPixmap() self.setIcon(QIcon(pixmap.fromImage(self.hamburger))) self.setStyleSheet("QPushButton, QPushButton:pressed{background-color: rgba(0,0,0,0)} QPushButton:hover {background-color: rgba(255,255,255,100); border-radius: 32px} ")
def sendMediaImageFile(self,jid,image): image = image.replace("file://","") user_img = QImage(image) if user_img.height() > user_img.width(): preimg = QPixmap.fromImage(QImage(user_img.scaledToWidth(64, Qt.SmoothTransformation))) elif user_img.height() < user_img.width(): preimg = QPixmap.fromImage(QImage(user_img.scaledToHeight(64, Qt.SmoothTransformation))) else: preimg = QPixmap.fromImage(QImage(user_img.scaled(64, 64, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation))) preimg.save(WAConstants.CACHE_PATH+"/temp2.png", "PNG") f = open(WAConstants.CACHE_PATH+"/temp2.png", 'r') stream = base64.b64encode(f.read()) f.close() self._d("creating PICTURE MMS for " +jid + " - file: " + image) fmsg = WAXMPP.message_store.createMessage(jid); mediaItem = WAXMPP.message_store.store.Media.create() mediaItem.mediatype_id = 2 mediaItem.local_path = image mediaItem.transfer_status = 0 mediaItem.preview = stream try: mediaItem.size = os.path.getsize(mediaItem.local_path) except: pass fmsg.content = QtCore.QCoreApplication.translate("WAEventHandler", "Image") fmsg.Media = mediaItem if fmsg.Conversation.type == "group": contact = WAXMPP.message_store.store.Contact.getOrCreateContactByJid(self.conn.jid) fmsg.setContact(contact); fmsg.setData({"status":0,"content":fmsg.content,"type":1}) WAXMPP.message_store.pushMessage(jid,fmsg)
def convert_bitmap(image, width=None, height=None): if isinstance(image, ImageResource): pix = traitsui_convert_bitmap(image) elif isinstance(image, Image): data = image.tostring('raw', 'RGBA') im = QImage(data, image.size[0], image.size[1], QImage.Format_ARGB32) pix = QPixmap.fromImage(QImage.rgbSwapped(im)) else: s = image.shape if len(s) >= 2: pix = QPixmap.fromImage(array2qimage(image)) else: pix = QPixmap() if pix: if width > 0 and height > 0: pix = pix.scaled(width, height) elif width > 0: pix = pix.scaledToWidth(width) if height > 0: pix = pix.scaledToHeight(height) return pix
class CheckBox(QCheckBox): def __init__(self, *args): super(CheckBox, self).__init__(*args) self.setMouseTracking(True) if tuple() in [type(i) for i in args]: for arg in args: if isinstance(arg) == tuple(): color = arg else: color = (QColor(0, 150, 136), QColor(255, 255, 255)) self.color1 = color[0] self.color2 = color[1] self.svgrenderer = QSvgRenderer("icons\\check.svg") self.check = QImage(500, 200, QImage.Format_ARGB32) self.resize(30, 30) paint = QPainter(self.check) self.svgrenderer.render(paint) paint.end() def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.HighQualityAntialiasing) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.SmoothPixmapTransform) self.img = QPixmap() if self.isChecked(): painter.setBrush(self.color1) painter.drawRoundedRect(QRect(-1, -1, 31, 31), 7, 7) painter.drawPixmap(QRect(-2, -5, 35, 40), self.img.fromImage(self.check)) else: pen = QPen() pen.setWidth(2) painter.setPen(pen) # hand draw rect painter.drawLine(QPoint(0, 0), QPoint(30, 0)) painter.drawLine(QPoint(30, 0), QPoint(30, 30)) painter.drawLine(QPoint(0, 0), QPoint(0, 30)) painter.drawLine(QPoint(0, 30), QPoint(30, 30)) painter.end() def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: if self.isChecked(): self.setChecked(False) else: self.setChecked(True) self.repaint()
def __init__(self, parent=None): self.hamburger = QImage(128, 128, QImage.Format_ARGB32) QPushButton.__init__(self, parent) self.svgrenderer = QSvgRenderer("icons\\hamburger.svg") paint = QPainter(self.hamburger) paint.setRenderHint(QPainter.HighQualityAntialiasing) paint.setRenderHint(QPainter.SmoothPixmapTransform) self.svgrenderer.render(paint) paint.end() pixmap = QPixmap() self.setIcon(QIcon(pixmap.fromImage(self.hamburger))) self.setStyleSheet( "QPushButton, QPushButton:pressed{background-color: rgba(0,0,0,0)} QPushButton:hover {background-color: rgba(255,255,255,100); border-radius: 32px} " )
def _update(self): # w, h = self.control.width(), self.control.height() # img = self.value.get_image_data(size=(w, h)) img = self.value.get_image_data() if img is not None: s = img.shape if s: im = QImage(img, s[1], s[0], QImage.Format_RGB32) # im = QImage(img, s[1], s[0], QImage.Format_RGB16) if self.swap: im = QImage.rgbSwapped(im) pix = QPixmap.fromImage(im) self.control.setPixmap(pix)
def set_yuv_image(self, img): """ Sets the spatial image as YUV array. The function expects a `uint8` array and will set the spatial domain image in the UI along with updating all internal fields. """ self.spatial_image = img img = util.yuv_to_rgb(self.spatial_image) qimage = util.numpy_to_qimage(img) pixmap = QPixmap.fromImage(qimage) self.set_image_pixmap(pixmap) self.invalidate_image_scale() self.render_image()
def play(self): self._finished = 0 path = "%s/%s" % (self._save_dir, self._options['uri']) rect = self._widget.geometry() self._img.load(path) self._img = self._img.scaled(rect.width(), rect.height(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation) self._widget.setPixmap(QPixmap.fromImage(self._img)) self._widget.show() self._widget.raise_() self._play_timer.setInterval(int(float(self._duration) * 1000)) self._play_timer.start() self.started_signal.emit()
def play(self): self.finished = 0 path = '%s/%s' % (self.save_dir, self.options['uri']) rect = self.widget.geometry() self.img.load(path) self.img = self.img.scaled(rect.width(), rect.height(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation) self.widget.setPixmap(QPixmap.fromImage(self.img)) self.widget.show() self.widget.raise_() if float(self.duration) > 0: self.play_timer.setInterval(int(float(self.duration) * 1000)) self.play_timer.start() self.started_signal.emit()
def paintEvent(self, event): if self._image is None: return QWidget.paintEvent(self, event) with paint(self) as painter: painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.HighQualityAntialiasing) pixmap = QPixmap.fromImage(self.image, Qt.AutoColor) scale_factor = 1.0 if self._scale: scale_factor = min(self.width() / pixmap.width(), self.height() / pixmap.height()) translated = (self.size() - (pixmap.size() * scale_factor)) / 2 painter.translate(translated.width(), translated.height()) painter.scale(scale_factor, scale_factor) painter.drawPixmap(0, 0, pixmap)
def resizeImage(self): if not self.image: self.ui.scrollArea.takeWidget() return w = self.ui.spinBoxWidth.value() h = self.ui.spinBoxHeight.value() img = self.image.scaled(w,h) pix = QPixmap.fromImage(img) lbl = QLabel() lbl.setPixmap(pix) self.ui.scrollArea.takeWidget() self.ui.scrollArea.setWidget(lbl)
def set_freq_image_magnitude(self, fimg): """ Sets a numpy array as a frequncy domain image magnitude. This function expects an appropriately shifted numpy array as input. Except taking log, no manipulation to the values is done before rendering. The function updates recomputes all internal intermediate values and re renders the frequency UI. """ self.frequency_array_magnitude = fimg qimage = util.fft_to_qimage(self.frequency_array_magnitude) pixmap = QPixmap.fromImage(qimage) self.set_freq_pixmap(pixmap) self.invalidate_freq_scale() self.render_freq()
def resize(self): trValue = QTransform().scale( self.transInfo.scaleX(), self.transInfo.scaleY() ) trValue *= QTransform().rotate( self.transInfo.rotValue ) imageTransformed = self.image.transformed(trValue) imageWidth = imageTransformed.width() imageHeight = imageTransformed.height() self.pixmap = QPixmap.fromImage( imageTransformed ) self.label.setPixmap( self.pixmap ) marginLeft = (self.width() - imageWidth)/2.0 marginTop = (self.height() - imageHeight)/2.0 self.label.setGeometry( marginLeft + self.transInfo.x,marginTop + self.transInfo.y, imageWidth, imageHeight )
def new_picture(self): dialog = QFileDialog() if (dialog.exec_()): filename = dialog.selectedFiles()[0] # print "ok {}".format(filename) f = open(filename,"rb") bytes = f.read(-1) f.close() image = QImage.fromData(QByteArray(bytes)) if image: # save as buffer(bytes) pixmap = QPixmap.fromImage(image.convertToFormat(QImage.Format_RGB16, Qt.MonoOnly).scaledToHeight(128)) self.set_pixmap_as_icon(pixmap)
def update_frame(self, img): ''' update the image :return: ''' #if not self.queue.empty(): # frame = self.queue.get() #img = frame['img'] img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) size = self.video_view.size() img = cv2.resize(img, (size.width() - 10, size.height() - 10)) height, width, bpc = img.shape bpl = bpc * width image = QImage(img.data, width, height, bpl, QImage.Format_RGB888) pitem = QGraphicsPixmapItem(QPixmap.fromImage(image)) scene = QGraphicsScene() scene.addItem(pitem) self.video_view.setScene(scene)
def firstPage(self): for i in range( self.mainLayout.count() ): item = self.mainLayout.itemAt(0) item.widget().setParent( None ) title = QLabel( "<p style='color:rgb( 137,129,120 )'>Welcome to the PingoTools Installer</p>" ) title.setFixedHeight( 50 ) titleFont = QFont() titleFont.setPixelSize( 18 ) titleFont.setBold( True ) titleFont.setFamily( "Helvetica [Cronyx]" ) title.setAlignment( QtCore.Qt.AlignCenter ) title.setFont( titleFont ) description = QLabel() description.setAlignment( QtCore.Qt.AlignCenter ) buttonsWidget = QWidget(); buttonsWidget.setMaximumHeight( 50 ) buttonsLayout = QHBoxLayout( buttonsWidget ) emptyArea = QLabel() buttonNext = QPushButton( 'Next > ' ) buttonCancel = QPushButton( 'Cancel' ) buttonsLayout.addWidget( emptyArea ) buttonsLayout.addWidget( buttonNext ); buttonNext.setFixedWidth( 100 ) buttonsLayout.addWidget( buttonCancel ); buttonCancel.setFixedWidth( 100 ) self.mainLayout.addWidget( title ) self.mainLayout.addWidget( description ) self.mainLayout.addWidget( buttonsWidget ) origWidth = 500 frontImage = QImage() frontImage.load( os.path.dirname( __file__ ) + '/images/pingoTools_main.jpg' ) trValue = QTransform().scale( float(origWidth)/frontImage.width(), float(origWidth)/frontImage.width() ) transformedImage = frontImage.transformed( trValue ) pixmap = QPixmap.fromImage( transformedImage ) description.setPixmap( pixmap ) description.setGeometry( 0,0, transformedImage.width() , transformedImage.height() ) description.paintEvent(QPaintEvent(QtCore.QRect( 0,0,self.width(), self.height() ))) QtCore.QObject.connect( buttonNext, QtCore.SIGNAL( 'clicked()' ), self.secondPage ) QtCore.QObject.connect( buttonCancel, QtCore.SIGNAL( 'clicked()' ), self.cmd_cancel )
def resize(self): if self.imageClean: return None trValue = QTransform().scale( self.transInfo.scaleX(), self.transInfo.scaleY() ) trValue *= QTransform().rotate( self.transInfo.rotValue ) imageTransformed = self.image.transformed(trValue) imageWidth = imageTransformed.width() imageHeight = imageTransformed.height() self.pixmap = QPixmap.fromImage( imageTransformed ) self.label.setPixmap( self.pixmap ) marginLeft = (self.width() - imageWidth)/2.0 marginTop = (self.height() - imageHeight)/2.0 self.label.setGeometry( marginLeft + self.transInfo.x,marginTop + self.transInfo.y, imageWidth, imageHeight ) self.label.paintEvent(QPaintEvent(QtCore.QRect( 0,0,self.width(), self.height() )))
def review_image(self, path): """Loads path for review """ print('MainWindow.review_image [{0}]'.format(path)) # Arbitrary delay to give the capture software time to finish writing # the image. time.sleep(1) image = cv2.imread(str(path)) if image is None: raise ValueError('Unable to read [{0}]'.format(path)) else: self._under_review = path self.setWindowTitle('') self.setWindowFilePath(str(path)) self._controls.specimen.setText(QSettings().value('specimen')) self._controls.location.setText(QSettings().value('location')) self._image_widget.set_pixmap(QPixmap.fromImage(qimage_of_bgr(image))) self._controls.image_handling.setEnabled(True)
def __init__(self, *args, **kwargs): super(Label_descriptionImage, self).__init__(*args, **kwargs) self.setAlignment(QtCore.Qt.AlignCenter) if Label_descriptionImage.descriptionImagePath: frontImage = QImage() frontImage.load(Label_descriptionImage.descriptionImagePath) origWidth = frontImage.width() trValue = QTransform().scale( float(origWidth) / frontImage.width(), float(origWidth) / frontImage.width()) transformedImage = frontImage.transformed(trValue) pixmap = QPixmap.fromImage(transformedImage) self.setPixmap(pixmap) self.setGeometry(0, 0, transformedImage.width(), transformedImage.height()) self.paintEvent( QPaintEvent(QtCore.QRect(0, 0, self.width(), self.height())))
def review_image(self, path): """Loads path for review """ print('MainWindow.review_image [{0}]'.format(path)) # Arbitrary delay to give the capture software time to finish writing # the image. time.sleep(1) image = cv2.imread(str(path)) if image is None: raise ValueError('Unable to read [{0}]'.format(path)) else: self._under_review = path self.setWindowTitle('') self.setWindowFilePath(str(path)) self._controls.specimen.setText(QSettings().value('specimen')) self._controls.location.setText(QSettings().value('location')) self._image_widget.set_pixmap( QPixmap.fromImage(qimage_of_bgr(image))) self._controls.image_handling.setEnabled(True)
def _ndarray_to_arraypixmap(array, color=(0, 255, 0, 128)): """Convert a binary array to an ArrayPixmap with specified color and alpha level Args: array -- binary ndarray color -- RGBA color tuple. [0, 255] for each channel Returns: An ArrayPixmap with of the ndarray with constant alpha value and color. The input array is colored with *color* and *alpha* anywhere it is equal to 1. """ assert array.ndim == 2, 'Only 2D arrays are supported' assert len(color) == 4, 'Color should be a 4-tuple' h, w = array.shape array = array.astype('uint32') array = (color[3] * array) << 24 \ | (color[0] * array) << 16 \ | (color[1] * array) << 8 \ | (color[2] * array) pixdata = array.flatten() img = QImage(pixdata, w, h, QImage.Format_ARGB32) return ArrayPixmap(pixdata, QPixmap.fromImage(img))
def convert_bitmap(image, width=None, height=None): pix = None if isinstance(image, ImageResource): pix = traitsui_convert_bitmap(image) else: s = image.shape if len(s) >= 2: im = QImage(image.tostring(), s[1], s[0], QImage.Format_RGB888 # QImage.Format_RGB16 ) pix = QPixmap.fromImage(QImage.rgbSwapped(im)) if pix: if width > 0 and height > 0: pix = pix.scaled(width, height) elif width > 0: pix = pix.scaledToWidth(width) if height > 0: pix = pix.scaledToHeight(height) return pix
def buildColorBarControl(self): """Builds the portion of this widget for color map selection.""" widget = QWidget() layout = QHBoxLayout() label = QLabel(self.color_map_label) self.colorbar = QLabel(self) self.colorbar.setPixmap(QPixmap.fromImage(ColorBarImage( self.color_map, 180, 15))) self.mapCombo = QComboBox(self) self.mapCombo.addItems(map_names) self.mapCombo.setCurrentIndex(map_names.index(self.color_map_name)) self.mapCombo.currentIndexChanged.connect(self.colorbarChange) layout.addWidget(label) layout.addItem(QSpacerItem(5,5)) layout.addWidget(self.mapCombo) layout.addItem(QSpacerItem(5,5)) layout.addWidget(self.colorbar) widget.setLayout(layout) return widget
def resize(self): if self.imageClean: return None trValue = QTransform().scale(self.transInfo.scaleX(), self.transInfo.scaleY()) trValue *= QTransform().rotate(self.transInfo.rotValue) imageTransformed = self.image.transformed(trValue) imageWidth = imageTransformed.width() imageHeight = imageTransformed.height() self.pixmap = QPixmap.fromImage(imageTransformed) self.label.setPixmap(self.pixmap) marginLeft = (self.width() - imageWidth) / 2.0 marginTop = (self.height() - imageHeight) / 2.0 self.label.setGeometry(marginLeft + self.transInfo.x, marginTop + self.transInfo.y, imageWidth, imageHeight) self.label.paintEvent( QPaintEvent(QtCore.QRect(0, 0, self.width(), self.height())))
def buildColorBarControl(self): """Builds the portion of this widget for color map selection.""" widget = QWidget() layout = QHBoxLayout() label = QLabel(self.color_map_label) self.colorbar = QLabel(self) self.colorbar.setPixmap( QPixmap.fromImage(ColorBarImage(self.color_map, 180, 15))) self.mapCombo = QComboBox(self) self.mapCombo.addItems(map_names) self.mapCombo.setCurrentIndex(map_names.index(self.color_map_name)) self.mapCombo.currentIndexChanged.connect(self.colorbarChange) layout.addWidget(label) layout.addItem(QSpacerItem(5, 5)) layout.addWidget(self.mapCombo) layout.addItem(QSpacerItem(5, 5)) layout.addWidget(self.colorbar) widget.setLayout(layout) return widget
def setSettings(self): """Set color, verbosity and logging options.""" self.logDock.setBgColor(self.config.get('Appearance', 'log_bg_color')) image = QImage(10, 10, QImage.Format_RGB32) image.fill(QColor(self.config.get('Appearance', 'circ_bg_color'))) image.setPixel(0, 0, QColor(0, 0, 0).rgb()) self.view.scene().setBackgroundBrush(QBrush(QPixmap.fromImage(image))) Plug.setInputVerbose = self.config.getboolean( 'LogVerbosity', 'input_chang') Plug.setOutputVerbose = self.config.getboolean( 'LogVerbosity', 'output_chang') Plug.connectVerbose = self.config.getboolean( 'LogVerbosity', 'conn_discon_io') Plug.addPlugVerbose = self.config.getboolean( 'LogVerbosity', 'adding_io') Circuit.addCircuitVerbose = self.config.getboolean( 'LogVerbosity', 'adding_circ') Circuit.removePlugVerbose = self.config.getboolean( 'LogVerbosity', 'removing_io') Circuit.removeCircuitVerbose = self.config.getboolean( 'LogVerbosity', 'removing_circ') Circuit.detailedRemoveVerbose = self.config.getboolean( 'LogVerbosity', 'detailed_rm') ClockThread.spd = self.config.getfloat( 'Clock', 'speed') if self.config.getboolean('LogHandlers', 'gui'): log.addHandler(self.logDock.handler) else: log.removeHandler(self.logDock.handler) if self.config.getboolean('LogHandlers', 'stdout'): log.addHandler(stdoutHandler) else: log.removeHandler(stdoutHandler) if self.config.getboolean('LogHandlers', 'file'): log.addHandler(fileHandler) else: log.removeHandler(fileHandler)
def drawArrow(element, painter, option): # From windows style but modified to enable AA if option.rect.width() <= 1 or option.rect.height() <= 1: return r = option.rect size = min(r.height(), r.width()) pixmap = QPixmap() pixmapName = "arrow-{0}-{1}-{2}-{3}-{4}".format( "$qt_ia", int(option.state), element, size, option.palette.cacheKey() ) if not QPixmapCache.find(pixmapName, pixmap): border = size / 5 sqsize = 2 * (size / 2) image = QImage(sqsize, sqsize, QImage.Format_ARGB32) image.fill(Qt.transparent) imagePainter = QPainter(image) imagePainter.setRenderHint(QPainter.Antialiasing, True) imagePainter.translate(0.5, 0.5) a = QPolygon() if element == QStyle.PE_IndicatorArrowUp: a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize - border, sqsize / 2) elif element == QStyle.PE_IndicatorArrowDown: a.setPoints(3, border, sqsize / 2, sqsize / 2, sqsize - border, sqsize - border, sqsize / 2) elif element == QStyle.PE_IndicatorArrowRight: a.setPoints(3, sqsize - border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border) elif element == QStyle.PE_IndicatorArrowLeft: a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border) else: pass bsx = 0 bsy = 0 if option.state & QStyle.State_Sunken: bsx = qApp.style().pixelMetric(QStyle.PM_ButtonShiftHorizontal) bsy = qApp.style().pixelMetric(QStyle.PM_ButtonShiftVertical) bounds = a.boundingRect() sx = sqsize / 2 - bounds.center().x() - 1 sy = sqsize / 2 - bounds.center().y() - 1 imagePainter.translate(sx + bsx, sy + bsy) if not (option.state & QStyle.State_Enabled): imagePainter.setBrush(option.palette.mid().color()) imagePainter.setPen(option.palette.mid().color()) else: shadow = QColor(0, 0, 0, 100) imagePainter.translate(0, 1) imagePainter.setPen(shadow) imagePainter.setBrush(shadow) foreGround = QColor(255, 255, 255, 210) imagePainter.drawPolygon(a) imagePainter.translate(0, -1) imagePainter.setPen(foreGround) imagePainter.setBrush(foreGround) imagePainter.drawPolygon(a) imagePainter.end() pixmap = QPixmap.fromImage(image) QPixmapCache.insert(pixmapName, pixmap) xOffset = r.x() + (r.width() - size) / 2 yOffset = r.y() + (r.height() - size) / 2 painter.drawPixmap(xOffset, yOffset, pixmap)
def compute(self): if self.writting is False: color,_, _, _ = self.rgbd_proxy.getData() frame = np.fromstring(color, dtype=np.uint8) frame = np.reshape(frame,(480, 640, 3)) (h, w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) # pass the blob through the network and obtain the detections and # predictions self.net.setInput(blob) detections = self.net.forward() rects = [] bounding_boxes = [] for i in range(0, detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence >self.confidence: box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") qr = QRect(QPoint(startX, endY), QPoint(endX,startY)) bounding_boxes.append(qr) rects.append(box.astype("int")) objects = self.ct.update(rects) # loop over the tracked objects faces_found = [] for (objectID, centroid) in objects.items(): faceT = TFace() tracking = False for qrects in bounding_boxes: if qrects.contains(QPoint(centroid[0],centroid[1])): faceT.tracking = True bbox = Box() (bbox.posx, bbox.posy, bbox.width,bbox.height) = qrects.getRect() faceT.boundingbox = bbox tracking = True (startX, endY , endX, startY) = qrects.getCoords() # extract the face ROI face = frame[startY:endY, startX:endX] (fH, fW) = face.shape[:2] # ensure the face width and height are sufficiently large if fW < 20 or fH < 20: continue faceBlob = cv2.dnn.blobFromImage(face, 1.0 / 255, (96, 96), (0, 0, 0), swapRB=True, crop=False) self.embedder.setInput(faceBlob) vec = self.embedder.forward() # perform classification to recognize the face preds = self.recognizer.predict_proba(vec)[0] j = np.argmax(preds) proba = preds[j] *100 if (proba < 50): name = "unknow" else: name = self.label_encoder.classes_[j] # draw the bounding box of the face along with the # associated probability text = "{}: {:.2f}%".format(name, proba) y = startY - 10 if startY - 10 > 10 else startY + 10 cv2.rectangle(frame, (startX, startY), (endX, endY), (255, 10, 150), 2) cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 10, 150), 2) faceT.name = name faceT.confidence = proba*100 break if (tracking == False): faceT.tracking = False pnt = Point() pnt.x = centroid[0] pnt.y = centroid [1] faceT.id = objectID faceT.centroid = pnt # draw both the ID of the object and the centroid of the # object on the output frame text = "ID {}".format(objectID) cv2.putText(frame, text, (centroid[0] - 10, centroid[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 10, 150), 2) cv2.circle(frame, (centroid[0], centroid[1]), 4, (255, 10, 150), -1) faces_found.append(faceT) self.faces = faces_found height, width, channel = frame.shape bytesPerLine = 3 * width qImg = QImage(frame.data, width, height, bytesPerLine, QImage.Format_RGB888) self.ui.image_label.setPixmap(QPixmap.fromImage(qImg)) return True
import numpy as np from PIL import Image from PIL import ImageOps from PySide.QtGui import QImage, QImageReader, QLabel, QPixmap, QApplication #building array arr_i = np.zeros(400 * 400 * 3).reshape(400, 400, 3) arr_i[20:100, 40:200, :] = 255 #converting to QImage img = Image.fromarray(np.uint8(arr_i)) data = img.convert('RGBA').tostring() q_img = QImage(data, img.size[0], img.size[1], QImage.Format_ARGB32) #building app with IMG app = QApplication([]) pix = QPixmap.fromImage(q_img) lbl = QLabel() lbl.setPixmap(pix) lbl.show() app.exec_() example_from_stackoverflow = ''' Image.fromarray(pix) Open I as an array: >>> I = numpy.asarray(PIL.Image.open('test.jpg')) Do some stuff to I, then, convert it back to an image: >>> im = PIL.Image.fromarray(numpy.uint8(I)) '''
def set_frame(self): ok, data = self.cap.read() shape = data.shape im = QImage(data, shape[1], shape[0], QImage.Format_RGB888) pix = QPixmap.fromImage(QImage.rgbSwapped(im)) self.label.setPixmap(pix)
def set_image(self, img, clean_visible=False): pix = QPixmap.fromImage(img) pix = pix.scaled(self.IMG_SIZE[0], self.IMG_SIZE[1], Qt.KeepAspectRatio) self.edImage.setPixmap(pix) self.edImage.setScaledContents(True) self.btnCleanImage.setVisible(clean_visible)