def showImage(ui): image_height, image_width, image_channel = ui.img.shape qimg = QImage() timg = cv2.cvtColor(ui.img, cv2.COLOR_BGR2RGB) qimg = QImage(timg.data, image_width, image_height, image_width * image_channel, QImage.Format_RGB888) pix = QPixmap.fromImage(qimg) ui.board.resize(pix.size()) ui.board.setPixmap(pix) ui.scrollAreaWidgetContents.resize(pix.size())
def createOffscreenBitmap(self, state: CreateOffscreenBitmap): LOG.debug(state) bmp = QImage(state.cx, state.cy, QImage.Format_ARGB32_Premultiplied) bmp.fill(0) self.surfaces[state.id] = bmp for d in state.delete: if d in self.surfaces: del self.surfaces[d]
def get_viewport_img(self): self.hide_proxies() img = QImage(self.viewport().rect().width(), self.viewport().height(), QImage.Format_ARGB32) img.fill(Qt.transparent) painter = QPainter(img) painter.setRenderHint(QPainter.Antialiasing) self.render(painter, self.viewport().rect(), self.viewport().rect()) self.show_proxies() return img
def test(self): image = QImage(QSize(200, 200), QImage.Format_ARGB32) image.fill(QColor(Qt.red)) pixelFormat = image.pixelFormat() print(pixelFormat.greenSize()) self.assertEqual(pixelFormat.alphaSize(), 8) self.assertEqual(pixelFormat.redSize(), 8) self.assertEqual(pixelFormat.greenSize(), 8) self.assertEqual(pixelFormat.blueSize(), 8) self.assertEqual(pixelFormat.bitsPerPixel(), 32)
def load(self, fileName): image = QImage(fileName) if image.isNull(): QMessageBox.information(self, QApplication.applicationName(), "Cannot load " + fileName) self.setWindowTitle("Image viewer") self.setPixmap(QPixmap()) self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.setWindowTitle(fileName)
def draw(self, qp): qp.setWindow(0, 0, self.width(), self.height()) # 设置窗口 # 画框架背景 qp.setBrush(QColor('#cecece')) # 框架背景色 qp.setPen(Qt.NoPen) rect = QRect(0, 0, self.width(), self.height()) qp.drawRect(rect) sw, sh = self.width(), self.height() # 图像窗口宽高 pw, ph = 0, 0 # 缩放后的QPixmap大小 # 画图 yh = 0 if self.image is not None: ih, iw, _ = self.image.shape self.scale = sw / iw if sw / iw < sh / ih else sh / ih # 缩放比例 yh = round((self.height() - ih * self.scale) / 2) qimage = QImage(self.image.data, iw, ih, 3 * iw, QImage.Format_RGB888) # 转QImage qpixmap = QPixmap.fromImage( qimage.scaled(self.width(), self.height(), Qt.KeepAspectRatio)) # 转QPixmap pw, ph = qpixmap.width(), qpixmap.height() qp.drawPixmap(0, yh, qpixmap) font = QFont() font.setFamily('Microsoft YaHei') if self.fps > 0: font.setPointSize(14) qp.setFont(font) pen = QPen() pen.setColor(Qt.white) qp.setPen(pen) qp.drawText(self.width() - 150, yh + 40, 'FPS: ' + str(round(self.fps, 2))) # 画目标框 pen = QPen() pen.setWidth(2) # 边框宽度 for obj in self.objects: font.setPointSize(10) qp.setFont(font) rgb = [round(c) for c in obj['color']] pen.setColor(QColor(rgb[0], rgb[1], rgb[2])) # 边框颜色 brush1 = QBrush(Qt.NoBrush) # 内部不填充 qp.setBrush(brush1) qp.setPen(pen) # 坐标 宽高 tx, ty = round(pw * obj['x']), yh + round(ph * obj['y']) tw, th = round(pw * obj['w']), round(ph * obj['h']) obj_rect = QRect(tx, ty, tw, th) qp.drawRect(obj_rect) # 画矩形框 # 画 类别 和 置信度 qp.drawText(tx, ty - 5, str(obj['class']) + str(round(obj['confidence'], 2)))
def get_img(self): # pixmap = self.render_view.grab(self.render_view.sceneRect().toRect()) img = QImage(self.scene().sceneRect().size().toSize(), QImage.Format_ARGB32) img.fill(Qt.transparent) painter = QPainter(img) painter.setRenderHint(QPainter.Antialiasing) self.scene().render(painter) # app crashes here for some reason # img.save('H:/Projekte/QT/PySide2/pyScript/pyScript_011/mypic.png') return img
def __init__(self, title: str, cover: qtg.QImage): super().__init__() cover = cover.scaledToHeight(300, qtc.Qt.TransformationMode.SmoothTransformation) cover = cover.copy(self._rect) icon = qtg.QIcon(qtg.QPixmap.fromImage(cover)) self.setToolButtonStyle(qtc.Qt.ToolButtonIconOnly) self.setIcon(icon) self.setIconSize(qtc.QSize(300, 300)) self.setToolTip(title) self.setToolTipDuration(0)
def set_object(self, level_object: Union[LevelObject, EnemyObject]): if level_object is not None: self.object = get_minimal_icon_object(level_object) self.image = self.object.as_image() self.setToolTip(self.object.name) else: self.image = QImage() self.setToolTip("") self.update()
def QImageToCV(image: QImage) -> ndarray: if image.format() != QImage.Format_RGB888: image = image.convertToFormat(QImage.Format_RGB888) width = image.width() height = image.height() ptr = image.bits() arr = array(ptr).reshape(height, width, 3) return arr
def encode_image(image: QImage) -> str: image_bytes = QByteArray() buffer = QBuffer(image_bytes) buffer.open(QIODevice.WriteOnly) # writes pixmap into bytes in PNG format image.save(buffer, "PNG") # type: ignore encoded_bytes = image_bytes.toBase64() codec = QTextCodec.codecForName(b"UTF-8") encoded_string = codec.toUnicode(encoded_bytes) return encoded_string
def send_error(self, title, text, btn=None): self.d = buttons.DarkerButton(parent=self.parent(), text='Ok') if btn is None else btn self.setWindowTitle(title) self.setText(text) image = QImage() image.loadFromData(err) self.setIconPixmap(QPixmap(image)) self.addButton(self.d, QMessageBox.AcceptRole) winsound.PlaySound('SystemHand', winsound.SND_ASYNC) return self.exec_()
def dropEvent(self, event): data = event.mimeData() if event.mimeData().hasImage(): image = QImage(event.mimeData().imageData()) self.filepath = f"{os.getcwd()}/cache/{str(uuid.uuid4())}.jpg" image.save(self.filepath) return urls = data.urls() if urls and urls[0].scheme() == 'file': # for some reason, this doubles up the intro slash self.filepath = str(urls[0].path())[1:]
def openImage(self, fileName): loadedImage = QImage() if not loadedImage.load(fileName): return False newSize = loadedImage.size().expandedTo(self.size()) self.resizeImage(loadedImage, newSize) self.image = loadedImage self.modified = False self.update() return True
def __init__(self, parent=None): super(Bot, self).__init__(parent) self._map = None self.image = QImage(300, 300, QImage.Format_RGBA8888) self.timer = QTimer() self.position = QPoint() self.around = None self.angle = 0 self.last_front = False self.timer.timeout.connect(lambda: self.drawCircle(self.position))
def setupScribble(self, width, height): self.scribbleWidth = width self.scribbleHeight = height if self.scribbleImagePath == "": self.image = QImage(self.scribbleWidth, self.scribbleHeight, QImage.Format_ARGB32) # print(self.image.depth()) # prints 32 self.image.fill(qRgba(0, 0, 0, 0)) else: self.image = QImage(self.scribbleImagePath) self.image = self.image.convertToFormat(QImage.Format_ARGB32) self.update()
def paste(self): clipboard = QApplication.clipboard() data = clipboard.mimeData() if data.hasImage(): image = QImage(data.imageData()) try: self.protocol.file_to_send = f"{os.getcwd()}/cache/{str(uuid.uuid4())}.jpg" except AttributeError: return image.save(self.protocol.file_to_send) elif data.hasText(): self.message_input.insert(data.text())
def cv_to_qpixmap(cvimg): qformat = QImage.Format_Indexed8 if len(cvimg.shape) == 3: if cvimg.shape[2] == 4: qformat = QImage.Format_RGBA8888 else: qformat = QImage.Format_RGB888 qimg = QImage(cvimg.data, cvimg.shape[1], cvimg.shape[0], cvimg.strides[0], qformat) qimg = qimg.rgbSwapped() return QPixmap.fromImage(qimg)
def as_image(self, tile_length=8): if tile_length not in self.cached_tiles.keys(): width = height = tile_length image = QImage(self.pixels, self.WIDTH, self.HEIGHT, QImage.Format_RGB888) image = image.scaled(width, height) self.cached_tiles[tile_length] = image return self.cached_tiles[tile_length]
def testImage(): width, height = 100, 100 im = QImage(width, height, QImage.Format_ARGB32) for x in range(im.width()): for y in range(im.height()): if x % 2 == 0: im.setPixel(x, y, QColor('white').rgb()) else: im.setPixel(x, y, QColor('black').rgb()) # im.setPixel(x, y, QColor(255, x*2.56, y*2.56, 255).rgb()) im.save('test.png')
def resize(self, width: int, height: int): """ Resize the image buffer. This is called when the clientData is parsed, which contains the screen size used for the connection. :param width: new width of the replay client's screen :param height: new height of the replay client's screen. """ self._buffer = QImage(width, height, QImage.Format_ARGB32_Premultiplied) self.sessionWidth = width self.sessionHeight = height self._updateWidgetSize()
class QMiniMapTargetSceneViewer(QGraphicsItem): """ Widget to render minimized version of the target view's scene on the minimap. For performance, the scene is cached in a QImage and only updated when update_scene_drawing is called. """ def __init__(self, target_view: QGraphicsView, *args, **kwargs): super().__init__(*args, **kwargs) self._view: QGraphicsView = target_view self._minimap_scene_rect: QRectF = QRectF() self._scene_img: QImage = QImage() def set_scene_rect(self, rect: QRectF): """ Define the dimensions of the total minimap scene. """ self.prepareGeometryChange() self._minimap_scene_rect = rect self.update_scene_drawing() self.update() def update_scene_drawing(self): """ Render the target scene in an image to be used for minimap painting. """ scene = self._view.scene() if scene is None: return dpr = self._view.devicePixelRatioF() self._scene_img = QImage(dpr * self._minimap_scene_rect.width(), dpr * self._minimap_scene_rect.height(), QImage.Format_ARGB32) self._scene_img.setDevicePixelRatio(dpr) self._scene_img.fill(Conf.palette_base) self._view.set_extra_render_pass(True) painter = QPainter(self._scene_img) painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform | QPainter.HighQualityAntialiasing) scene.render(painter, target=self._minimap_scene_rect) self._view.set_extra_render_pass(False) self.update() def paint(self, painter, option, widget): # pylint: disable=unused-argument """ Paint the minimized scene image. """ painter.drawImage(0, 0, self._scene_img) def boundingRect(self): return self._minimap_scene_rect
def __init__(self, name, baseSize, contourPath, presetFilename=None, image=None): """ @param name: @type name: str @param baseSize: @type baseSize: int @param contourPath: base shape of the brush family @type contourPath: QPainterPath @param presetFilename: preset file @type presetFilename: str """ self.name = name self.baseSize = baseSize # init the brush pixmap self.basePixmap = QPixmap(self.baseSize, self.baseSize) # to get an alpha channel, we must fill the pixmap a first time with an opacity < 255 self.basePixmap.fill(QColor(0, 0, 0, 0)) if self.name == 'eraser': self.basePixmap.fill(QColor(0, 0, 0, 255)) self.contourPath = contourPath # init brush cursor self.baseCursor = QPixmap(self.baseSize, self.baseSize) self.baseCursor.fill(QColor(0, 0, 0, 0)) qp = QPainter(self.baseCursor) pen = qp.pen() pen.setWidth(self.baseSize / 20) qp.setPen(pen) # needed!! qp.drawPath(contourPath) qp.end() self.__pxmp = None self.bOpacity = 1.0 self.bFlow = 1.0 self.bHardness = 1.0 self.preset = None if presetFilename is not None: img = QImage(presetFilename) elif image is not None: img = image else: return img = img.convertToFormat(QImage.Format_ARGB32) buf = QImageBuffer(img) b = np.sum(buf[..., :3], axis=-1, dtype=np.float) b /= 3 buf[..., 3] = b self.preset = QPixmap.fromImage(img)
def requestImage(self, url, size, requestedSize): url = QUrl(url) image = QImage(url.toLocalFile()) width, height = image.width(), image.height() if size: size.setWidth(width) size.setHeight(height) if requestedSize.width() > 0: width = requestedSize.width() if requestedSize.height() > 0: height = requestedSize.height() return image.scaled(min(width, THUMBNAIL_SIZE), min(height, THUMBNAIL_SIZE), Qt.KeepAspectRatio)
def __init__(self): super(AppWindows, self).__init__() self.setWindowTitle("Darts Scorer powered by Jcigi") self.resize(1000, 1000) self.widget = QWidget() self.main_layout = QVBoxLayout() self.widget.setLayout(self.main_layout) self.setCentralWidget(self.widget) self.background_image = QImage("images/gdc_logo_uj.png") self.image_rect = QRect() # A menus.py definiálja a menüpontokat create_menus(self)
def get_pixmap(self, option: QStyleOptionViewItem, index: QModelIndex) -> QImage: view = option.styleObject model = view.model() w = view.columnWidth(0) if w == 0: return QImage() else: file = model.data(index) file = os.path.join(model.folder, file) if os.path.isdir(file): return QImage() return self.do_get_image(file, w)
def show_image(self, cv_image): self.resize(200, 200) rgb_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB) h, w, ch = rgb_image.shape bytes_per_line = ch * w qt_image = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888) img_w = qt_image.width() img_h = qt_image.height() proportion = img_w / img_h self.resize(self.width() * proportion, self.height()) qt_image = qt_image.scaled(self.width(), self.height()) self.setPixmap(QPixmap(qt_image)) self.parent_node_instance.update_shape()
def __init__(self, path): super(Picture, self).__init__() self.path = path self.name = self.path.split("/")[-1] self.extension = os.path.splitext(self.path)[1] self.scale = 1.0 self.image = QImage(self.path) self.thumbnail = self.image.scaled(QSize(110, 110), aspectMode=Qt.KeepAspectRatio, mode=Qt.SmoothTransformation) self.resolution = "Resolution: " + str(self.image.width()) + "x" + str( self.image.height()) + "px"
def _draw_mario(self, painter: QPainter, level: Level): mario_actions = QImage(str(data_dir / "mario.png")) mario_actions.convertTo(QImage.Format_RGBA8888) mario_position = QPoint(*level.header.mario_position()) * self.block_length x_offset = 32 * level.start_action mario_cutout = mario_actions.copy(QRect(x_offset, 0, 32, 32)).scaled( 2 * self.block_length, 2 * self.block_length ) painter.drawImage(mario_position, mario_cutout)
def _show_legend(self): pen = QPen(Qt.transparent) gradient = self._make_legend_gradient(self.LEGEND_X, self.LEGEND_Y, self.LEGEND_X, self.LEGEND_Y + self.legend_height) brush = QBrush(gradient) self.legend = self.traceScene.addRect(self.LEGEND_X, self.LEGEND_Y, self.LEGEND_WIDTH, self.legend_height, pen, brush) reference_gradient = self._make_legend_gradient(0, 0, self.LEGEND_WIDTH, 1000) base_img = QImage(self.LEGEND_WIDTH, 1000, QImage.Format.Format_ARGB32) p = QPainter(base_img) p.fillRect(base_img.rect(),reference_gradient) self.legend_img = base_img #reference shade
class SetPixelFloat(UsesQApplication): '''Test case for calling setPixel with float as argument''' def setUp(self): #Acquire resources super(SetPixelFloat, self).setUp() self.color = qRgb(255, 0, 0) self.image = QImage(200, 200, QImage.Format_RGB32) def tearDown(self): #Release resources del self.color del self.image super(SetPixelFloat, self).tearDown() def testFloat(self): #QImage.setPixel(float, float, color) - Implicit conversion self.image.setPixel(3.14, 4.2, self.color) self.assertEqual(self.image.pixel(3.14, 4.2), self.color)
def setUp(self): #Acquire resources super(SetPixelFloat, self).setUp() self.color = qRgb(255, 0, 0) self.image = QImage(200, 200, QImage.Format_RGB32)
def run(self): while True: self.mutex.lock() resultSize = self.resultSize scaleFactor = self.scaleFactor centerX = self.centerX centerY = self.centerY self.mutex.unlock() halfWidth = resultSize.width() // 2 halfHeight = resultSize.height() // 2 image = QImage(resultSize, QImage.Format_RGB32) NumPasses = 8 curpass = 0 while curpass < NumPasses: MaxIterations = (1 << (2 * curpass + 6)) + 32 Limit = 4 allBlack = True for y in range(-halfHeight, halfHeight): if self.restart: break if self.abort: return ay = 1j * (centerY + (y * scaleFactor)) for x in range(-halfWidth, halfWidth): c0 = centerX + (x * scaleFactor) + ay c = c0 numIterations = 0 while numIterations < MaxIterations: numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break numIterations += 1 c = c*c + c0 if abs(c) >= Limit: break if numIterations < MaxIterations: image.setPixel(x + halfWidth, y + halfHeight, self.colormap[numIterations % RenderThread.ColormapSize]) allBlack = False else: image.setPixel(x + halfWidth, y + halfHeight, qRgb(0, 0, 0)) if allBlack and curpass == 0: curpass = 4 else: if not self.restart: self.renderedImage.emit(image, scaleFactor) curpass += 1 self.mutex.lock() if not self.restart: self.condition.wait(self.mutex) self.restart = False self.mutex.unlock()
class Generator(object): def __init__(self): self.tileWidth = 16 self.tileHeight = 16 self.forcePot = False self.isTransparent = True self.bgColor = None self.reorder = False self.padding = 0 self._cols = 0 self._rows = 0 self._gridHeight = 0 self._gridWidth = 0 self._targetHeight = 0 self._targetWidth = 0 self._target = None def create(self, source): self._findSizes(source) self._createTargetImage() self._drawTiles(source) self._drawEdges() return self._target def _drawEdges(self): cols = int(self._targetWidth / self._gridWidth) rows = int(self._targetHeight / self._gridHeight) for offset in range(1, self.padding + 1): for j in range(rows): # horizontally (top) y = j * self._gridHeight + self.padding for x in range(self._targetWidth): self._target.setPixel(x, y - offset, self._target.pixel(x, y)) # horizontally (bottom) y = j * self._gridHeight + self.tileHeight + self.padding - 1 for x in range(self._targetWidth): self._target.setPixel(x, y + offset, self._target.pixel(x, y)) for offset in range(1, self.padding + 1): for j in range(cols): # vertically (left) x = j * self._gridWidth + self.padding for y in range(self._targetHeight): self._target.setPixel(x - offset, y, self._target.pixel(x, y)) # vertically (right) x = j * self._gridWidth + self.tileWidth + self.padding - 1 for y in range(self._targetHeight): self._target.setPixel(x + offset, y, self._target.pixel(x, y)) def _drawTiles(self, source): x = self.padding y = self.padding sx = 0 sy = 0 doReorder = self.forcePot & self.reorder painter = QPainter(self._target) for j in range(self._rows): for i in range(self._cols): painter.drawPixmap(x, y, source, sx, sy, self.tileWidth, self.tileHeight) x += self._gridWidth if doReorder and x >= self._targetWidth - self._gridWidth: x = self.padding y += self._gridHeight sx += self.tileWidth if not doReorder: x = self.padding y += self._gridHeight sx = 0 sy += self.tileHeight def _findSizes(self, source): self._cols = int(source.width() / self.tileWidth) self._rows = int(source.height() / self.tileHeight) self._gridWidth = self.tileWidth + self.padding * 2 self._gridHeight = self.tileHeight + self.padding * 2 self._targetWidth = self._cols * self._gridWidth self._targetHeight = self._rows * self._gridHeight if not self.forcePot: return self._targetHeight, self._targetWidth size = 1 widthOk = False heightOk = False for i in range(1, 31): if not widthOk and self._targetWidth < size: self._targetWidth = size widthOk = True if not heightOk and self._targetHeight < size: self._targetHeight = size heightOk = True if widthOk and heightOk: break size *= 2 return self._targetHeight, self._targetWidth def _createTargetImage(self): self._target = QImage(self._targetWidth, self._targetHeight, QImage.Format_ARGB32) if self.isTransparent: self._target.fill(Qt.transparent) else: self._target.fill(self.bgColor)
def _createTargetImage(self): self._target = QImage(self._targetWidth, self._targetHeight, QImage.Format_ARGB32) if self.isTransparent: self._target.fill(Qt.transparent) else: self._target.fill(self.bgColor)