def _init_images(self): A, = 'A'.encode('ascii') gs = Qt.QGraphicsScene() sti = Qt.QGraphicsSimpleTextItem() sti.setFont(Qt.QFont('Courier', pointSize=24, weight=Qt.QFont.Bold)) gs.addItem(sti) self.images = [] for char in range(A, A + 26): for i in range(0, 10): text = bytes([char]).decode('ascii') + str(i) sti.setText(text) scene_rect_f = gs.itemsBoundingRect() scene_rect = Qt.QRect( 0, 0, math.ceil(scene_rect_f.width()), math.ceil(scene_rect_f.height())) gs.setSceneRect(scene_rect_f) buffer = numpy.empty((scene_rect.height(), scene_rect.width(), 4), dtype=numpy.uint8) buffer[:] = 255 qimage = Qt.QImage(sip.voidptr(buffer.ctypes.data), scene_rect.size().width(), scene_rect.size().height(), Qt.QImage.Format_RGBA8888) qpainter = Qt.QPainter() qpainter.begin(qimage) qpainter.setRenderHint(Qt.QPainter.Antialiasing) qpainter.setRenderHint(Qt.QPainter.HighQualityAntialiasing) gs.render(qpainter) qpainter.end() self.images.append(Image(buffer.copy(), shape_is_width_height=False, name=text))
def write_roi_mask_files(data_dir, rois): """ Create a "Focus Masks" directory of ROIs for timecourse acquisitions. Focus ROIs obtained from get_positions_with_roi() will be converted to mask images and written to "Focus Masks" in the experiment directory. NOTE: focus ROIs are used ONLY in fine-focus-only mode. They will be ignored if DO_COARSE_FOCUS is True. Parameters: data_dir: directory to write metadata file into rois: list of Qt.QRectFs describing the bounds of an elliptical ROI within which autofocus scores will be calculated, OR dict mapping different category names to lists of Qt.QRectFs. """ mask_dir = pathlib.Path(data_dir) / 'Focus Masks' mask_dir.mkdir(parents=True, exist_ok=True) image = Qt.QImage(2560, 2160, Qt.QImage.Format_Grayscale8) painter = Qt.QPainter() try: items = rois.items() except AttributeError: items = [('', rois)] for name_prefix, rois in items: names = _name_positions(len(rois), name_prefix) for name, roi in zip(names, rois): image.fill(Qt.Qt.black) painter.begin(image) painter.setBrush(Qt.Qt.white) painter.drawEllipse(roi) painter.end() image.save(str(mask_dir / name) + '.png') del image # image must be deleted before painter to avoid warning. So delete now...
def adaptive_resize(self): if self.img is None: dummy_img = np.ones((5, 5, 3)).astype(np.uint8) * 43 height, width, channel = dummy_img.shape q_image = Qt.QImage(dummy_img.data, width, height, 3 * width, Qt.QImage.Format_RGB888).rgbSwapped() self.img = Qt.QPixmap.fromImage(q_image) image_width = self.img.width() image_height = self.img.height() image_w_h_ratio = image_width / image_height parent_w_h_ratio = self.width() / self.height() if image_w_h_ratio > parent_w_h_ratio: # 横向撑满 target_width = self.width() target_height = image_height * target_width / image_width self.setGeometry(0, 0, self.width(), self.height()) self.point_center = Qt.QPoint(0, (self.height() - target_height) // 2) self.point = self.point_center else: # 纵向撑满 target_height = self.height() target_width = image_width * target_height / image_height self.setGeometry(0, 0, self.width(), self.height()) self.point_center = Qt.QPoint((self.width() - target_width) // 2, 0) self.point = self.point_center self.initial_size = Qt.QSize(target_width, target_height) self.scaled_img = self.img.scaled(Qt.QSize(target_width, target_height))
def qImage(cvIm): """ Create QImage from cv2 image. """ h, w, ch = cvIm.shape qim = qt.QImage(cvIm.data, w, h, w * ch, qt.QImage.Format_RGB888) return qim.rgbSwapped()
def Rgb_update(self): if self.rgb_picture: im = cv2.imread(self.path) image = b.rgbBin(im, self.R_val_spin.value(), self.G_val_spin.value(), self.B_val_spin.value()) pximage = Qt.QPixmap.fromImage(Qt.QImage("george.jpg")) self.show(pximage)
def toBlack_white(self): self.rgb_picture = False self.is_manual = False im = cv2.imread(self.path) imG = b.greyscale(im) im2 = Qt.QImage("george.jpg") pximage = Qt.QPixmap.fromImage(im2) self.show(pximage)
def Adapt(self): self.rgb_picture = False self.is_manual = False im = cv2.imread(self.path) grey = b.greyscale(im) imG = b.adaptive_bin(grey) pximage = Qt.QPixmap.fromImage(Qt.QImage("george.jpg")) self.show(pximage)
def OtsuBin(self): self.rgb_picture = False self.is_manual = False im = cv2.imread(self.path) im_grey = b.greyscale(im) im_otsu = b.otsu(im_grey) pximage = Qt.QPixmap.fromImage(Qt.QImage("george.jpg")) self.show(pximage)
def render_raw_videoframe( self, vs_frame: vs.VideoFrame, vs_frame_alpha: Optional[vs.VideoFrame] = None) -> Qt.QPixmap: # powerful spell. do not touch frame_data_pointer = ctypes.cast( vs_frame.get_read_ptr(0), ctypes.POINTER(ctypes.c_char * (vs_frame.format.bytes_per_sample * vs_frame.width * vs_frame.height)))[0] frame_image = Qt.QImage(frame_data_pointer, vs_frame.width, vs_frame.height, vs_frame.get_stride(0), Qt.QImage.Format_RGB32) if vs_frame_alpha is None: result_pixmap = Qt.QPixmap.fromImage(frame_image) else: alpha_data_pointer = ctypes.cast( vs_frame_alpha.get_read_ptr(0), ctypes.POINTER( ctypes.c_char * (vs_frame_alpha.format.bytes_per_sample * vs_frame_alpha.width * vs_frame_alpha.height)))[0] alpha_image = Qt.QImage(alpha_data_pointer, vs_frame.width, vs_frame.height, vs_frame_alpha.get_stride(0), Qt.QImage.Format_Alpha8) result_image = Qt.QImage(vs_frame.width, vs_frame.height, Qt.QImage.Format_ARGB32_Premultiplied) painter = Qt.QPainter(result_image) painter.setCompositionMode(Qt.QPainter.CompositionMode_Source) painter.drawImage(0, 0, frame_image) painter.setCompositionMode( Qt.QPainter.CompositionMode_DestinationIn) painter.drawImage(0, 0, alpha_image) painter.end() result_pixmap = Qt.QPixmap.fromImage(result_image) return result_pixmap
def numpy_array_to_QImage(numpy_array): if numpy_array.dtype != np.uint8: return height, width = numpy_array.shape[:2] if len(numpy_array.shape) == 2: img = Qt.QImage(numpy_array.data, width, height, numpy_array.strides[0], Qt.QImage.Format_Indexed8) img.setColorTable(GRAY_COLOR_TABLE) return img elif len(numpy_array.shape) == 3: if numpy_array.shape[2] == 3: img = Qt.QImage(numpy_array.data, width, height, numpy_array.strides[0], Qt.QImage.Format_RGB888) return img elif numpy_array.shape[2] == 4: img = Qt.QImage(numpy_array.data, width, height, numpy_array.strides[0], Qt.QImage.Format_ARGB32) return img
def load(fpath): im = Qt.QImage(str(fpath)).scaledToHeight(height) setattr(self, 'low_' + fpath.stem + '_pm', Qt.QPixmap.fromImage(im)) setattr(self, 'high_' + fpath.stem + '_pm', Qt.QPixmap.fromImage(im.transformed(flip))) setattr( self, 'low_' + fpath.stem + '_tt', fpath.stem[0].capitalize() + fpath.stem[1:].replace('_', ' ') + ' reached.') setattr( self, 'high_' + fpath.stem + '_tt', fpath.stem[0].capitalize() + fpath.stem[1:].replace('_', ' ') + ' reached.')
def render_raw_videoframe( self, vs_frame: vs.VideoFrame, vs_frame_alpha: Optional[vs.VideoFrame] = None) -> Qt.QImage: # powerful spell. do not touch frame_data_pointer = ctypes.cast( vs_frame.get_read_ptr(0), ctypes.POINTER(ctypes.c_char * (vs_frame.format.bytes_per_sample * vs_frame.width * vs_frame.height))) frame_image = Qt.QImage(frame_data_pointer.contents, vs_frame.width, vs_frame.height, vs_frame.get_stride(0), Qt.QImage.Format_RGB32) if vs_frame_alpha is None: return frame_image alpha_data_pointer = ctypes.cast( vs_frame_alpha.get_read_ptr(0), ctypes.POINTER(ctypes.c_char * (vs_frame_alpha.format.bytes_per_sample * vs_frame_alpha.width * vs_frame_alpha.height))) alpha_image = Qt.QImage(alpha_data_pointer.contents, vs_frame.width, vs_frame.height, vs_frame_alpha.get_stride(0), Qt.QImage.Format_Alpha8) result_image = Qt.QImage(vs_frame.width, vs_frame.height, Qt.QImage.Format_ARGB32_Premultiplied) painter = Qt.QPainter(result_image) painter.setCompositionMode(Qt.QPainter.CompositionMode_Source) painter.drawImage(0, 0, frame_image) painter.setCompositionMode(Qt.QPainter.CompositionMode_DestinationIn) painter.drawImage(0, 0, alpha_image) if self.main.CHECKERBOARD_ENABLED: painter.setCompositionMode( Qt.QPainter.CompositionMode_DestinationOver) painter.drawImage(0, 0, self.checkerboard) painter.end() return result_image
def combox_index_change(self, new_index): new_begin_index = self.combox_begin.currentIndex() new_end_index = self.combox_end.currentIndex() if new_begin_index == self.combox_begin.prev_index and new_end_index == self.combox_end.prev_index: return False if new_begin_index > new_end_index: QtWidgets.QMessageBox.critical(self, '选择错误', '起始学期在结束学期之后,请重新选择!') if new_begin_index != self.combox_begin.prev_index: self.combox_begin.setCurrentIndex(self.combox_begin.prev_index) elif new_end_index != self.combox_end.prev_index: self.combox_end.setCurrentIndex(self.combox_end.prev_index) return False self.change = True # self.response.refresh_current_value(new_begin_index, new_end_index + 1) self.refresh_dict() #self.tw.clear() y = 0 self.tw.clear() self.grid.removeWidget(self.tw) #create a new one, use the old one remains some bug self.create_table(new_begin_index, new_end_index + 1) self.grid.addWidget(self.tw, 1, 0) self.total_label.setText(str(round(self.response.current_total_credit, 2))) self.total_label.repaint() self.require_label.setText(str(round(self.response.current_require_credit, 2))) self.require_label.repaint() self.li_ke_label.setText(str(round(self.response.current_li_ke_credit, 2))) self.li_ke_label.repaint() self.wen_ke_label.setText(str(round(self.response.current_wen_ke_credit, 2))) self.wen_ke_label.repaint() self.major_require_label.setText(str(round(self.response.current_major_elective_credit, 2))) self.major_require_label.repaint() self.avg_gpa_label_name.setText(self.get_avg_label_name()) self.avg_gpa_label_name.repaint() self.avg_gpa_label_credit.setText(str(round(self.response.current_ave_gpa, 4))) self.avg_gpa_label_credit.repaint() self.combox_begin.prev_index = new_begin_index self.combox_end.prev_index = new_end_index interval_str = self.szx_rrre.SEMESTERS_LIST[self.combox_begin.currentIndex()][3][:4] + self.szx_rrre.SEMESTERS_LIST[self.combox_begin.currentIndex()][3][-3] + '_' + self.szx_rrre.SEMESTERS_LIST[self.combox_end.currentIndex()][3][:4] + self.szx_rrre.SEMESTERS_LIST[self.combox_end.currentIndex()][3][-3] if os.path.isfile(self.logindlg.dir + '\\' + self.message_list[0] + '_' + interval_str + '_pie.png'): for photo_label, photo_dir in (self.photo_label_pie, self.logindlg.dir + '\\' + self.message_list[0] + '_' + interval_str + '_pie.png'), (self.photo_label_radar, self.logindlg.dir + '\\' + self.message_list[0] + '_' + interval_str + '_radar.png'), (self.photo_label_pie1, self.logindlg.dir + '\\' + self.message_list[0] + '_' + interval_str + '_pie1.png'), (self.photo_label_bar, self.logindlg.dir + '\\' + self.message_list[0] + '_' + interval_str + '_bar.png'): photo = Qt.QImage(photo_dir) photo_label.setPixmap(Qt.QPixmap.fromImage(photo).scaled(300, 300, Qt.Qt.KeepAspectRatio, Qt.Qt.SmoothTransformation)) photo_label.repaint()
def __init__(self, height=25): flip = Qt.QTransform() flip.rotate(180) for icon in ('no_limit', 'soft_limit', 'hard_limit', 'hard_and_soft_limits'): fname = pkg_resources.resource_filename(__name__, f'limit_icons/{icon}.svg') im = Qt.QImage(fname).scaledToHeight(height) setattr(self, 'low_' + icon + '_pm', Qt.QPixmap.fromImage(im)) setattr(self, 'high_' + icon + '_pm', Qt.QPixmap.fromImage(im.transformed(flip))) setattr( self, 'low_' + icon + '_tt', icon[0].capitalize() + icon[1:].replace('_', ' ') + ' reached.') setattr( self, 'high_' + icon + '_tt', icon[0].capitalize() + icon[1:].replace('_', ' ') + ' reached.')
def conv_cvimage_to_pixmap(cvimage_src): """OpenCV画像からQPixmapに変換 Args: cvimage_src (cv2::image): """ # 色情報の並びを変更(BGR to RGB) cvimage_dst = graphics.cv_image.colororder_bgr_to_rgb(cvimage_src) o_image = Qt.QImage(cvimage_dst, cvimage_dst.shape[1], cvimage_dst.shape[0], cvimage_dst.shape[1] * 3, Qt.QImage.Format_RGB888) result_o_pixmap = QtGui.QPixmap() result_o_pixmap.convertFromImage(o_image) return result_o_pixmap
def render_raw_videoframe(self, vs_frame: vs.VideoFrame) -> Qt.QPixmap: import ctypes frame_data = vs_frame.get_read_ptr(0) frame_stride = vs_frame.get_stride(0) # frame_itemsize = vs_frame.get_read_array(0).itemsize frame_itemsize = vs_frame.format.bytes_per_sample # powerful spell. do not touch frame_data = ctypes.cast( frame_data, ctypes.POINTER(ctypes.c_char * (frame_itemsize * vs_frame.width * vs_frame.height)))[0] # type: ignore frame_image = Qt.QImage(frame_data, vs_frame.width, vs_frame.height, frame_stride, Qt.QImage.Format_RGB32) frame_pixmap = Qt.QPixmap.fromImage(frame_image) return frame_pixmap
def _generate_checkerboard(self) -> Qt.QImage: tile_size = self.main.CHECKERBOARD_TILE_SIZE tile_color_1 = self.main.CHECKERBOARD_TILE_COLOR_1 tile_color_2 = self.main.CHECKERBOARD_TILE_COLOR_2 macrotile_pixmap = Qt.QPixmap(tile_size * 2, tile_size * 2) painter = Qt.QPainter(macrotile_pixmap) painter.fillRect(macrotile_pixmap.rect(), tile_color_1) painter.fillRect(tile_size, 0, tile_size, tile_size, tile_color_2) painter.fillRect(0, tile_size, tile_size, tile_size, tile_color_2) painter.end() result_image = Qt.QImage(self.width, self.height, Qt.QImage.Format_ARGB32_Premultiplied) painter = Qt.QPainter(result_image) painter.drawTiledPixmap(result_image.rect(), macrotile_pixmap) painter.end() return result_image
def on_bmpLoadBtn_clicked(self): settings = Qt.QSettings() default_dir = settings.value('imgdir', '') or '' fn, ok = Qt.QFileDialog.getOpenFileName( self, 'Select bitmap file', default_dir, 'Image files (*.bmp *.png *.jpg *.gif *.xbm ' '*.xpm *.pbm *.pgm *.ppm);;All (*)') if not ok: return settings.setValue('imgdir', path.dirname(fn)) img = Qt.QImage(fn) if img.isNull(): Qt.QMessageBox.warning(self, 'Error', 'Image could not be read.') return img.convertToFormat(Qt.QImage.Format_Mono, Qt.Qt.MonoOnly) img.invertPixels() # make sure we have at least the required height, and width divisible # by 8 to avoid garbage in the scanlines img = img.copy(0, 0, (img.width() + 7) & ~7, HEIGHT) self.bitmap = Bitmap(img, min(img.width(), 4096)) self.changed.emit()
def _gray_log(data): """Returns the 2D data converted to an image. It uses an autoscale gray colormap and log normalization. :param numpy.ndarray data: Data array :return: The corresponding RGB image as a pixmap :rtype: QPixmap """ # Get strictly positive range valid_data = data[numpy.logical_and(numpy.isfinite(data), data > 0.)] if valid_data.size: min_ = numpy.min(valid_data) max_ = numpy.max(valid_data) else: # No finite strictly positive data min_ = 1. max_ = 10. # Log scale normalization normalized_data = 255 * ((numpy.log10(data) - numpy.log10(min_)) / (numpy.log10(max_) - numpy.log10(min_))) # Convert to grayscale RGB array image = numpy.empty(normalized_data.shape + (3, ), dtype=numpy.uint8) image[:] = normalized_data.astype(numpy.uint8)[..., numpy.newaxis] # Convert to QImage height, width, depth = image.shape qimage = Qt.QImage( image.data, width, height, image.strides[0], # bytesPerLine Qt.QImage.Format_RGB888) qimage = qimage.copy() # Making a copy of the image and its data # Convert to QPixmap and return return Qt.QPixmap.fromImage(qimage)
def loadImages(self): ''' Loads up picture files, which are stored in the 'data/' directory ''' path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', '{}') self.tileImg = Qt.QImage() self.tileImg.load(path.format('tile.png'), 'PNG') self.emptyTileImg = Qt.QImage() self.emptyTileImg.load(path.format('emptyTile.png'), 'PNG') self.flagImg = Qt.QImage() self.flagImg.load(path.format('flag.png'), 'PNG') self.wrongFlagImg = Qt.QImage() self.wrongFlagImg.load(path.format('wrongFlag.png'), 'PNG') self.mineImg = Qt.QImage() self.mineImg.load(path.format('mine.png'), 'PNG') self.explodedMineImg = Qt.QImage() self.explodedMineImg.load(path.format('explodedMine.png'), 'PNG') self.numberImages = [Qt.QImage() for i in range(0, 8)] for i in range(0, 8): self.numberImages[i].load(path.format(str(i + 1) + '.png'), 'PNG')
def genBitmap(self): if self.bitmap is not None: return self.bitmap font = Qt.QFont() font.fromString(self.font) # for some reason the bounding rect calculated here is wrong by quite a # bit, so let's use twice as a rough estimation width = 2 * Qt.QFontMetrics(font).boundingRect(self.text).width() if not width: return Bitmap() image = Qt.QImage(width, HEIGHT, Qt.QImage.Format_Mono) image.fill(0) with Qt.QPainter(image) as painter: # no antialiasing painter.setRenderHints(Qt.QPainter.RenderHints()) painter.setFont(font) painter.setPen(Qt.QPen(Qt.QColor('white'))) # here we get the real width of the drawn text real_width = painter.drawText(0, -self.offset, width, HEIGHT + self.offset, Qt.Qt.AlignTop | Qt.Qt.AlignLeft, self.text).width() return Bitmap(image, real_width)
def load_photo(self, start_index, end_index): if not self.elective_class.retrieve: self.photo_label_pie, self.photo_label_radar, self.photo_label_pie1, self.photo_label_bar, self.personal_photo_label = QtWidgets.QLabel(), QtWidgets.QLabel(), QtWidgets.QLabel(), QtWidgets.QLabel(), QtWidgets.QLabel() if self.logindlg.cache_flag and not self.elective_class.retrieve: i = 0 interval_str = self.szx_rrre.SEMESTERS_LIST[start_index][3][:4] + self.szx_rrre.SEMESTERS_LIST[start_index][3][-3] + '_' + self.szx_rrre.SEMESTERS_LIST[end_index][3][:4] + self.szx_rrre.SEMESTERS_LIST[end_index][3][-3] for photo_label, photo_dir in (self.personal_photo_label, self.logindlg.photodir), (self.photo_label_pie, self.logindlg.dir + '\\' + self.message_list[0] + '_' + interval_str + '_pie.png'), (self.photo_label_radar, self.logindlg.dir + '\\' + self.message_list[0] + '_' + interval_str + '_radar.png'), (self.photo_label_pie1, self.logindlg.dir + '\\' + self.message_list[0] + '_' + interval_str + '_pie1.png'), (self.photo_label_bar, self.logindlg.dir + '\\' + self.message_list[0] + '_' + interval_str + '_bar.png'): bias = -50 if i == 0 else 0 photo = Qt.QImage(photo_dir) photo_label.setPixmap(Qt.QPixmap.fromImage(photo).scaled(300 + bias, 300 + bias, Qt.Qt.KeepAspectRatio, Qt.Qt.SmoothTransformation)) i += 1 else: if not self.elective_class.retrieve: pixmap = QtGui.QPixmap() pixmap.loadFromData(QtCore.QByteArray(self.photo_byte)) self.personal_photo_label.setPixmap(pixmap.scaled(250, 250, Qt.Qt.KeepAspectRatio, Qt.Qt.SmoothTransformation)) for label, byte in (self.photo_label_pie, self.photo_pie_byte0), (self.photo_label_radar, self.photo_radar_byte), (self.photo_label_pie1, self.photo_pie_pyte1), (self.photo_label_bar, self.photo_bar_byte): pixmap = QtGui.QPixmap() pixmap.loadFromData(QtCore.QByteArray(byte)) label.setPixmap(pixmap.scaled(300, 300, Qt.Qt.KeepAspectRatio, Qt.Qt.SmoothTransformation)) if self.elective_class.retrieve: label.repaint()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # SOURCE: https://stackoverflow.com/a/8551810/5909792 from PyQt5 import Qt # A QApplication instance is necessary if fonts are used in the SVG app = Qt.QApplication([]) # Load your SVG renderer = Qt.QSvgRenderer("input.svg") for width, height in [(32, 32), (64, 64), (512, 512), (4096, 4096)]: # Prepare a QImage with desired characteritisc image = Qt.QImage(width, height, Qt.QImage.Format_ARGB32) # Partly transparent red-ish background image.fill(Qt.Qt.transparent) # Get QPainter that paints to the image painter = Qt.QPainter(image) renderer.render(painter) # Save, image format based on file extension image.save("output_{}x{}.png".format(width, height))
def load_image(self, img): height, width, channel = img.shape q_image = Qt.QImage(img.data, width, height, 3 * width, Qt.QImage.Format_RGB888).rgbSwapped() self.img = Qt.QPixmap.fromImage(q_image)
def Man_update(self): im = cv2.imread(self.path) im_grey = b.greyscale(im) im_bin = b.regular_bin(im_grey, self.Manual_slider.value()) pximage = Qt.QPixmap.fromImage(Qt.QImage("george.jpg")) self.show(pximage)
LED_IMAGES = {} LED_COLORS = [ "ledblueoff", "ledblue", "ledgreenoff", "ledgreen", "ledredoff", "ledred", "ledyellowoff", "ledyellow", "ledorangeoff", "ledorange" ] # Load led images: for size in ['s24', 's48']: LED_IMAGES[size] = {} if size == 's24': module_name = 'icepapcms.gui.Led.images24' else: module_name = 'icepapcms.gui.Led.images48' for color in LED_COLORS: image_filename = '{}.png'.format(color) LED_IMAGES[size][color] = Qt.QImage( resource_filename(module_name, image_filename)) class Led(QtWidgets.QWidget): BLUE, GREEN, RED, YELLOW, ORANGE = list(range(5)) ON, OFF = list(range(2)) S24, S48 = list(range(2)) colors = LED_COLORS def __init__(self, parent=None, ledsize=S24, ledcolor=GREEN): QtWidgets.QWidget.__init__(self, parent) self.ledsize = ledsize if ledsize == Led.S48: lsize = 48