Python PyQt5.QtGui 模块,QImage() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtGui.QImage()

项目:pynephoscope    作者:neXyon    | 项目源码 | 文件源码
def selectImage(self, index):
        if index >= len(self.files) or index < 0:
            self.ui.imageView.setText("No images found.")
            return

        self.index = index
        self.image = cv2.imread(self.files[index], 1)

        image = self.modes[self.current_mode].getImage()

        if len(image.shape) < 3 or image.shape[2] == 1:
            image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
        else:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        height, width, byteValue = self.image.shape
        byteValue = byteValue * width

        qimage = QtGui.QImage(image, width, height, byteValue, QtGui.QImage.Format_RGB888)

        self.ui.imageView.setPixmap(QtGui.QPixmap.fromImage(qimage))
项目:imagepyqt    作者:Image-Py    | 项目源码 | 文件源码
def QImageToMat(qimg):
    """RGB888"""
    #qimg = QImage()
    #qimg.load("/home/auss/Pictures/test.png")
    qimg = qimg.convertToFormat(QImage.Format_RGB888)
    qimg = qimg.rgbSwapped()
    #assert(qimg.byteCount() == qimg.width() * qimg.height() * 3)

    ptr = qimg.constBits()
    ptr.setsize(qimg.byteCount())

    mat = np.array(ptr).reshape( qimg.height(), qimg.width(), 3)  #  Copies the data
    return mat
项目:uitester    作者:IfengAutomation    | 项目源码 | 文件源码
def __init__(self, refresh_signal, conflict_tags_message_dict, case_data_manager, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.refresh_signal = refresh_signal
        self.case_data_manager = case_data_manager
        ui_dir_path = os.path.dirname(__file__)
        ui_file_path = os.path.join(ui_dir_path, "conflict_tag.ui")
        uic.loadUi(ui_file_path, self)
        self.setWindowTitle("conflict tag")
        self.conflict_tags_message_dict = conflict_tags_message_dict
        self.set_conflict_tags_table_widget()

        config = Config()
        image = QImage(os.path.join(config.images, 'notice.png'))
        result = image.scaled(40, 40)
        self.notice_image_label.setPixmap(QPixmap.fromImage(result))
        self.notice_image_label.setAlignment(Qt.AlignCenter)
        self.notice_text_label.setText(
            '?????????\n'
            '1???????????????????????????????\n'
            '2???????????????')  # todo ??????
        self.conflict_tags_submit_button.clicked.connect(self.conflict_tags_submit)
        self.button_style(self.conflict_tags_submit_button)
        self.cancel_submit_button.clicked.connect(self.cancel_submit)
        self.button_style(self.cancel_submit_button)
项目:ovirt-desktop-client    作者:nkovacne    | 项目源码 | 文件源码
def make_button(self, filename, tooltip, alignment=Qt.AlignCenter):
        """
            Description: Creates a QLabel which will contain an image and will
                         simulate a button. No associated text will be shown.
            Arguments: 1. filename: The filename of the icon/image to show 
                       2. tooltip: Some text to show as a tooltip to the image
                       3. alignment: Alignment of the button (center by default)
            Returns: The created QLabel button
        """

        global STANDARDCELLCSS, IMGDIR

        filepath = '%s%s%s' % (IMGDIR, filename, '.png')
        icon = QImage(filepath)
        image = QLabel()
        image.setToolTip('<span style="color:#B9B900">%s</span>' % (tooltip))
        image.setStyleSheet(STANDARDCELLCSS)
        image.setPixmap(QPixmap.fromImage(icon))
        image.setAlignment(alignment)

        return image
项目:SantosGUI    作者:santosfamilyfoundation    | 项目源码 | 文件源码
def open_image_fd(self, dialog_text="Open Image", default_folder=""):
        """Opens a file dialog, allowing user to select an image file.

        Creates a QImage object from the filename selected by the user in the
        popup file dialog menu.

        Args:
            dialog_text [Optional(str.)]: Text to prompt user with in open file
                dialog. Defaults to "Open Image".
            default_folder [Optional(str.)]: Path of the default directory to open
                the file dialog box to. Defaults to "".

        Returns:
            QImage: Image object created from selected image file.
            None: Returns None if no file was selected in the dialog box.
        """
        fname = QtWidgets.QFileDialog.getOpenFileName(self, dialog_text, default_folder)  # TODO: Filter to show only image files
        if fname:
            image = QtGui.QImage(fname[0])
        else:
            image = None
        return image
项目:SantosGUI    作者:santosfamilyfoundation    | 项目源码 | 文件源码
def load_image(self, image):
        """
        Call this to load a new image from the provide QImage into
        this HomographyView's scene. The image's top left corner will
        be placed at (0,0) in the scene.
        """
        self.scene_image = image
        new_scene = HomographyScene(self)
        pmap = QtGui.QPixmap().fromImage(image)
        pmapitem = new_scene.addPixmap(pmap)
        new_scene.register_pixmap(pmapitem)
        new_scene.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(0, 0, 0)))
        self.setScene(new_scene)
        self.fitInView(0, 0, pmap.width(), pmap.height(), Qt.KeepAspectRatio)
        self.show()
        self.image_loaded = True
项目:labelImage    作者:tsuzukit    | 项目源码 | 文件源码
def savePascalVocFormat(self, filename, shapes, imagePath, imageData,
                            lineColor=None, fillColor=None, databaseSrc=None):
        imgFolderPath = os.path.dirname(imagePath)
        imgFolderName = os.path.split(imgFolderPath)[-1]
        imgFileName = os.path.basename(imagePath)
        #imgFileNameWithoutExt = os.path.splitext(imgFileName)[0]
        # Read from file path because self.imageData might be empty if saving to
        # Pascal format
        image = QImage()
        image.load(imagePath)
        imageShape = [image.height(), image.width(),
                      1 if image.isGrayscale() else 3]
        writer = PascalVocWriter(imgFolderName, imgFileName,
                                 imageShape, localImgPath=imagePath)
        writer.verified = self.verified

        for shape in shapes:
            points = shape['points']
            label = shape['label']
            # Add Chris
            difficult = int(shape['difficult'])
            bndbox = LabelFile.convertPoints2BndBox(points)
            writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult)

        writer.save(targetFile=filename)
        return
项目:transpyler    作者:Transpyler    | 项目源码 | 文件源码
def saveImage(self, fname):  # noqa: N802
        """
        Saves current viewport as a png file of the given fname.
        """

        rect = self.viewport()
        rgb = QtGui.QImage.Format_RGB32
        image = QtGui.QImage(rect.width(), rect.height(), rgb)
        image.fill(QtGui.QColor(255, 255, 255))
        painter = QtGui.QPainter(image)
        self.render(painter)
        if not image.save(fname):
            raise ValueError('could not save image %s' % fname)
        del painter
项目:ida_strcluster    作者:Comsecuris    | 项目源码 | 文件源码
def getIcon(self):
        icon = (
            '0000010001001010000001002000680400001600000028000000100000002000000001'
            '0020000000000000040000130b0000130b00000000000000000000000000000773e600'
            '0577df000877dd060477df490277e0a70277e0e30277e0fb0277e0fb0277e0e30277e0'
            'a70377e0490577e0060377e1000175f00000000000000000000377e0000577df180377'
            'e0920277e0ed0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0277e0ed02'
            '77e0920377e1180277e100000000000577df000577df180277e0b10177e0ff0177e0ff'
            '0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0277e0'
            'b10377e1180377e1000174de070176df920076e0ff0077e0ff0177e0ff0177e0ff0177'
            'e0ff0076e0ff0076e0ff0177e0ff0177e0ff0177e0ff0077e0ff0076e0ff0176e09202'
            '76e107127fe0481983e2ee1f87e3ff0d7de1ff0076e0ff0077e0ff067ae1ff1d86e3ff'
            '1a84e3ff077ae1ff0177e0ff0076e0ff0e7ee1ff1e87e3ff1581e2ee0a7be1483592e4'
            'a759a6e9ff4fa0e8ff66adeaff1e86e3ff0b7ce1ff60a9e9ff57a5e9ff56a4e9ff459b'
            'e7ff0277e0ff288ce4ff68aeeaff51a1e8ff56a4e8ff2389e3a70578e0e40177e0ff00'
            '72dfff499de7ff4fa1e8ff3c96e6ff53a3e8ff0074dfff0075e0ff0579e0ff0478e0ff'
            '6cb0ebff268be4ff0075e0ff0378e0ff0478e0e40176e0fb1481e2ff439ae7ff7bb8ec'
            'ff2a8ce4ff5da8eaff63abeaff3793e5ff3894e6ff3392e5ff1481e2ff73b4edff0b7c'
            'e1ff0177e0ff0177e0ff0277e0fb2c8de4fb76b5ecff50a1e8ff1e86e3ff0075e0ff59'
            'a6e9ff63abeaff3692e5ff3793e5ff76b5ecff2389e3ff73b4ecff0d7de1ff0077e0ff'
            '0077e0ff0177e0fb5ea8e9e455a4e8ff0075e0ff0b7ce1ff0679e0ff3090e5ff59a6e9'
            'ff0377e0ff1380e2ff62abe9ff0c7ce1ff65aceaff3693e5ff0478e0ff0d7de1ff077a'
            'e1e42489e2a75ba7e9ff59a5e9ff5aa6e9ff1983e2ff0578e0ff489de7ff5da8eaff5f'
            'a9eaff2c8ee4ff0075e0ff1a84e2ff60aaeaff5ba6e9ff57a4e9ff1f86e3a70075df48'
            '0478e0ee0e7ee1ff087be1ff0177e0ff0177e0ff0177e0ff0c7de1ff087be1ff0076e0'
            'ff0177e0ff0076e0ff0479e0ff0e7ee1ff087ae1ee0377e0480777de070377e0920177'
            'e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff01'
            '77e0ff0177e0ff0177e0ff0277e0920477e1070577df000577df180277e0b10177e0ff'
            '0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0'
            'ff0277e0b10377e1180377e100000000000377e0000577df180377e0920277e0ed0177'
            'e0ff0177e0ff0177e0ff0177e0ff0177e0ff0177e0ff0277e0ed0277e0920377e11802'
            '77e10000000000000000000773e6000577df000877dd060477df490277e0a70277e0e3'
            '0277e0fb0277e0fb0277e0e30277e0a70377e0490676e0060377e1000174f300000000'
            '00e0070000c00300008001000000000000000000000000000000000000000000000000'
            '00000000000000000000000000000000000080010000c0030000e0070000')
        image = QtGui.QImage()
        image.loadFromData(QtCore.QByteArray.fromHex(icon))
        pixmap = QtGui.QPixmap()
        pixmap.convertFromImage(image)
        return QtGui.QIcon(pixmap)
项目:imagepyqt    作者:Image-Py    | 项目源码 | 文件源码
def mkQImage(argb, alpha=None, trans=False):
    """
    Use the cpoied data of ARGB argb to make QImage and return it.
    argb:  (w,h,3 or 4)  this (bgr/rgb or bgra/rgba).
    alpha: ARGB32 if alpha is True else RGB32 (always be 4).
    trans: if trans is true then x/y axes are transposed.

    In default
    Qt: ARGB (32bpp), (width,height)

    """
    if alpha is None or not isinstance(alpha,bool):
        alpha = (argb.shape[2] == 4)

    if argb.shape[2] == 3:
        tmp = np.empty(argb.shape[:2] + (4,), dtype = argb.dtype)
        tmp[...,:3] = argb
        tmp[...,3] = 255
        argb = tmp

    if alpha:
        imgFormat = QtGui.QImage.Format_ARGB32
    else:
        imgFormat = QtGui.QImage.Format_RGB32

    if trans:
        # (y,x,c) => (x,y,c)
        argb = argb.transpose((1, 0, 2))

    addr = argb.data #addr = memoryview(argb)
    qimg = QtGui.QImage(addr,argb.shape[1],argb.shape[0],imgFormat)

    return qimg
项目:imagepyqt    作者:Image-Py    | 项目源码 | 文件源码
def MatToQImage(mat,swapped=True):
    '''?numpy.ndarray???QtGui.QImage?????QPixmap?????QLabel???'''
    height, width = mat.shape[:2]
    dim = 1 if mat.ndim == 2 else mat.shape[2]
    bytesPerLine = dim * width
    # ?numpy.ndarray???QtGui.QImage????????
    qimage = QtGui.QImage(mat.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888)
    if swapped:
        qimage = qimage.rgbSwapped()
    return qimage
    #return QPixmap.fromImage(qimg)
项目:roLabelImg    作者:cgvict    | 项目源码 | 文件源码
def savePascalVocFormat(self, filename, shapes, imagePath, imageData,
                            lineColor=None, fillColor=None, databaseSrc=None):
        imgFolderPath = os.path.dirname(imagePath)
        imgFolderName = os.path.split(imgFolderPath)[-1]
        imgFileName = os.path.basename(imagePath)
        imgFileNameWithoutExt = os.path.splitext(imgFileName)[0]
        # Read from file path because self.imageData might be empty if saving to
        # Pascal format
        image = QImage()
        image.load(imagePath)
        imageShape = [image.height(), image.width(),
                      1 if image.isGrayscale() else 3]
        writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt,
                                 imageShape, localImgPath=imagePath)
        writer.verified = self.verified

        for shape in shapes:
            points = shape['points']
            label = shape['label']
            # Add Chris
            difficult = int(shape['difficult'])           
            direction = shape['direction']
            isRotated = shape['isRotated']
            # if shape is normal box, save as bounding box 
            # print('direction is %lf' % direction)
            if not isRotated:
                bndbox = LabelFile.convertPoints2BndBox(points)
                writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], 
                    bndbox[3], label, difficult)
            else: #if shape is rotated box, save as rotated bounding box
                robndbox = LabelFile.convertPoints2RotatedBndBox(shape)
                writer.addRotatedBndBox(robndbox[0],robndbox[1],
                    robndbox[2],robndbox[3],robndbox[4],label,difficult)

        writer.save(targetFile=filename)
        return
项目:SiebenApp    作者:ahitrin    | 项目源码 | 文件源码
def reload_image(self):
        if not self.goals.events and not self.force_refresh:
            return
        self.force_refresh = False
        save(self.goals, self.db)
        if self.use_dot:
            with open('work.dot', 'w') as f:
                f.write(dot_export(self.goals))
            run(['dot', '-Tpng', '-o', 'work.png', 'work.dot'])
            img = QImage('work.png')
            self.label.setPixmap(QPixmap.fromImage(img))
            self.label.resize(img.size().width(), img.size().height())
项目:Mac-Python-3.X    作者:L1nwatch    | 项目源码 | 文件源码
def __init__(self, parent=None):
        super(ImageModel, self).__init__(parent)

        self.modelImage = QImage()
项目:Mac-Python-3.X    作者:L1nwatch    | 项目源码 | 文件源码
def setImage(self, image):
        self.beginResetModel()
        self.modelImage = QImage(image)
        self.endResetModel()
项目:Mac-Python-3.X    作者:L1nwatch    | 项目源码 | 文件源码
def openImage(self, fileName):
        image = QImage()

        if image.load(fileName):
            self.model.setImage(image)

            if not fileName.startswith(':/'):
                self.currentPath = fileName
                self.setWindowTitle("%s - Pixelator" % self.currentPath)

            self.printAction.setEnabled(True)
            self.updateView()
项目:Mac-Python-3.X    作者:L1nwatch    | 项目源码 | 文件源码
def loadFromMemory(self):
        """ This slot function is called in the second Dialog process, when the
        user presses the "Load Image from Shared Memory" button.  First, it
        attaches the process to the shared memory segment created by the first
        Dialog process.  Then it locks the segment for exclusive access, copies
        the image data from the segment into a QBuffer, and streams the QBuffer
        into a QImage.  Then it unlocks the shared memory segment, detaches
        from it, and finally displays the QImage in the Dialog.
        """

        if not self.sharedMemory.attach():
            self.ui.label.setText(
                    "Unable to attach to shared memory segment.\nLoad an "
                    "image first.")
            return

        buf = QBuffer()
        ins = QDataStream(buf)
        image = QImage()

        self.sharedMemory.lock()
        buf.setData(self.sharedMemory.constData())
        buf.open(QBuffer.ReadOnly)
        ins >> image
        self.sharedMemory.unlock()
        self.sharedMemory.detach()

        self.ui.label.setPixmap(QPixmap.fromImage(image))
项目:Mac-Python-3.X    作者:L1nwatch    | 项目源码 | 文件源码
def changeIcon(self):
        icon = QIcon()

        for row in range(self.imagesTable.rowCount()):
            item0 = self.imagesTable.item(row, 0)
            item1 = self.imagesTable.item(row, 1)
            item2 = self.imagesTable.item(row, 2)

            if item0.checkState() == Qt.Checked:
                if item1.text() == "Normal":
                    mode = QIcon.Normal
                elif item1.text() == "Active":
                    mode = QIcon.Active
                elif item1.text() == "Disabled":
                    mode = QIcon.Disabled
                else:
                    mode = QIcon.Selected

                if item2.text() == "On":
                    state = QIcon.On
                else:
                    state = QIcon.Off

                fileName = item0.data(Qt.UserRole)
                image = QImage(fileName)
                if not image.isNull():
                    icon.addPixmap(QPixmap.fromImage(image), mode, state)

        self.previewArea.setIcon(icon)
项目:eclipse2017    作者:google    | 项目源码 | 文件源码
def qimage_to_numpy(image):
    # Convert a QImage to a numpy array
    image = image.convertToFormat(QtGui.QImage.Format_ARGB32)
    width = image.width()
    height = image.height()
    ptr = image.constBits()

    return np.frombuffer(ptr.asstring(image.byteCount()), dtype=np.uint8).reshape(height, width, 4)
项目:eclipse2017    作者:google    | 项目源码 | 文件源码
def paintGL(self, sun_x, sun_y, sun_z, moon_x, moon_y, moon_z):
        # Draw the sun
        self.fbo.bind()
        self.draw_sun(sun_x, sun_y, sun_z)
        glFlush()
        self.fbo.release()
        image = self.fbo.toImage()

        # Produce blurred image of sun
        npimage = qimage_to_numpy(image)
        h, w, b = npimage.shape
        blur = cv2.GaussianBlur(npimage, (75, 75), 0, 0)
        cv2.convertScaleAbs(blur, blur, 2, 1)
        # Combine the blurred with the sun
        combo = cv2.addWeighted(blur, 0.5, npimage, 0.5, -1)
        h, w, b = combo.shape
        qimage = QtGui.QImage(combo.data,w,h,QtGui.QImage.Format_ARGB32).rgbSwapped()
        self.fbo.bind()
        device = QtGui.QOpenGLPaintDevice(RES_X, RES_Y)
        painter = QtGui.QPainter()
        painter.begin(device)
        rect = QtCore.QRect(0, 0, RES_X, RES_Y)
        # Draw the blurred sun/sun combo image on the screen
        painter.drawImage(rect, qimage, rect)
        painter.end()
        self.fbo.release()

        # Draw the moon
        self.fbo.bind()
        self.draw_moon(moon_x, moon_y, moon_z)
        glFlush()
        self.fbo.release()
项目:examples    作者:pyqt    | 项目源码 | 文件源码
def __init__(self, parent=None):
        super(ImageModel, self).__init__(parent)

        self.modelImage = QImage()
项目:examples    作者:pyqt    | 项目源码 | 文件源码
def setImage(self, image):
        self.beginResetModel()
        self.modelImage = QImage(image)
        self.endResetModel()
项目:examples    作者:pyqt    | 项目源码 | 文件源码
def openImage(self, fileName):
        image = QImage()

        if image.load(fileName):
            self.model.setImage(image)

            if not fileName.startswith(':/'):
                self.currentPath = fileName
                self.setWindowTitle("%s - Pixelator" % self.currentPath)

            self.printAction.setEnabled(True)
            self.updateView()
项目:examples    作者:pyqt    | 项目源码 | 文件源码
def loadFromMemory(self):
        """ This slot function is called in the second Dialog process, when the
        user presses the "Load Image from Shared Memory" button.  First, it
        attaches the process to the shared memory segment created by the first
        Dialog process.  Then it locks the segment for exclusive access, copies
        the image data from the segment into a QBuffer, and streams the QBuffer
        into a QImage.  Then it unlocks the shared memory segment, detaches
        from it, and finally displays the QImage in the Dialog.
        """

        if not self.sharedMemory.attach():
            self.ui.label.setText(
                    "Unable to attach to shared memory segment.\nLoad an "
                    "image first.")
            return

        buf = QBuffer()
        ins = QDataStream(buf)
        image = QImage()

        self.sharedMemory.lock()
        buf.setData(self.sharedMemory.constData())
        buf.open(QBuffer.ReadOnly)
        ins >> image
        self.sharedMemory.unlock()
        self.sharedMemory.detach()

        self.ui.label.setPixmap(QPixmap.fromImage(image))
项目:examples    作者:pyqt    | 项目源码 | 文件源码
def changeIcon(self):
        icon = QIcon()

        for row in range(self.imagesTable.rowCount()):
            item0 = self.imagesTable.item(row, 0)
            item1 = self.imagesTable.item(row, 1)
            item2 = self.imagesTable.item(row, 2)

            if item0.checkState() == Qt.Checked:
                if item1.text() == "Normal":
                    mode = QIcon.Normal
                elif item1.text() == "Active":
                    mode = QIcon.Active
                elif item1.text() == "Disabled":
                    mode = QIcon.Disabled
                else:
                    mode = QIcon.Selected

                if item2.text() == "On":
                    state = QIcon.On
                else:
                    state = QIcon.Off

                fileName = item0.data(Qt.UserRole)
                image = QImage(fileName)
                if not image.isNull():
                    icon.addPixmap(QPixmap.fromImage(image), mode, state)

        self.previewArea.setIcon(icon)
项目:ETS2Autopilot    作者:BrunoTh    | 项目源码 | 文件源码
def set_image(cv_image, ui_element):
    qimg = QtGui.QImage(cv_image, cv_image.shape[1], cv_image.shape[0], cv_image.strides[0], QtGui.QImage.Format_RGB888)
    pixmap = QtGui.QPixmap(qimg)
    pixmap = pixmap.scaledToHeight(ui_element.height())
    ui_element.setPixmap(pixmap)
项目:ETS2Autopilot    作者:BrunoTh    | 项目源码 | 文件源码
def fill_screen_cap(self):
        # TODO: Screen 2 shows black image
        slider_left = self.ui.slider_left.value()
        slider_right = self.ui.slider_right.value()
        slider_top = self.ui.slider_top.value()
        slider_bottom = self.ui.slider_bottom.value()

        frame_raw = ImageGrab.grab(bbox=functions.get_screen_bbox())
        frame = np.uint8(frame_raw)
        frame = cv2.rectangle(frame, (slider_left, slider_top), (slider_right, slider_bottom), (255, 0, 0), 4)
        qimg = QtGui.QImage(frame, frame.shape[1], frame.shape[0], frame.strides[0], QtGui.QImage.Format_RGB888)
        pixmap = QtGui.QPixmap(qimg)
        pixmap = pixmap.scaledToHeight(self.ui.screen_cap.height())
        self.ui.screen_cap.setPixmap(pixmap)
项目:bubblesub    作者:rr-    | 项目源码 | 文件源码
def _draw_spectrogram(self, painter, _event):
        width = painter.viewport().width()
        height = (1 << DERIVATION_SIZE) + 1

        pixels = np.zeros([width, height], dtype='byte')
        horizontal_res = (
            self._api.opt.general['audio']['spectrogram_resolution'])

        # since the task queue is a LIFO queue, in order to render the columns
        # left-to-right, they need to be iterated backwards (hence reversed()).
        for x in reversed(range(width)):
            pts = self._pts_from_x(x)
            pts = (pts // horizontal_res) * horizontal_res
            column = self._spectrum_cache.get(pts, NOT_CACHED)
            if column is NOT_CACHED:
                self._spectrum_provider.schedule_task(pts)
                self._spectrum_cache[pts] = CACHING
                continue
            if column is CACHING:
                continue
            pixels[x] = column

        pixels = pixels.transpose().copy()
        image = QtGui.QImage(
            pixels.data,
            pixels.shape[1],
            pixels.shape[0],
            pixels.strides[0],
            QtGui.QImage.Format_Indexed8)
        image.setColorTable(self._color_table)
        painter.save()
        painter.scale(1, painter.viewport().height() / (height - 1))
        painter.drawPixmap(0, 0, QtGui.QPixmap.fromImage(image))
        painter.restore()
项目:Pesterchum-Discord    作者:henry232323    | 项目源码 | 文件源码
def load_emojis(self):
        async with aiohttp.ClientSession(loop=self.app.loop) as session:
            for emoji in self.app.client.get_all_emojis():
                if emoji.server == self.memo.server:
                    with timeout(10):
                        async with session.get(emoji.url) as response:
                            img = await response.read()
                            qmg = QImage()
                            qmg.loadFromData(img)
                            self.userOutput.document().addResource(QTextDocument.ImageResource, QUrl(emoji.url), qmg)
项目:OctoPrintPlugin    作者:fieldOfView    | 项目源码 | 文件源码
def _stopCamera(self):
        if self._image_reply:
            self._image_reply.abort()
            self._image_reply.downloadProgress.disconnect(self._onStreamDownloadProgress)
            self._image_reply = None
        image_request = None

        self._stream_buffer = b""
        self._stream_buffer_start_index = -1

        self._camera_image = QImage()
        self.newImage.emit()
项目:SantosGUI    作者:santosfamilyfoundation    | 项目源码 | 文件源码
def homography_open_image_camera(self):
        """Opens a file dialog, allowing user to select an camera image file.

        Creates a QImage object from the filename of an camera image
        selected by the user in a popup file dialog menu.
        """
        qi = self.open_image_fd(dialog_text="Select camera image...")
        if qi:
            self.ui.homography_cameraview.load_image(qi)
项目:SantosGUI    作者:santosfamilyfoundation    | 项目源码 | 文件源码
def homography_open_image_aerial(self):
        """Opens a file dialog, allowing user to select an aerial image file.

        Creates a QImage object from the filename of an aerial image
        selected by the user in a popup file dialog menu.
        """
        qi = self.open_image_fd(dialog_text="Select aerial image...")
        if qi:
            self.ui.homography_aerialview.load_image(qi)
项目:SantosGUI    作者:santosfamilyfoundation    | 项目源码 | 文件源码
def load_image(self, image):
        """
        Call this to load a new image from the provide QImage into
        this HomographyView's scene. The image's top left corner will
        be placed at (0,0) in the scene.
        """
        self.scene_image = image
        new_scene = QtWidgets.QGraphicsScene(self)
        pmap = QtGui.QPixmap().fromImage(image)
        pmapitem = new_scene.addPixmap(pmap)
        new_scene.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(0, 0, 0)))
        self.setScene(new_scene)
        self.fitInView(0, 0, pmap.width(), pmap.height(), Qt.KeepAspectRatio)
        self.show()
        self.image_loaded = True
项目:SantosGUI    作者:santosfamilyfoundation    | 项目源码 | 文件源码
def load_image_from_path(self, path):
        im = QtGui.QImage(path)
        self.load_image(im)
项目:blog    作者:benhoff    | 项目源码 | 文件源码
def __init__(self, haar_cascade_filepath, parent=None):
        super().__init__(parent)
        self.classifier = cv2.CascadeClassifier(haar_cascade_filepath)
        self.image = QtGui.QImage()
        self._red = (0, 0, 255)
        self._width = 2
        self._min_size = (30, 30)
项目:blog    作者:benhoff    | 项目源码 | 文件源码
def get_qimage(self, image: np.ndarray):
        height, width, colors = image.shape
        bytesPerLine = 3 * width
        QImage = QtGui.QImage

        image = QImage(image.data,
                       width,
                       height,
                       bytesPerLine,
                       QImage.Format_RGB888)

        image = image.rgbSwapped()
        return image
项目:blog    作者:benhoff    | 项目源码 | 文件源码
def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawImage(0, 0, self.image)
        self.image = QtGui.QImage()
项目:blog    作者:benhoff    | 项目源码 | 文件源码
def __init__(self, haar_cascade_filepath, parent=None):
        super().__init__(parent)
        self.classifier = cv2.CascadeClassifier(haar_cascade_filepath)
        self.image = QtGui.QImage()
        self._red = (0, 0, 255)
        self._width = 2
        self._min_size = (30, 30)
项目:blog    作者:benhoff    | 项目源码 | 文件源码
def get_qimage(self, image: np.ndarray):
        height, width, colors = image.shape
        bytesPerLine = 3 * width
        QImage = QtGui.QImage

        image = QImage(image.data,
                       width,
                       height,
                       bytesPerLine,
                       QImage.Format_RGB888)

        image = image.rgbSwapped()
        return image
项目:pyqt5-example    作者:guinslym    | 项目源码 | 文件源码
def __init__(self, parent=None):
        super(ImageModel, self).__init__(parent)

        self.modelImage = QImage()
项目:pyqt5-example    作者:guinslym    | 项目源码 | 文件源码
def setImage(self, image):
        self.beginResetModel()
        self.modelImage = QImage(image)
        self.endResetModel()
项目:pyqt5-example    作者:guinslym    | 项目源码 | 文件源码
def openImage(self, fileName):
        image = QImage()

        if image.load(fileName):
            self.model.setImage(image)

            if not fileName.startswith(':/'):
                self.currentPath = fileName
                self.setWindowTitle("%s - Pixelator" % self.currentPath)

            self.printAction.setEnabled(True)
            self.updateView()
项目:pyqt5-example    作者:guinslym    | 项目源码 | 文件源码
def loadFromMemory(self):
        """ This slot function is called in the second Dialog process, when the
        user presses the "Load Image from Shared Memory" button.  First, it
        attaches the process to the shared memory segment created by the first
        Dialog process.  Then it locks the segment for exclusive access, copies
        the image data from the segment into a QBuffer, and streams the QBuffer
        into a QImage.  Then it unlocks the shared memory segment, detaches
        from it, and finally displays the QImage in the Dialog.
        """

        if not self.sharedMemory.attach():
            self.ui.label.setText(
                    "Unable to attach to shared memory segment.\nLoad an "
                    "image first.")
            return

        buf = QBuffer()
        ins = QDataStream(buf)
        image = QImage()

        self.sharedMemory.lock()
        buf.setData(self.sharedMemory.constData())
        buf.open(QBuffer.ReadOnly)
        ins >> image
        self.sharedMemory.unlock()
        self.sharedMemory.detach()

        self.ui.label.setPixmap(QPixmap.fromImage(image))
项目:pyqt5-example    作者:guinslym    | 项目源码 | 文件源码
def changeIcon(self):
        icon = QIcon()

        for row in range(self.imagesTable.rowCount()):
            item0 = self.imagesTable.item(row, 0)
            item1 = self.imagesTable.item(row, 1)
            item2 = self.imagesTable.item(row, 2)

            if item0.checkState() == Qt.Checked:
                if item1.text() == "Normal":
                    mode = QIcon.Normal
                elif item1.text() == "Active":
                    mode = QIcon.Active
                elif item1.text() == "Disabled":
                    mode = QIcon.Disabled
                else:
                    mode = QIcon.Selected

                if item2.text() == "On":
                    state = QIcon.On
                else:
                    state = QIcon.Off

                fileName = item0.data(Qt.UserRole)
                image = QImage(fileName)
                if not image.isNull():
                    icon.addPixmap(QPixmap.fromImage(image), mode, state)

        self.previewArea.setIcon(icon)
项目:Red-GUI    作者:ScarletRav3n    | 项目源码 | 文件源码
def init_ui(self):

        # v.box
        gbox = QtWidgets.QGridLayout()
        box = QtWidgets.QVBoxLayout()
        self.rbox = QtWidgets.QVBoxLayout()
        self.hbox = QtWidgets.QHBoxLayout()

        # padding/margins
        gbox.setContentsMargins(0, 0, 0, 0)
        self.rbox.setContentsMargins(0, 0, 10, 10)
        self.hbox.setContentsMargins(0, 0, 10, 10)
        box.addStretch()
        self.hbox.addStretch()
        gbox.setSpacing(10)
        box.setSpacing(0)
        self.rbox.setSpacing(5)
        self.hbox.setSpacing(0)

        image = QtGui.QImage()
        image.loadFromData(urllib.request.urlopen('http://i.imgur.com/04DUqa3.png').read())
        png = QLabel(self)
        pixmap = QtGui.QPixmap(image)
        png.setPixmap(pixmap)
        gbox.addWidget(png, 0, 0, 1, 1, Qt.AlignTop)

        box.insertSpacing(1, 10)
        self.l1 = QLabel(self)
        self.l1.setWordWrap(True)
        self.large_font.setBold(True)
        self.l1.setFont(self.large_font)
        box.addWidget(self.l1, 0, Qt.AlignTop)

        hline = QtWidgets.QFrame()
        hline.setFrameShape(QtWidgets.QFrame.HLine)
        hline.setFrameShadow(QtWidgets.QFrame.Sunken)
        gbox.addWidget(hline, 0, 0, 1, 3, Qt.AlignBottom)

        # start form
        self.req_ui()

        self.rbox.setAlignment(Qt.AlignTop)
        box.addLayout(self.rbox, 1)
        gbox.addLayout(box, 0, 1, 1, 2)
        gbox.addLayout(self.hbox, 1, 0, 1, 3)
        self.setLayout(gbox)

        # window
        self.setFixedSize(490, 400)
        self.setWindowIcon(QtGui.QIcon('red.ico'))
        self.setWindowTitle('Red Discord Bot - Setup')
        self.show()
项目:git-annex-metadata-gui    作者:alpernebbi    | 项目源码 | 文件源码
def preview_image_file(self, path):
        filename = path.split('/')[-1]

        if self.graphics_preview is None:
            msg = "Graphics preview widget not created yet."
            logger.critical(msg)
            return

        if not self.isVisible():
            msg = "Preview widget invisible, not previewing image."
            logger.info(msg)
            return

        self.setCurrentWidget(self.graphics_preview)

        scene = QtWidgets.QGraphicsScene(self)
        self.graphics_preview.setScene(scene)

        # Using QImage instead of directly creating the QPixmap
        # prevents a segmentation fault in my container setup
        image = QtGui.QImage(path)
        if image.isNull():
            fmt = "File '{}' should be an image, but isn't."
            msg = fmt.format(filename)
            logger.error(msg)
            return

        pixmap = QtGui.QPixmap.fromImage(image)
        if pixmap.isNull():
            fmt = "Failed to generate pixmap from image '{}'."
            msg = fmt.format(filename)
            logger.critical(msg)
            return

        pixmap_item = QtWidgets.QGraphicsPixmapItem(pixmap)
        scene.addItem(pixmap_item)
        self.graphics_preview.fitInView(
            pixmap_item,
            Qt.Qt.KeepAspectRatio,
        )

        fmt = "Previewed file '{}' as an image."
        msg = fmt.format(filename)
        logger.info(msg)
项目:kodi-remote    作者:chatper    | 项目源码 | 文件源码
def handleSignals(self, signal, param):
        if signal == 'Input.OnInputRequested':
            self.showInputDialog()
            print("Text sending")
        if signal == 'Player.OnStop':
            self.isPlaying = False
            self.status.setText( 'Nothing playing now' )
            self.img.setPixmap(QPixmap(IMG_PATH))
            if self.timer.isActive():
                self.timer.stop()
                self.pbar.setValue(0)
                print('Stoping timer')
        if signal == 'play':
            self.isPlaying = True
            self.status.setText( param )
            self.rpc("Player.GetItem",{"properties":["thumbnail","fanart"],"playerid":1}, True)
            if not self.timer.isActive():
                self.timer.start(1000, self)
                print('Starting timer')
        if signal == 'queue':        
            gui.rpc("GUI.ShowNotification",{"title":"Added to playlist!", "message":param}, False)
        if signal == 'System.OnQuit' or signal == 'System.OnRestart':
            if self.timer.isActive():
                self.timer.stop()
                print('Stoping timer')
            self.quit(False)
        if signal == 'thumbnail':
            url = urllib.parse.unquote(param)
            try:
                img_arr = urllib.request.urlopen(url).read()
                qImg = QImage()
                qImg.loadFromData(img_arr)
                self.img.setPixmap(QPixmap(qImg))
            except Exception as e:
                print("---> Error while getting image: %s" % e)
        if signal == 'time':
            tokens = param.split('-',1)
            curTime = int(tokens[0])
            totTime = int(tokens[1])
            if totTime>0:
                self.pbar.setValue((curTime/totTime)*100)
        if signal == 'addons':
            OpenDialog(param, self).exec_()
        #print (signal)
项目:uah_driveset_reader    作者:Eromera    | 项目源码 | 文件源码
def startCapture(self):
      global currentSecond
      global delayVideoData
      #cap = self.capturer
      num = 0
      while(self.capturing):
         while (self.paused and self.capturing):
            time.sleep(0.05)

         prevTime = datetime.now()

         if (self.frameNumberChanged):
            newFrameNumber = int(self.sliderVideoFrame.value()*30)
            num = newFrameNumber
            self.frameNumber = newFrameNumber
            self.frameNumberChanged = False

         frame = self.videoReader.get_data(num)
         num = num+1

         if (num >= self.videoReader.get_length()):
            self.frameNumberChanged=True
            self.sliderVideoFrame.setValue(0)
            self.start_button.setText('Start')
            self.video_thread = False
            self.capturing = False      
            break

         self.frameNumber = num
         currentSecond = self.frameNumber/fps   #valor importante para sync datos
         self.labelCurrentVideoSecond.setText("{0:.1f}".format(currentSecond - delayVideoToData))
         if (self.sliderWasReleased):
            self.sliderVideoFrame.setValue(int(self.frameNumber/fps))

         #Convert opencv mat to QImage:
         imageQ = QtGui.QImage(frame.tostring(), frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888)

         if (frame.shape[1] != videowidthShow or frame.shape[0] != videoheightShow):
            imageQ = imageQ.scaled(videowidthShow, videoheightShow)  #resize image to fit

         #Convert QImage to pixmap:
         pixmap = QtGui.QPixmap.fromImage(imageQ)
         #Set pixmap to label:
         #self.labelImage.setPixmap(pixmap) #old mode, cuidado porque es un thread outside the GUI, esto da problemas en pyqt
         self.signalUpdatePixmap.emit(pixmap)   #nuevo mode para evitar esos problemas
         self.updateScoreLabels()
         diftime = ((datetime.now()-prevTime).microseconds)/1000000.0
         #print (diftime)
         #print(1/fps - diftime )
         if (diftime < 1/fps):
            time.sleep (1/fps - diftime)
         else:
            time.sleep(0.01)
         app.processEvents()    #prevents app from crashing because of lack of responsiveness
项目:DicomBrowser    作者:ericspod    | 项目源码 | 文件源码
def __init__(self,args,parent=None):
        QtGui.QMainWindow.__init__(self,parent)

        self.srclist=[] # list of source directories
        self.imageIndex=0 # index of selected image
        self.seriesMap=OrderedDict() # maps series table row tuples to DicomSeries object it was generated from
        self.seriesColumns=list(seriesListColumns) # keywords for columns
        self.selectedRow=-1 # selected series row
        self.lastDir='.' # last loaded directory root
        self.filterRegex='' # regular expression to filter tags by

        # create the directory queue and loading thread objects
        self.dirQueue=Queue() # queue of directories to load
        self.loadDirThread=threading.Thread(target=self._loadDirsThread)
        self.loadDirThread.daemon=True # clean shutdown possible with daemon threads
        self.loadDirThread.start() # start the thread now, it will wait until something is put on self.dirQueue

        # setup ui
        self.setupUi(self) # create UI elements based on the loaded .ui file
        self.setWindowTitle('DicomBrowser v%s (FOR RESEARCH ONLY)'%(__version__))
        self.setStatus('')

        # connect signals
        self.importButton.clicked.connect(self._openDirDialog)
        self.statusSignal.connect(self.setStatus)
        self.updateSignal.connect(self._updateSeriesTable)
        self.filterLine.textChanged.connect(self._setFilterString)
        self.imageSlider.valueChanged.connect(self.setSeriesImage)
        self.seriesView.clicked.connect(self._seriesTableClicked)

        # setup the list and table models
        self.srcmodel=QStringListModel()
        self.seriesmodel=SeriesTableModel(self.seriesColumns)
        self.seriesmodel.layoutChanged.connect(self._seriesTableResize)
        self.tagmodel=QtGui.QStandardItemModel()

        # assign models to views
        self.sourceListView.setModel(self.srcmodel)
        self.seriesView.setModel(self.seriesmodel)
        self.tagView.setModel(self.tagmodel)

        # create the pyqtgraph object for viewing images
        self.imageview=pg.ImageView()
        layout=QtGui.QGridLayout(self.view2DGroup)
        layout.addWidget(self.imageview)

        # load the empty image placeholder into a ndarray
        qimg=QtGui.QImage(':/icons/noimage.png')
        bytedata=qimg.constBits().asstring(qimg.width()*qimg.height())
        self.noimg=np.ndarray((qimg.width(),qimg.height()),dtype=np.ubyte,buffer=bytedata)

        # add the directories passed as arguments to the directory queue to start loading
        for i in args:
            if os.path.isdir(i):
                self.addSourceDir(i)
项目:brown    作者:ajyoon    | 项目源码 | 文件源码
def render_image(self, rect, image_path, dpm, quality, bg_color, autocrop):
        """Render a section of self.scene to an image.

        It is assumed that all input arguments are valid.

        Args:
            rect (Rect): The part of the document to render,
                in document coordinates.
            image_path (str): The path to the output image.
                This must be a valid path relative to the current
                working directory.
            dpm (int): The pixels per meter of the rendered image.
            quality (int): The quality of the output image for compressed
                image formats. Must be either `-1` (default compression) or
                between `0` (most compressed) and `100` (least compressed).
            bg_color (Color): The background color for the image.
            autocrop (bool): Whether or not to crop the output image to tightly
                fit the contents of the frame. If true, the image will be
                cropped such that all 4 edges have at least one pixel not of
                `bg_color`.

        Returns: None

        Raises:
            ImageExportError: If Qt image export fails for unknown reasons.
        """
        scale_factor = dpm / Unit(Meter(1)).value
        pix_width = Unit(rect.width).value * scale_factor
        pix_height = Unit(rect.height).value * scale_factor

        q_image = QtGui.QImage(pix_width, pix_height,
                               QtGui.QImage.Format_ARGB32)
        q_image.setDotsPerMeterX(dpm)
        q_image.setDotsPerMeterY(dpm)
        q_color = color_to_q_color(bg_color)
        q_image.fill(q_color)

        painter = QtGui.QPainter()
        painter.begin(q_image)

        target_rect = QtCore.QRectF(q_image.rect())
        source_rect = rect_to_qt_rect_f(rect)

        self.scene.render(painter, target=target_rect, source=source_rect)
        painter.end()

        if autocrop:
            q_image = images.autocrop(q_image, q_color)

        success = q_image.save(image_path, quality=quality)

        if not success:
            raise ImageExportError(
                'Unknown error occurred when exporting image to ' + image_path)