def SaveFullImg(self): recap = self.capTimer.isActive() self.capTimer.stop() file = QFileDialog.getSaveFileName(self, "Save file", QDir.homePath(), "PNG images (*.png)") filename = file[0] if filename != "": if filename[-4:] != ".png" and filename[-4:] != ".PNG": filename = filename + ".png" stackPix = QPixmap(self.camView.width(), self.camView.height()) painter = QPainter(stackPix) painter.setRenderHints( QPainter.Antialiasing | QPainter.SmoothPixmapTransform, True) if self.camView.pixmap() is not None: painter.drawPixmap( 0, 0, self.camView.pixmap().scaled(self.camView.size(), Qt.IgnoreAspectRatio)) if self.scaleOverlay.pixmap() is not None: painter.drawPixmap(0, 0, self.scaleOverlay.pixmap()) if self.fscaleOverlay.pixmap() is not None: painter.drawPixmap(0, 0, self.fscaleOverlay.pixmap()) painter.end() stackPix.toImage().scaled(self.camView.size(), Qt.IgnoreAspectRatio).save(filename) if recap: self.capTimer.start()
class ImageDocument(DocumentInterface): def __init__(self, associated_view): super().__init__() self._selection = tuple() self._assoc_view = associated_view self._scene = QGraphicsScene(associated_view) self._pixmap = QPixmap() @property def contents(self): return self._scene @property def raw(self): raw_contents = RawContents(image=self._pixmap.toImage()) return raw_contents('image') @property def selection(self): return self._selection @selection.setter def selection(self, value): self._selection = tuple(value) @property def has_selection(self): # the same as an `if not ...` / etc. return bool(self._selection) @property def associated_view(self): return self._assoc_view def load_document(self, load_callback): load_callback(self._pixmap) if self._pixmap.isNull(): return False self._scene.addPixmap(self._pixmap) self._scene.setSceneRect(0, 0, self._pixmap.width(), self._pixmap.height()) return True def reset_document(self): self._scene.clear() def save_document(self, file_obj, format): raise NotImplementedError def get_selection_as_image(self): if not self.has_selection: raise ValueError("No Selection.") return self._pixmap.toImage().copy(*self._selection)
def pixmapToBytesIO(pixmap:QPixmap) -> BytesIO: #get image data bio=BytesIO() buff=QBuffer() buff.open(QBuffer.ReadWrite) pixmap.toImage().save(buff,"PNG") bio.write(buff.data()) bio.seek(0) return bio
class Canvas(QLabel): def __init__(self): super().__init__() self.paly() self.last_x, self.last_y = None, None self.pen_color = QColor('#000') def paly(self): self.canvas = QPixmap(320, 320) self.canvas.fill(QColor('white')) self.setPixmap(self.canvas) def GetContentAsQImage(self): # self.canvas = canvas.resize((28, 28), canvas.ANTIALIAS) # 将截图转换成 28 * 28 像素 image = self.canvas.toImage() return image def set_pen_color(self, c): self.pen_color = QColor(c) def mouseReleaseEvent(self, *args, **kwargs): """ 松开鼠标事件 """ self.last_x, self.last_y = None, None def mouseMoveEvent(self, e): """ 移动鼠标事件 """ if self.last_x is None: self.last_x = e.x() self.last_y = e.y() return painter = QPainter(self.pixmap()) pen = painter.pen() pen.setWidth(18) pen.setColor(self.pen_color) painter.setPen(pen) painter.drawLine(self.last_x, self.last_y, e.x(), e.y()) painter.end() self.update() # update the origin for next time self.last_x = e.x() self.last_y = e.y() image = self.canvas.toImage() image.save('paly.png', 'png', image.Format_RGB888)
def createDefAnimationView(self,movImags,spcImags): if not spcImags or not movImags : return spcImg,movImg = QImage(spcImags[0]),QImage(movImags[0]) spcFrameSize,movFrameSize = spcImg.width(),movImg.width() for i in range(0,3): firstFrame = QPixmap(movImg.copy(0,(i+6)*movFrameSize,movFrameSize,movFrameSize)) secondFrame = QPixmap(spcImg.copy(0,i*spcFrameSize,spcFrameSize,spcFrameSize)) eliminateBackgroundColor(firstFrame) eliminateBackgroundColor(secondFrame) bmps = [firstFrame,secondFrame] self.animationPanel.addAnimationView(AnimationView(bmps)) if i == 2: firstFrame = QPixmap(firstFrame.toImage().mirrored(True,False)) secondFrame = QPixmap(secondFrame.toImage().mirrored(True,False)) bmps = [firstFrame,secondFrame] self.animationPanel.addAnimationView(AnimationView(bmps))
def ask_image(self): inputImage = QFileDialog.getOpenFileName(self, 'Open file...', '.', 'Bitmap files (*.bmp)') if inputImage[0]: pixmap = QPixmap(inputImage[0]) if not pixmap.toImage().isGrayscale(): errorBox = QMessageBox() errorBox.setWindowTitle("Unsupported file Type") errorBox.setText("The input file must be a greyscale bitmap") errorBox.setIcon(QMessageBox.Critical) errorBox.exec_() return # Remove text placeholders and display image self.originalImage.setText('') self.compressedImage.setText('') self.originalImage.setPixmap(pixmap) self.compressedImage.setPixmap(None) limit = min(pixmap.width(), pixmap.height()) self.fSlider.setMaximum(limit) self.fSlider.setEnabled(True) self.fSlider.setTickInterval(limit / 10)
def loadImage(self, image_path): image = QPixmap(image_path) if image.hasAlphaChannel(): image = QPixmap.fromImage(image.toImage().convertToFormat(QImage.Format_RGB32)) self.label_image.setPixmap(image) self.label_image.resize(image.width(), image.height()) return True
def photo(self): if self.photo_flag and self.photo_num < 15: process = str(int(self.photo_num / 15 * 100)) + '%' self.label_2.setText('shooting process ...... ' + process) a = QPixmap.toImage(self.label.pixmap()) frame = qimage2ndarray.rgb_view(a) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) faces = detectAndDisplay(frame, self.face_cascade) if len(faces) == 1: self.photo_num += 1 ##self.logger.info('shoot the person(studentid number:'+self.comboBox_2.currentText()+'the '+str(self.photo_num)+' photo)') frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faceROI = frame[faces[0][1]:(faces[0][1] + faces[0][3]), faces[0][0]:(faces[0][0] + faces[0][2])] myface = cv2.resize(faceROI, (92, 111), 0, 0, cv2.INTER_AREA) cv2.imwrite('./temp/' + str(self.photo_num) + '.pgm', myface) elif len(faces) == 0: self.label_2.setText( 'No face detected,Please move to a brightly lit place!') elif len(faces) > 1: self.label_2.setText( 'Please keep only one face in front of the camera!') elif self.photo_flag and self.photo_num == 15: self.photo_timer.stop() self.label_2.setText('shooting process ...... 100%') self.showMessageBox_info('Info', 'Photo finished') self.quit()
def scalePixmap(self, pix_: QtGui.QPixmap, w_: int, h_: int, mode_: QtCore.Qt.AspectRatioMode) -> QtGui.QImage: """Return QImage scaled from a QPixmap.""" img_ = pix_.toImage() return img_.scaled(w_, h_, mode_)
def pixmap_into_gray_matrix(self, pixmap: QPixmap) -> np.ndarray: matrix = np.empty(shape=(config.IMG_WIDTH, config.IMG_HEIGHT)) image: QImage = pixmap.toImage() for i in range(pixmap.width()): for j in range(pixmap.height()): matrix[i][j] = 255 - qGray(image.pixel(i, j)) return matrix
def update_color(self): color_sq = QPixmap(self.width(), self.height()) color_sq.fill(self.color) image = color_sq.toImage() painter = QPainter(self) painter.drawImage(0, 0, image)
def characterWidth(part, fontFamily): virtualCanvas = QPixmap(10, 10) canvas = QPainter(virtualCanvas) width = virtualCanvas.width() height = virtualCanvas.height() canvas.setRenderHint(QPainter.Antialiasing, False) canvas.fillRect(-width, -height, width * 2, height * 2, Qt.white) canvas.setPen(QPen(Qt.gray)) writeFont = QFont(fontFamily) pixelSize = width writeFont.setPixelSize(pixelSize) canvas.setFont(writeFont) canvas.drawText(0, pixelSize, part) canvas.end() img = virtualCanvas.toImage() minx = width maxx = 0 y = 0 while y < height: x = 0 while x < width: if not (0xffffffff == img.pixel(x, y)): if minx > x: minx = x if maxx < x: maxx = x x += 1 y += 1 space = (1.0 - (float(maxx + minx)/float(width))) / 2.0 if space < 0.1: space = 0 space *= 1.2 return space
def refresh(self): self.serie.clear() self.valuesDisplay.clear() screen = app.primaryScreen() #grabWindow(wID, x, y, w, h) pix = QPixmap( screen.grabWindow(0, int((screenW * 3) / 4) - 10, int((screenH - nbPixels) / 2), 20, nbPixels)) self.pixelRow.setPixmap(pix) img = QImage(pix.toImage()) array = [0 for i in range(nbBlocsH)] for i in range(nbBlocsH): y = nbPixels - (i * (nbPixels / nbBlocsH) + (nbPixels / (2 * nbBlocsH))) colorvalue = 255 - QColor(img.pixel(10, y)).black() self.valuesDisplay.append(str(colorvalue)) self.valuesDisplay.append("\n") self.serie.append(y, colorvalue) #convert colors from 0->couleurMax to 0->nbBlocsD if colorvalue > couleurMax: colorvalue = nbBlocsD elif colorvalue < couleurMin: colorvalue = 0 else: colorvalue = int(colorvalue / (couleurMax / nbBlocsD)) array[i] = colorvalue self.convertToMatrix(array)
def pixmap_to_numpy(pixmap: QPixmap): """ Converts a Pixmap to a numpy array :param pixmap: the Pixmap :return: a numpy array """ return convertQImageToMat(pixmap.toImage().convertToFormat(QImage.Format_ARGB32_Premultiplied))
def build_one_image_cursor(toolname: str, color: Optional[QColor] = None) -> QCursor: hot_x = 8 hot_y = 8 target_x = 0 target_y = 0 tool_x = 15 tool_y = 15 if toolname == "text": hot_x = 8 + 15 hot_y = 8 target_x = 15 target_y = 0 tool_x = 0 tool_y = 15 tool = QPixmap(":/icons/" + TOOL_ICON[toolname]) target = QPixmap(":/icons/target") if color: target = WImage(target.toImage()) target.change_color(color) target = QPixmap.fromImage(target) res = QPixmap(30, 30) res.fill(QColor("transparent")) p = QPainter(res) p.drawPixmap(QPoint(target_x, target_y), target.scaledToWidth(15)) p.drawPixmap(QPoint(tool_x, tool_y), tool.scaledToWidth(15)) p.end() # res.save("/tmp/cursor_" + toolname + ".png") return QCursor(res, hot_x, hot_y)
def init_image_info(self, text_edit, img: ImageHandler): text_edit.append(f"Image name: {img.img_name}") text_edit.append(f"Image number: {img.image_ind}") text_edit.append(f"Batch number: {img.batch_no}") text_edit.append(f"Path: {img.path}") text_edit.append("\n" + img.batch_info + "\n") contours = img.contours headers = [ "Number", "Bottom left corner", "Top right corner", "Object confidence", "Class Score", "Class", "Label", "Color" ] cursor = text_edit.textCursor() cursor.insertTable(len(contours) + 1, len(headers)) for header in headers: cursor.insertText(header) cursor.movePosition(QTextCursor.NextCell) for contour in contours: row = [ contour.number, contour.corner_bl, contour.corner_tr, contour.obj_conf, contour.cls_score, contour.cls, contour.label ] for value in row: cursor.insertText(f"{value}") cursor.movePosition(QTextCursor.NextCell) pix_map = QPixmap(20, 20) b, g, r = contour.color pix_map.fill(QColor(r, g, b)) color_icon = pix_map.toImage() cursor.insertImage(color_icon) cursor.movePosition(QTextCursor.NextCell)
def get_icon_pixmap(ico_file_name: str, rotate=0, force_color_change: str = None) -> QPixmap: if app_defs.APP_IMAGE_DIR: path = app_defs.APP_IMAGE_DIR else: path = 'img' path = os.path.join(path, ico_file_name) if not os.path.isfile(path): logging.warning(f'File {path} does not exist or is not a file') pixmap = QPixmap(path) if rotate: transf = QTransform().rotate(rotate) pixmap = QPixmap(pixmap.transformed(transf)) if force_color_change: tmp = pixmap.toImage() color = QColor(force_color_change) for y in range(0, tmp.height()): for x in range(0, tmp.width()): color.setAlpha(tmp.pixelColor(x, y).alpha()) tmp.setPixelColor(x, y, color) pixmap = QPixmap.fromImage(tmp) return pixmap
def Qpixmap2array(cls, pixmap: QPixmap) -> np.ndarray: image=pixmap.toImage() channels_count= 4 if image.hasAlphaChannel() else 3 width, height = image.width(), image.height() buffer=image.bits().asarray(width*height*channels_count) arr=np.frombuffer(buffer,dtype=np.uint8).reshape((height,width,channels_count)) return arr
def slot_fill_combobox(self): if self.currentPalette is None: pass palette = self.currentPalette self.colorComboBox.clear() self.colorList = list() for i in range(palette.colorsCountTotal()): entry = palette.colorSetEntryByIndex(i) color = palette.colorForEntry(entry).colorForCanvas(self.canvas()) colorSquare = QPixmap(12, 12) if entry.spotColor() is True: img = colorSquare.toImage() circlePainter = QPainter() img.fill(self.colorComboBox.palette().color(QPalette.Base)) circlePainter.begin(img) brush = QBrush(Qt.SolidPattern) brush.setColor(color) circlePainter.setBrush(brush) circlePainter.pen().setWidth(0) circlePainter.drawEllipse(0, 0, 11, 11) circlePainter.end() colorSquare = QPixmap.fromImage(img) else: colorSquare.fill(color) name = entry.name() if len(entry.id()) > 0: name = entry.id() + " - " + entry.name() self.colorList.append(name) self.colorComboBox.addItem(QIcon(colorSquare), name) self.colorComboBox.setEditable(True) self.colorComboBox.setInsertPolicy(QComboBox.NoInsert) self.colorComboBox.completer().setCompletionMode( QCompleter.PopupCompletion) self.colorComboBox.completer().setCaseSensitivity(False) self.colorComboBox.completer().setFilterMode(Qt.MatchContains)
class Image: def __init__(self, file_name): self.pixmap = QPixmap(file_name) self.image = self.pixmap.toImage() self._find_scale_bar() def _find_scale_bar(self): """Find the scale bar. Find longest white line from both direction. Line can be the leftmost or rightmost, so there are breaks after first white line inclusions. """ scale_bar = 0 for y in range(self.image.height() * 3 // 4, self.image.height()): counter = 0 for x in range(self.image.width()): pixel = self.image.pixel(x, y) *rgb, _ = QColor(pixel).getRgbF() if all(i > 0.9 for i in rgb): counter += 1 if any(i < 0.9 for i in rgb) and counter != 0: break if counter > scale_bar: scale_bar = counter self.scale_bar = scale_bar
def setIcon(self, widget, ico, rotate=0, force_color_change: str = None): if isinstance(ico, str): icon = QIcon() if not ico == '': if app_defs.APP_IMAGE_DIR: path = app_defs.APP_IMAGE_DIR else: path = 'img' path = os.path.join(path, ico) if not os.path.isfile(path): logging.warning( f'File {path} does not exist or is not a file') pixmap = QPixmap(path) if rotate: transf = QTransform().rotate(rotate) pixmap = QPixmap(pixmap.transformed(transf)) if force_color_change: tmp = pixmap.toImage() color = QColor(force_color_change) for y in range(0, tmp.height()): for x in range(0, tmp.width()): color.setAlpha(tmp.pixelColor(x, y).alpha()) tmp.setPixelColor(x, y, color) pixmap = QPixmap.fromImage(tmp) icon.addPixmap(pixmap) else: icon = self.style().standardIcon(ico) widget.setIcon(icon)
def show_contour_on_signal(self, contour: ContourHandler): text_edit = self.textEdit2 text_edit.clear() left, bottom = contour.corner_bl right, top = contour.corner_tr text_edit.append(f"Contour number: {contour.number}") text_edit.append(f"Contour left margin: {left}") text_edit.append(f"Contour right margin: {right}") text_edit.append(f"Contour bottom margin: {bottom}") text_edit.append(f"Contour top margin: {top}") text_edit.append(f"Object confidence: {contour.obj_conf}") text_edit.append(f"Class score: {contour.cls_score}") text_edit.append(f"Label: <b>{contour.label}</b>") if contour.id_track == -1: text_edit.append(f"Tracking ID: No tracking") else: text_edit.append(f"Tracking ID: {contour.id_track}") text_edit.append("Color: ") pix_map = QPixmap(20, 20) b, g, r = contour.color pix_map.fill(QColor(r, g, b)) color_icon = pix_map.toImage() text_cursor = text_edit.textCursor() text_cursor.movePosition(QtGui.QTextCursor.NextCell, QtGui.QTextCursor.MoveAnchor) text_cursor.insertImage(color_icon) # This will hide the cursor blank_cursor = QtGui.QCursor(Qt.BlankCursor) text_edit.setCursor(blank_cursor) text_edit.moveCursor(QtGui.QTextCursor.End)
def _refresh_scene(self): self._scene.clear() self.spriteList.clear() for k in self._sprites.keys(): sprite = self._sprites[k] self.spriteList.addItem(k) if not sprite["is_text"]: if sprite["render"]["enable"]: sprite_path = os.path.join(self._currentProject, sprite["path"]) sprite_obj = json.loads(open(sprite_path).read()) image_path = os.path.join(os.path.split(sprite_path)[0], sprite_obj["image"]["path"]) pixmap = QPixmap(image_path) slice_col = sprite_obj["image"]["col"] slice_row = sprite_obj["image"]["row"] slice_width = pixmap.width() // slice_col slice_height = pixmap.height() // slice_row slice_index = sprite["render"]["default_frame"] pixmap = pixmap.copy( QRect( (slice_index % slice_col) * slice_width, (slice_index // slice_col) * slice_height, slice_width, slice_height)) pixmap = pixmap.scaledToWidth(int(pixmap.width() * sprite["render"]["render_scale"])) pixmap = QPixmap.fromImage(pixmap.toImage().mirrored(sprite["render"]["flipX"], False)) pixmap_item = self._scene.addPixmap(pixmap) pixmap_item.setPos(sprite["transform"]["position"]["x"], -sprite["transform"]["position"]["y"]) pixmap_item.moveBy(pixmap.width() // -2, pixmap.height() // -2) pixmap_item.moveBy(self.sceneView.width() // 2, self.sceneView.height() // 2) pixmap_item.setZValue(sprite["render"]["layer"]) if sprite["collision"]["enable"]: pen = QPen(Qt.green, 1, Qt.SolidLine) c_width = sprite["collision"]["x_size"] c_height = sprite["collision"]["y_size"] collision_item = self._scene.addRect(QRectF( sprite["transform"]["position"]["x"] - c_width // 2, -sprite["transform"]["position"]["y"] - c_height // 2, c_width, c_height ), pen) collision_item.moveBy(self.sceneView.width() // 2, self.sceneView.height() // 2) collision_item.setZValue(sprite["render"]["layer"]) else: if sprite["render"]["enable"]: text_item = self._scene.addText( sprite["content"] if len(sprite["content"]) > 0 else k, QFont("Arial", 20)) text_item.setScale(sprite["render"]["render_scale"]) text_item.setPos(sprite["transform"]["position"]["x"], -sprite["transform"]["position"]["y"]) text_item.moveBy(self.sceneView.width() // 2, self.sceneView.height() // 2) text_item.setZValue(sprite["render"]["layer"]) text_item.setDefaultTextColor(Qt.red) pen = QPen(Qt.darkGray, 1, Qt.DotLine) self._scene.addLine( QLineF( 0, self.sceneView.height() / 2, self.sceneView.width(), self.sceneView.height() / 2), pen).setZValue(9999) self._scene.addLine( QLineF( self.sceneView.width() / 2, 0, self.sceneView.width() / 2, self.sceneView.height()), pen).setZValue(9999)
def getFullScreen(self, temp): pix = QPixmap(self.window.mainWidget.size()) self.window.mainWidget.render(pix) image = pix.toImage() s = image.bits().asstring(image.width() * image.height() * 3) arr = np.fromstring(s, dtype='uint8').reshape((image.width(), image.height(), 3)) pix.save(temp) return arr
def getMarkedImage(self): marked_image = QPixmap.toImage(self.cellPixmapUnscaled) # draw dots on saving image green = qRgb(0, 255, 0) for point in self.pointsArray: marked_image.setPixel(point.x, point.y, green) return marked_image
def drawLogo(self, pixmap: QPixmap): try: self.ui.icon.setPixmap(pixmap) color = self.analyzeColor(pixmap.toImage()) color_str = "rgb(%d, %d, %d)" % (color.red(), color.green(), color.blue()) self.ui.avatar_area.setStyleSheet("background: %s" % color_str) except RuntimeError: pass
def disabledSideBarIcon(enabledicon: QPixmap) -> QPixmap: im = enabledicon.toImage().convertToFormat(QImage.Format_ARGB32) for y in range(im.height()): for x in range(im.width()): pixel = im.pixel(x, y) intensity = qGray(pixel) im.setPixel(x, y, qRgba(intensity, intensity, intensity, qAlpha(pixel))) return QPixmap.fromImage(im)
def pixmap_to_bytes(pixmap: QPixmap) -> bytes: image = pixmap.toImage() grayed = image.convertToFormat(QImage.Format.Format_Grayscale8) ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) ok = grayed.save(bf, 'PNG') assert ok return ba.data()
def generate_qrcode(self, currency_name, url_link): img = QRCode(url_link) file_name = os.path.join(bin_path(), currency_name + '.png') img.png(file_name) pixmap = QPixmap(file_name) pixmap = pixmap.scaled(256, 256) pixmap.save(file_name) self.qrcode_cash[currency_name] = pixmap.toImage() return currency_name
def transQPixmapToNdarray(self, pixmap: QPixmap): """ 将QPixmap转换为numpy数组 """ width, height = pixmap.width(), pixmap.height() channels_count = 4 image = pixmap.toImage() # type:QImage s = image.bits().asstring(height * width * channels_count) # 得到BGRA格式数组 array = numpy.fromstring(s, numpy.uint8).reshape( (height, width, channels_count)) return array
def tmpimage(tmpdir, qtbot): """Create an image to work with.""" path = str(tmpdir.join("any_image.png")) width = 10 height = 10 pm = QPixmap(width, height) qtbot.addWidget(pm) writer = QImageWriter(path) assert writer.write(pm.toImage()) return path
def image(self): pixmap = self._makePixmap(self.widthSpinBox.value(), self.heightSpinBox.value()) return QPixmap.toImage(pixmap)