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 pixmap_from_image(image): # type: (QImage) -> QPixmap pixmap = QPixmap.fromImage(image) # type: QPixmap if hasattr(pixmap, "setDevicePixelRatio"): pixmap.setDevicePixelRatio(image.logicalDpiX() / 72) else: pixmap = pixmap.scaled((image.size() * 72) / image.logicalDpiX(), Qt.KeepAspectRatio, Qt.SmoothTransformation) return pixmap
def update_frame(self): # read pixle values from camera _, frame = self.vc.read() balls = [None, None] if frame.size: # display image in orange widget image = QImage(frame[:, :, ::-1].copy(), frame.shape[1], frame.shape[0], QImage.Format_RGB888) pix = QPixmap.fromImage(image).scaled( self.image_label.size(), Qt.KeepAspectRatio | Qt.FastTransformation) self.image_label.setPixmap(pix) # Convert BGR to HSV hsv_image = cv.cvtColor(frame, cv.COLOR_BGR2HSV) # accumulated_mask = np.zeros(hsv_image.shape[:2], dtype='uint8') for index, (lower, upper) in enumerate(BOUNDARIES): mask = cv.inRange(hsv_image, lower, upper) size = self.remap(np.count_nonzero(mask), 0, mask.size, 0.2, 1) rgb_value = (cv.cvtColor( np.uint8([[cv.mean(hsv_image, mask)[:3]]]), cv.COLOR_HSV2RGB).flatten()) balls[index] = (tuple(rgb_value) if rgb_value.any() else None, size) # accumulated_mask = cv.bitwise_or(accumulated_mask, mask) dominant_colors = find_image_colors(hsv_image, image_processing_size=(100, 100)) # accumulated_mask = cv.bitwise_not(accumulated_mask) # res = cv.bitwise_and(frame, frame, mask=accumulated_mask) # print(res.reshape((res.shape[0] * res.shape[1], 3)).shape) # print(cv.mean(hsv_image, accumulated_mask)) # res = cv.resize(res, (100, 100), interpolation=cv.INTER_AREA) # if res.size: # # display image in orange widget # image = QImage(res[:, :, ::-1].copy(), res.shape[1], res.shape[0], QImage.Format_RGB888) # pix = QPixmap.fromImage(image).scaled(self.image_label.size(), Qt.KeepAspectRatio | Qt.FastTransformation) # self.image_label.setPixmap(pix) # res = res.reshape((res.shape[0] * res.shape[1], 3)) # res = res[~(res == 0).all(1)] # # # print(res) # # colors = find_image_colors(res, k=6, image_processing_size=(150, 150)) return dominant_colors, balls
def nextFrameSlot(self): t = int(round(time.time() * 1000)) ret, f = self.cap.read() f = cv2.cvtColor(f, cv2.COLOR_BGR2RGB) qFormat = QImage.Format_Indexed8 if len(f.shape) == 3: if f.shape[2] == 4: qFormat = QImage.Format_RGBA8888 else: qFormat = QImage.Format_RGB888 self.image = QImage(f, f.shape[1], f.shape[0], f.strides[0], qFormat) if self.fullScreenImage is not None: img = self.fullScreenImage.findChild(ImageLabel, "image") img.setPixmap( QPixmap.fromImage( self.image.scaledToHeight(img.height() * 0.95))) else: self._page.setPixmap( QPixmap.fromImage(self.image.scaledToHeight(Config.camHeight))) self._frameLabel.setText("FPS: " + str(int(1000 / (t - self._time)))) self._time = t
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)
def update_properties(self): ## Mostly copied from OWScatterPlotGraph if not self.plot(): return if not self.rect: x,y = self.axes() self.rect = self.plot().data_rect_for_axes(x,y) s = self.graph_transform().mapRect(self.rect).size().toSize() if not s.isValid(): return rx = s.width() ry = s.height() rx -= rx % self.granularity ry -= ry % self.granularity p = self.graph_transform().map(QPointF(0, 0)) - self.graph_transform().map(self.rect.topLeft()) p = p.toPoint() ox = p.x() oy = -p.y() if self.classifier.classVar.is_continuous: imagebmp = orangeom.potentialsBitmap(self.classifier, rx, ry, ox, oy, self.granularity, self.scale) palette = [qRgb(255.*i/255., 255.*i/255., 255-(255.*i/255.)) for i in range(255)] + [qRgb(255, 255, 255)] else: imagebmp, nShades = orangeom.potentialsBitmap(self.classifier, rx, ry, ox, oy, self.granularity, self.scale, self.spacing) palette = [] sortedClasses = get_variable_values_sorted(self.classifier.domain.classVar) for cls in self.classifier.classVar.values: color = self.plot().discPalette.getRGB(sortedClasses.index(cls)) towhite = [255-c for c in color] for s in range(nShades): si = 1-float(s)/nShades palette.append(qRgb(*tuple([color[i]+towhite[i]*si for i in (0, 1, 2)]))) palette.extend([qRgb(255, 255, 255) for i in range(256-len(palette))]) self.potentialsImage = QImage(imagebmp, rx, ry, QImage.Format_Indexed8) self.potentialsImage.setColorTable(palette) self.potentialsImage.setNumColors(256) self.pixmap_item.setPixmap(QPixmap.fromImage(self.potentialsImage)) self.pixmap_item.setPos(self.graph_transform().map(self.rect.bottomLeft()))
def fullscreen(self): if not self.isImageFullscreen: cam = QMainWindow(self) panel = QWidget(cam) panel.layout = QHBoxLayout(panel) panel.setLayout(panel.layout) image = ImageLabel(panel) image.setAlignment(Qt.AlignCenter) image.setObjectName("image") image.mReleased.connect(cam.parent().fullscreen) image.setPixmap(QPixmap.fromImage(cam.parent().image)) panel.layout.addWidget(image) cam.setCentralWidget(panel) cam.showFullScreen() cam.parent().isImageFullscreen = True cam.parent().fullScreenImage = cam else: self.fullScreenImage.close() self.fullScreenImage = None self.isImageFullscreen = False
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()
def setupScene(self): self.error() if self.data: attr = self.stringAttrs[self.imageAttr] titleAttr = self.allAttrs[self.titleAttr] assert self.thumbnailView.count() == 0 size = QSizeF(self.imageSize, self.imageSize) for i, inst in enumerate(self.data): if not numpy.isfinite(inst[attr]): # skip missing continue 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()
def setStamp(self, stamp): self.stamp = stamp self.setPixmap(QPixmap.fromImage(ImageQt.ImageQt(im_numbers[stamp]), flags=Qt.AutoColor))
def setup_scene(self, process_grid=True): self.clear_scene() self.error() if self.data: attr = self.stringAttrs[self.imageAttr] assert self.thumbnailView.count() == 0 size = QSizeF(self.imageSize, self.imageSize) if process_grid and self.image_grid: self.process() self.columns = self.image_grid.size_x self.rows = self.image_grid.size_y self.thumbnailView.setFixedColumnCount(self.columns) self.thumbnailView.setFixedRowCount(self.rows) for i, inst in enumerate(self.image_grid.image_list): label_text = (str(inst[self.label_attr]) if self.label_attr is not None else "") if label_text == "?": label_text = "" thumbnail = GraphicsThumbnailWidget( QPixmap(), crop=self.cell_fit == 1, add_label=self.label_selected and self.label_attr is not None, text=label_text) thumbnail.setThumbnailSize(size) thumbnail.instance = inst self.thumbnailView.addThumbnail(thumbnail) if not np.isfinite(inst[attr]) or inst[attr] == "?": # skip missing future, url = None, None else: url = self.url_from_value(inst[attr]) thumbnail.setToolTip(url.toString()) self.nonempty.append(i) 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._note_completed(future) else: future = None self.items.append(_ImageItem(i, thumbnail, url, future)) if not any(not it.future.done() if it.future else False for it in self.items): self._update_status() self.apply_subset() self.update_selection()
def init_style_option( delegate: QStyledItemDelegate, option: QStyleOptionViewItem, index: QModelIndex, data: Mapping[int, Any], roles: Optional[Container[int]] = None, ) -> None: """ Like `QStyledItemDelegate.initStyleOption` but fill in the fields from `data` mapping. If `roles` is not `None` init the `option` for the specified `roles` only. """ # pylint: disable=too-many-branches option.styleObject = None option.index = index if roles is None: roles = data features = 0 if Qt.DisplayRole in roles: value = data.get(Qt.DisplayRole) if value is not None: option.text = delegate.displayText(value, option.locale) features |= _QStyleOptionViewItem_HasDisplay if Qt.FontRole in roles: value = data.get(Qt.FontRole) font = cast_(QFont, value) if font is not None: font = font.resolve(option.font) option.font = font option.fontMetrics = QFontMetrics(option.font) if Qt.ForegroundRole in roles: value = data.get(Qt.ForegroundRole) foreground = cast_(QBrush, value) if foreground is not None: option.palette.setBrush(QPalette.Text, foreground) if Qt.BackgroundRole in roles: value = data.get(Qt.BackgroundRole) background = cast_(QBrush, value) if background is not None: option.backgroundBrush = background if Qt.TextAlignmentRole in roles: value = data.get(Qt.TextAlignmentRole) alignment = cast_(int, value) if alignment is not None: alignment = alignment & _AlignmentMask option.displayAlignment = _AlignmentCache[alignment] if Qt.CheckStateRole in roles: state = data.get(Qt.CheckStateRole) if state is not None: features |= _QStyleOptionViewItem_HasCheckIndicator state = cast_(int, state) if state is not None: option.checkState = state if Qt.DecorationRole in roles: value = data.get(Qt.DecorationRole) if value is not None: features |= _QStyleOptionViewItem_HasDecoration if isinstance(value, QIcon): option.icon = value elif isinstance(value, QColor): pix = QPixmap(option.decorationSize) pix.fill(value) option.icon = QIcon(pix) elif isinstance(value, QPixmap): option.icon = QIcon(value) option.decorationSize = (value.size() / value.devicePixelRatio()).toSize() elif isinstance(value, QImage): pix = QPixmap.fromImage(value) option.icon = QIcon(value) option.decorationSize = (pix.size() / pix.devicePixelRatio()).toSize() option.features |= features
def __init__(self, parent=None, *, mime=None, image=None): QDialog.__init__(self, parent) self.setupUi(self) self._backend = None self._backend_controls = {} self._label_anonymous = self.tr('Anonymous') self._label_select_login = self.tr('Select Login') self._available_backends = [] data = None file_name = None if image: self._share_type = Bi.Image data = image elif mime: if mime.hasImage(): self._share_type = Bi.Image data = mime.imageData() elif mime.hasUrls(): urls = mime.urls() if len(urls) == 1: file_path = os.path.realpath(urls[0].toLocalFile()) if not os.path.isfile(file_path): raise ValueError(self.tr('Directories can not be shared')) file_size = os.path.getsize(file_path) file_name = os.path.basename(file_path) if file_size > const.BIG_FILE_WARNING_SIZE: file_name = os.path.basename(file_path) nice_size = format_size(file_size) result = QMessageBox.warning(self, self.tr('Warning'), self.tr('File "{file_name}" {nice_size}.\n' 'Are you sure you want to continue?').format(**locals()), QMessageBox.Yes | QMessageBox.Abort) if result == QMessageBox.Abort: QTimer.singleShot(0, self.reject) return if file_has_extension(file_path, ('png', 'jpg', 'jpeg', 'bmp', 'gif')): image = QPixmap(file_path) else: image = None if not image or image.isNull(): data = read_text_from_file(file_path) if data: self._share_type = Bi.Text else: self._share_type = Bi.File data = file_path else: self._share_type = Bi.Image data = image else: raise ValueError(self.tr('Can not share more than one file')) elif mime.hasText(): self._share_type = Bi.Text data = mime.text() else: raise RuntimeError() if not data: raise ValueError(self.tr('There is no content in your clipboard.\nCopy something in order to share it.')) if self._share_type == Bi.Image: if not file_name: file_name = '{}-{}.png'.format('screenshot' if image else 'image', int(time())) if data.width() > self.image_preview.width() or data.height() > self.image_preview.height(): preview = data.scaled(self.image_preview.size(), Qt.KeepAspectRatio) else: preview = data if isinstance(preview, QImage): preview = QPixmap.fromImage(preview) self.image_preview.setPixmap(preview) self.preview_stack.setCurrentIndex(0) buf = QBuffer() data.save(buf, 'png', 100) data = buf.data().data() elif self._share_type == Bi.Text: if not file_name: file_name = 'file-{}.txt'.format(int(time())) self.text_preview.setPlainText(dedent_text_and_truncate(data, 128)) self.preview_stack.setCurrentIndex(1) elif self._share_type == Bi.File: if not file_name: file_name = 'file-{}.bin'.format(int(time())) self.text_preview.setPlainText(self.tr('No preview available')) self.preview_stack.setCurrentIndex(1) self._file_name = file_name self._data = data self.populate_backends() self.share.pressed.connect(self.share_item) self.add_login.pressed.connect(self.on_add_login) self.logout.pressed.connect(self.logout_selected) self.login_list.currentIndexChanged.connect(self.select_login) min_height = self.backend_selector.minimumSizeHint().height() if os.name == 'nt': # On windows tab widget and font are rather small min_height -= 5 for el in (self.add_login, self.login_list, self.logout, self.share): font = el.font() font.setPointSize(12) el.setFont(font) self.login_list.setFixedHeight(self.add_login.height() - 2) self.backend_selector.setFixedHeight(min_height) self.backend_selector.currentChanged.connect(self.select_backend) if self.backend_selector.height() < self.add_login.height(): # Move tab widget down based on size of controls on the right. Makes widgets below seem to belong to the # selected tab. self.backend_selector.move(0, self.add_login.height() - self.backend_selector.height()) self.resize(self.width(), 0) self.setWindowState((self.windowState() & ~Qt.WindowMinimized) | Qt.WindowActive) self.raise_() self.activateWindow()
def setup_scene(self, process_grid=True): self.error() if self.data: attr = self.stringAttrs[self.imageAttr] assert self.thumbnailView.count() == 0 size = QSizeF(self.imageSize, self.imageSize) if process_grid and self.image_grid: self.process() self.columns = self.image_grid.size_x self.rows = self.image_grid.size_y self.thumbnailView.setFixedColumnCount(self.columns) self.thumbnailView.setFixedRowCount(self.rows) for i, inst in enumerate(self.image_grid.image_list): thumbnail = GraphicsThumbnailWidget(QPixmap(), crop=self.cell_fit == 1) thumbnail.setThumbnailSize(size) thumbnail.instance = inst self.thumbnailView.addThumbnail(thumbnail) if not np.isfinite(inst[attr]) or inst[attr] == "?": # skip missing future, url = None, None else: url = self.url_from_value(inst[attr]) thumbnail.setToolTip(url.toString()) self.nonempty.append(i) 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._note_completed(future) else: future = None self.items.append(_ImageItem(i, thumbnail, url, future)) if any(not it.future.done() if it.future else False for it in self.items): self.info.setText("Retrieving...\n") else: self._update_status() self.apply_subset() self.update_selection()