Esempio n. 1
0
def main():

    img = QImage("D:\\Tulips.jpg")
    print("byteCount()=%d" % img.byteCount())
    print("bytesPerLine()=%d" % img.bytesPerLine())
    cv_np = convertQImageToMat(img)
    #cv_np = QImageToCvMat(img)  #测试没通过
    cv_img = cv_np
    print("%d,%d,%d" % (cv_img.shape[0], cv_img.shape[1], cv_img.shape[2]))

    cv_img = rotate_bound(cv_img, 30)

    cv2.imwrite("D:\\tulips_cv.jpg", cv_img)
    #cv2.imshow("OpenCV",cv_img)
    #cv2.waitKey()

    #cv_img = cv2.cvtColor(cv_np, cv2.COLOR_BGR2RGB)
    #w = cv_img.shape[0]
    #h = cv_img.shape[1]
    print("lenght=%d,(%d,%d)", (cv_img.size, cv_img.shape[0], cv_img.shape[1]))
    print("bit[1]=%d,bit[2]=%d,bit[3]=%d",
          (cv_img[0][0][0], cv_img[0][0][1], cv_img[0][0][2]))

    #qt_img = QImage(cv_img, w, h, w * 4, QImage.Format_RGB32)

    qt_img = np2qpixmap(cv_img)
    print("byteCount()=%d" % qt_img.byteCount())
    qt_img.save("D:\\tulips_qt.jpg")
    return cv_img
Esempio n. 2
0
def convert_bgr_to_QImage(t_img):
    height, width, channel = t_img.shape
    print('shape = {0}'.format(t_img.shape))
    bytes_per_line = channel * width
    img = QImage(t_img.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
    print('QImage: w: {0}, h: {1}, bytes: {2}'.format(img.width(), img.height(), img.byteCount()))
    return img
Esempio n. 3
0
def qimage2numpy(qimage: QImage):
    """Convert QImage to numpy.ndarray.  The dtype defaults to uint8
    for QImage.Format_Indexed8 or `bgra_dtype` (i.e. a record array)
    for 32bit color images.  You can pass a different dtype to use, or
    'array' to get a 3D uint8 array for color images."""
    result_shape = (qimage.height(), qimage.width())
    temp_shape = (qimage.height(), int(qimage.bytesPerLine() * 8 / qimage.depth()))
    if qimage.format() in (QImage.Format_ARGB32_Premultiplied,
                           QImage.Format_ARGB32,
                           QImage.Format_RGB32):
        dtype = np.uint8
        result_shape += (4,)
        temp_shape += (4,)
    elif qimage.format() == QtGui.QImage.Format_Indexed8:
        dtype = np.uint8
    else:
        raise ValueError("qimage2numpy only supports 32bit and 8bit images")
        # FIXME: raise error if alignment does not match
    buf = qimage.bits().asstring(qimage.byteCount())
    result = np.frombuffer(buf, dtype).reshape(temp_shape)
    if result_shape != temp_shape:
        result = result[:, :result_shape[1]]
    if qimage.format() == QImage.Format_RGB32 and dtype == np.uint8:
        result = result[..., :3]
    return result
Esempio n. 4
0
class ImageWidget(QLabel):
    updateRow = pyqtSignal(int, bytearray)
    imageComplete = pyqtSignal()

    def _updateRow(self, i, line):
        print("updateRow {}".format(i))
        lineSize = self.image.width() * 4
        offset = lineSize * i
        self.imagePtr[offset:offset + lineSize] = line
        self._updatePixmap()

    def _updatePixmap(self):
        self.setPixmap(QPixmap.fromImage(self.image))

    def resizeEvent(self, event):
        self._updatePixmap()

    def saveImage(self):
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        self.image.save("scan_{}.png".format(timestamp))

    def __init__(self, imageSize, parent=None):
        super(ImageWidget, self).__init__()
        self.setScaledContents(True)
        self.image = QImage(*imageSize, QImage.Format_ARGB32)
        self.image.fill(0x12345678)
        self.imagePtr = self.image.bits()
        self.imagePtr.setsize(self.image.byteCount())
        self.updateRow.connect(self._updateRow)
        self.imageComplete.connect(self.saveImage)
        self.setMinimumSize(100, 100)
        self.setScaledContents(True)
        self.setCursor(Qt.BlankCursor)
Esempio n. 5
0
def white_outline(image: QImage, sigma=6, repeat=6) -> QImage:
    if image.format() != QImage.Format_ARGB32:
        image = image.convertToFormat(QImage.Format_ARGB32)

    bits = image.bits()
    bits.setsize(image.byteCount())

    shape = (image.width() * image.height())
    strides = (4,)

    alpha = numpy.ndarray(shape=shape, dtype=numpy.uint8,
                          buffer=bits, strides=strides, offset=3)
    color = numpy.ndarray(shape=shape, dtype=numpy.uint8)
    color.fill(255)

    alpha = alpha.reshape((image.width(), image.height()))
    alpha = alpha.astype(numpy.float)
    alpha = gaussian_filter(alpha, sigma=sigma)
    alpha *= repeat
    numpy.clip(alpha, 0, 255, out=alpha)
    alpha = alpha.astype(numpy.uint8)
    alpha = alpha.reshape(shape)

    arr = numpy.dstack((color, color, color, alpha))

    return QImage(arr, image.width(), image.height(), QImage.Format_ARGB32)
Esempio n. 6
0
def create_tile_mode7_indexed(data):
    # Each byte is a pixel. 8bit palette.
    tile = array('B', range(64))
    tile = data[:64]
    img = QImage(8, 8, QImage.Format_Indexed8)
    imgbits = img.bits()
    imgbits.setsize(img.byteCount())
    imgbits[:64] = tile
    return img
def pixmap2cv(pixmap):
    qImg = QImage(pixmap)
    qImg = qImg.convertToFormat(4)

    width = qImg.width()
    height = qImg.height()
    ptr = qImg.bits()
    ptr.setsize(qImg.byteCount())
    arr = np.array(ptr).reshape(height, width, 4)  #  Copies the data
    return arr
Esempio n. 8
0
    def set_colors(data: bin,
                   fg: QColor,
                   bg: QColor,
                   trans: QColor,
                   swap_fg_bg=False) -> bin:  # pylint: disable=too-many-locals
        """
        Burns foreground and background colors into a raster image, and returns
        the results as a PNG binary
        """
        image = QImage()
        image.loadFromData(data)
        if image.isNull():
            raise UnreadablePictureException(
                'Could not read embedded picture data')

        image = image.convertToFormat(QImage.Format_ARGB32)
        ucharptr = image.bits()
        ucharptr.setsize(image.byteCount() * image.height())

        fg_rgba = qRgba(fg.red(), fg.green(), fg.blue(),
                        fg.alpha()) if fg and fg.isValid() else None
        bg_rgba = qRgba(bg.red(), bg.green(), bg.blue(),
                        bg.alpha()) if bg and bg.isValid() else None

        COLOR_TOLERANCE = 40

        fg_comp = 0
        bg_comp = 255

        for y in range(image.height()):
            start = y * image.width() * 4
            for x in range(image.width()):
                x_start = x * 4 + start
                rgba = struct.unpack('I', ucharptr[x_start:x_start + 4])[0]
                if trans and abs(qRed(rgba) - trans.red(
                )) < COLOR_TOLERANCE and abs(qGreen(rgba) - trans.green(
                )) < COLOR_TOLERANCE and abs(qBlue(rgba) -
                                             trans.blue()) < COLOR_TOLERANCE:
                    ucharptr[x_start:x_start + 4] = struct.pack(
                        'I', qRgba(0, 0, 0, 0))
                elif fg_rgba is not None and abs(
                        qRed(rgba) - fg_comp) < COLOR_TOLERANCE and abs(
                            qGreen(rgba) - fg_comp) < COLOR_TOLERANCE and abs(
                                qBlue(rgba) - fg_comp) < COLOR_TOLERANCE:
                    ucharptr[x_start:x_start + 4] = struct.pack('I', fg_rgba)
                elif bg_rgba is not None and abs(
                        qRed(rgba) - bg_comp) < COLOR_TOLERANCE and abs(
                            qGreen(rgba) - bg_comp) < COLOR_TOLERANCE and abs(
                                qBlue(rgba) - bg_comp) < COLOR_TOLERANCE:
                    ucharptr[x_start:x_start + 4] = struct.pack('I', bg_rgba)

        # convert to PNG
        png_data = QBuffer()
        image.save(png_data, "png")
        return png_data.data()
Esempio n. 9
0
def create_tritile(data):
    img = QImage(16, 12, QImage.Format_Indexed8)
    imgbits = img.bits()
    imgbits.setsize(img.byteCount())
    img.setColorTable(const.dialogue_palette)
    tile = array('B', range(192))
    for p, row, b in [(p, j, b) for p in range(2) for j in range(12)
                      for b in reversed(range(8))]:
        tile[(7 - b) + (row * 16) + (p * 8)] = (data[row + (p * 12)] >> b & 1)
    imgbits[:192] = tile
    return QPixmap.fromImage(img)
Esempio n. 10
0
def np2qimage(np_img):
    #frame = cv2.cvtColor(np_img, cv2.COLOR_BGR2RGBA)
    #frame = copy.deepcopy(np_img)
    frame = np_img
    print("framelenght=%d,(%d,%d),%",
          (frame.size, frame.shape[0], frame.shape[1],
           frame.shape[0] * frame.shape[1] * 4))
    img = QImage(frame, frame.shape[1], frame.shape[0],
                 QImage.Format_RGB32)  #  , frame.shape[1] * 4 RGBA8888
    print("byteCount()=%d" % img.byteCount())
    return img  #QPixmap.fromImage(img)
Esempio n. 11
0
    def load_graphics(self, path):
        graphics = []
        list_of_files = [f for f in listdir(path) if isfile(join(path, f))]

        for i in list_of_files:
            im = QImage(path + '/' + i)
            im = im.convertToFormat(QImage.Format_RGBA8888)
            ptr = im.bits()
            ptr.setsize(im.byteCount())
            graphics.append(ptr.asstring())

        return graphics
Esempio n. 12
0
 def qimage_to_pil(self, qimage: QImage) -> Image:
     """ Convert QImage (in ARGB32 format) to PIL.Image (in RGBA mode). """
     # In our case QImage uses 0xAARRGGBB format stored in host endian
     # order, we must convert it to [0xRR, 0xGG, 0xBB, 0xAA] sequences
     # used by Pillow.
     buf = qimage.bits().asstring(qimage.byteCount())
     if sys.byteorder != "little":
         buf = swap_byte_order_i32(buf)
     return Image.frombytes(
         self.pillow_image_format,
         qsize_to_tuple(qimage.size()),
         buf, 'raw', self.pillow_decoder_format)
Esempio n. 13
0
    def getImageBoundaries(image: QImage):
        # Look at the resulting image to get a good crop.
        # Get the pixels as byte array
        pixel_array = image.bits().asarray(image.byteCount())
        width, height = image.width(), image.height()
        # Convert to numpy array, assume it's 32 bit (it should always be)
        pixels = numpy.frombuffer(pixel_array, dtype=numpy.uint8).reshape([height, width, 4])
        # Find indices of non zero pixels
        nonzero_pixels = numpy.nonzero(pixels)
        min_y, min_x, min_a_ = numpy.amin(nonzero_pixels, axis=1)
        max_y, max_x, max_a_ = numpy.amax(nonzero_pixels, axis=1)

        return min_x, max_x, min_y, max_y
Esempio n. 14
0
    def getImageBoundaries(image: QImage):
        # Look at the resulting image to get a good crop.
        # Get the pixels as byte array
        pixel_array = image.bits().asarray(image.byteCount())
        width, height = image.width(), image.height()
        # Convert to numpy array, assume it's 32 bit (it should always be)
        pixels = numpy.frombuffer(pixel_array, dtype=numpy.uint8).reshape([height, width, 4])
        # Find indices of non zero pixels
        nonzero_pixels = numpy.nonzero(pixels)
        min_y, min_x, min_a_ = numpy.amin(nonzero_pixels, axis=1)
        max_y, max_x, max_a_ = numpy.amax(nonzero_pixels, axis=1)

        return min_x, max_x, min_y, max_y
Esempio n. 15
0
    def initHeightMap(self, fileName):
        heightImage = QImage(fileName)
        bits = heightImage.constBits().asarray(heightImage.byteCount())
        colorTable = heightImage.colorTable()

        layerData = bytearray(self.layerDataSize**2)
        index = 0

        for i in range(self.layerDataSize):
            for j in range(self.layerDataSize):
                layerData[index] = qRed(colorTable[bits[index]])
                index += 1

        return layerData
Esempio n. 16
0
    def load_image(self, path):
        qim = QImage(path).mirrored()
        qim = qim.convertToFormat(QImage.Format_RGBA8888_Premultiplied)
        ptr = qim.bits()
        ptr.setsize(qim.byteCount())
        image_data = np.asarray(ptr).reshape(qim.width(), qim.height(), 4)

        im = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, im)
        glTexImage2D( GL_TEXTURE_2D, 0, 4, qim.width(), qim.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data)
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glDisable(GL_ALPHA_TEST)
        self.images[path] = im
        self.image_values[path] = QRect(0, 0, qim.width(), qim.height())
        self.imageOrder.append(path)
Esempio n. 17
0
    def colorize_picture(picture, color):
        """
        Applies a color overlay to a picture, emulating the ArcMap
        results
        """
        if issubclass(picture.__class__, StdPicture):
            picture = picture.picture

        image = QImage()
        image.loadFromData(picture.content)
        if image.isNull():
            raise UnreadablePictureException('Could not read embedded picture data')

        image = image.convertToFormat(QImage.Format_ARGB32)
        ucharptr = image.bits()
        ucharptr.setsize(image.byteCount() * image.height())

        # assume top left pixel is transparent?
        c = image.pixelColor(0, 0)
        trans_rgba = qRgba(c.red(), c.green(), c.blue(), c.alpha())
        actual_trans_rgba = qRgba(c.red(), c.green(), c.blue(), 0)

        for y in range(image.height()):
            start = y * image.width() * 4
            for x in range(image.width()):
                x_start = x * 4 + start
                rgba = struct.unpack('I', ucharptr[x_start:x_start + 4])[0]

                if rgba == trans_rgba:
                    ucharptr[x_start:x_start + 4] = struct.pack('I', actual_trans_rgba)

        if color is None or color.is_null:
            return image

        fg_color = ColorConverter.color_to_qcolor(color)
        if not fg_color.isValid():
            return image

        alpha = QImage(image)
        image.detach()
        p = QPainter(image)
        p.setCompositionMode(QPainter.CompositionMode_SourceIn)
        p.setBrush(fg_color)
        p.drawRect(image.rect())
        p.setCompositionMode(QPainter.CompositionMode_Multiply)
        p.drawImage(0, 0, alpha)
        p.end()
        return image
Esempio n. 18
0
            def run(self):
                self._abort = False

                while True:
                    with QMutexLocker(self._mutex):
                        if self._abort:
                            break
                        frame = self.frame
                        self.frame = None

                    pixel_format = frame.pixelFormat()
                    image_format = QVideoFrame.imageFormatFromPixelFormat(pixel_format)
                    if image_format == QImage.Format_Invalid:
                        qDebug("WARNING: Could not convert video frame to image!")
                        return
                    if not frame.map(QAbstractVideoBuffer.ReadOnly):
                        qDebug("WARNING: Could not map video frame!")
                        return

                    width = frame.width()
                    height = frame.height()
                    bytes_per_line = frame.bytesPerLine()
                    image = QImage(frame.bits(), width, height, bytes_per_line, image_format)
                    image = image.convertToFormat(QImage.Format_RGB32)

                    frame.unmap()

                    # fix upside-down data for windows
                    if platform.system() == "Windows":
                        image = image.mirrored(vertical=True)

                    # now convert QImage to ndarray
                    pointer = image.constBits()
                    pointer.setsize(image.byteCount())
                    array = np.array(pointer).reshape(image.height(), image.width(), 4)

                    # get rid of the transparency channel and organize the colors as rgb
                    # NB: it would be safer to figure out the image format first, and where the transparency channel is
                    # stored...
                    array = array[:, :, 0:3:][:, :, ::-1]

                    self.ndarray_available.emit(array)

                    # see if new data is available, go to sleep if not
                    with QMutexLocker(self._mutex):
                        if self.frame is None:
                            self._condition.wait(self._mutex)
Esempio n. 19
0
    def get_snapshot(self, bw=None, return_as_array=None):
        qimage = QImage(self.image)
        if return_as_array:
            qimage = qimage.convertToFormat(4)
            ptr = qimage.bits()
            ptr.setsize(qimage.byteCount())

            image_array = np.array(ptr).reshape(qimage.height(), qimage.width(), 4)
            if bw:
                return np.dot(image_array[..., :3], [0.299, 0.587, 0.144])
            else:
                return image_array
        else:
            if bw:
                return qimage.convertToFormat(QImage.Format_Mono)
            else:
                return qimage
    def get_snapshot(self, bw=None, return_as_array=None):
        qimage = QImage(self.image)
        if return_as_array:
            qimage = qimage.convertToFormat(4)
            ptr = qimage.bits()
            ptr.setsize(qimage.byteCount())

            image_array = np.array(ptr).reshape(qimage.height(), qimage.width(), 4)
            if bw:
                return np.dot(image_array[..., :3], [0.299, 0.587, 0.144])
            else:
                return image_array
        else:
            if bw:
                return qimage.convertToFormat(QImage.Format_Mono)
            else:
                return qimage
Esempio n. 21
0
def create_tile_old(data, palette):
    '''
    Creates a QPixmap of a SNES tile. DO NOT USE OUTSIDE OF QApplication CONTEXT
    '''
    planes = len(data) // 8
    tile = array('B', range(64))
    img = QImage(8, 8, QImage.Format_Indexed8)
    imgbits = img.bits()
    imgbits.setsize(img.byteCount())
    if planes == 0:
        raise ValueError("Empty bytes passed")
    if planes == 1:
        img.setColorTable([0x00000080, 0xFFFFFFFF])
        t_ptr = 0
        for j, x in [(j, x) for j in range(8) for x in reversed(range(8))]:
            tile[t_ptr] = (data[j] >> x & 1)
            t_ptr += 1
    else:
        img.setColorTable(palette)
        t_ptr = 0
        for j, x in [(j, x) for j in range(0, 16, 2)
                     for x in reversed(range(8))]:
            tile[t_ptr] = (data[j] >> x & 1) | ((data[j + 1] >> x & 1) << 1)
            t_ptr += 1
        t_ptr = 0
        if planes == 3:
            for j, x in [(j, x) for j in range(16, 24, 1)
                         for x in reversed(range(8))]:
                tile[t_ptr] |= ((data[j] >> x & 1) << 2)
                t_ptr += 1
        elif planes >= 4:
            for j, x in [(j, x) for j in range(16, 32, 2)
                         for x in reversed(range(8))]:
                tile[t_ptr] |= ((data[j] >> x & 1) << 2) | (
                    (data[j + 1] >> x & 1) << 3)
                t_ptr += 1
        if planes == 8:
            t_ptr = 0
            for j, x in [(j, x) for j in range(32, 48, 2)
                         for x in reversed(range(8))]:
                tile[t_ptr] |= ((data[j] >> x & 1) << 4) | ((data[j+1] >> x & 1) << 5) \
                    | ((data[j+16] >> x & 1) << 6) | ((data[j+17] >> x & 1) << 7)
                t_ptr += 1
    imgbits[:64] = tile
    return QPixmap.fromImage(img)
Esempio n. 22
0
 def onExtendedDataArrived(self, category, data):
     if category == 'videoFrame' and self._timer.isActive():
         self._nextFrame = True
         image = QImage(data, self._width, self._height,
                        QImage.Format_RGB16)
         if self._filename:
             image.save(self._filename)
             self._filename = None
         self.frame = image
         bits = image.bits()
         bits.setsize(image.byteCount())
         frame = np.array(bits, np.uint8).reshape(self._height, self._width,
                                                  2)
         frame = cv2.cvtColor(frame, cv2.COLOR_BGR5652BGR)
         self._videoWriter.write(frame)
         return True
     else:
         return False
Esempio n. 23
0
class Canvas_Indexed:
    def __init__(self, cols, rows, color=0, tilesize=8):
        self.image = QImage(tilesize * cols, tilesize * rows,
                            QImage.Format_Indexed8)
        self.width = tilesize * cols
        self.tilesize = tilesize
        self.image.fill(0)
        self.imgbits = self.image.bits()
        self.imgbits.setsize(self.image.byteCount())
        self.max_col = 1
        self.max_row = 1

    def draw_tile(self,
                  col,
                  row,
                  image,
                  h_flip=False,
                  v_flip=False,
                  palette=0):
        image = image.mirrored(h_flip, v_flip)
        imgbits = image.bits()
        imgbits.setsize(image.byteCount())
        if palette:
            p = palette << 4
            imgbits[:] = bytes([int(i[0]) | p for i in imgbits])
        x = col * self.tilesize
        y = row * self.tilesize
        start = x + y * self.width
        for i in range(self.tilesize):
            offset = i * self.width
            self.imgbits[start + offset:start + offset +
                         self.tilesize] = imgbits[i * self.tilesize:(i + 1) *
                                                  self.tilesize]
        self.max_col = max(col, self.max_col)
        self.max_row = max(row, self.max_row)

    def pixmap(self, palette, trim=False):
        if trim:
            img = self.image.copy(0, 0, (self.max_col + 1) * self.tilesize,
                                  (self.max_row + 1) * self.tilesize)
            img.setColorTable(palette)
            return QPixmap.fromImage(img)
        self.image.setColorTable(palette)
        return QPixmap.fromImage(self.image)
Esempio n. 24
0
    def colorize_picture_data(data, color: QColor, fix_alpha=True):
        """
        Colorizes picture data
        """
        image = QImage()
        image.loadFromData(data)
        if image.isNull():
            raise UnreadablePictureException('Could not read embedded picture data')

        image = image.convertToFormat(QImage.Format_ARGB32)
        ucharptr = image.bits()
        ucharptr.setsize(image.byteCount() * image.height())

        # assume top left pixel is transparent?
        if fix_alpha:
            c = image.pixelColor(0, 0)
            trans_rgba = qRgba(c.red(), c.green(), c.blue(), c.alpha())
            actual_trans_rgba = qRgba(c.red(), c.green(), c.blue(), 0)

            for y in range(image.height()):
                start = y * image.width() * 4
                for x in range(image.width()):
                    x_start = x * 4 + start
                    rgba = struct.unpack('I', ucharptr[x_start:x_start + 4])[0]

                    if rgba == trans_rgba:
                        ucharptr[x_start:x_start + 4] = struct.pack('I', actual_trans_rgba)

        if not color.isValid():
            return image

        alpha = QImage(image)
        image.detach()
        p = QPainter(image)
        p.setCompositionMode(QPainter.CompositionMode_SourceIn)
        p.setBrush(color)
        p.drawRect(image.rect())
        p.setCompositionMode(QPainter.CompositionMode_Multiply)
        p.drawImage(0, 0, alpha)
        p.end()
        return image
Esempio n. 25
0
    def setImageColor(cls, img, color):
        """Set an image to a single color while preserving the alpha"""
        img = QImage(img)
        modifiedImg = None
        # return img

        red = color.red()
        green = color.green()
        blue = color.blue()
        bits = img.bits()
        bits.setsize(img.byteCount())
        #
        arr = numpy.array(bits).reshape(img.height(), img.width(), 4)
        for line in arr:
            for pix in line:
                pix[0] = blue
                pix[1] = green
                pix[2] = red
        modifiedImg = QImage(arr, img.width(), img.height(),
                             QImage.Format_ARGB32)
        return modifiedImg
Esempio n. 26
0
def drop_shadow(image: QImage) -> QImage:
    if image.format() != QImage.Format_ARGB32:
        image = image.convertToFormat(QImage.Format_ARGB32)

    bits = image.bits()
    bits.setsize(image.byteCount())

    shape = (image.width() * image.height())
    strides = (4,)

    alpha = numpy.ndarray(shape=shape, dtype=numpy.uint8,
                          buffer=bits, strides=strides, offset=3)
    color = numpy.ndarray(shape=shape, dtype=numpy.uint8)
    color.fill(0)

    alpha = alpha.reshape((image.width(), image.height()))
    alpha = gaussian_filter(alpha, sigma=10)
    alpha = alpha.reshape(shape)

    arr = numpy.dstack((color, color, color, alpha))

    return QImage(arr, image.width(), image.height(), QImage.Format_ARGB32)
Esempio n. 27
0
 def b_layer_create(self):
     temp_dir = tempfile.gettempdir() + "/rcpg10.svg"
     body = self.rcpg_object.get_svg_string()
     with open(temp_dir, 'w', encoding='utf-8') as f:
         f.write(body)
     app = Krita.instance()
     doc = app.activeDocument()
     if doc != None:
         root = doc.rootNode()
         layer = doc.createNode("Panels", "paintLayer")
         img = QImage(temp_dir)
         img = img.scaled(doc.width(),
                          doc.height(),
                          aspectRatioMode=Qt.KeepAspectRatio,
                          transformMode=Qt.SmoothTransformation)
         if not img.isNull():
             img.convertToFormat(QImage.Format_RGBA8888)
             ptr = img.constBits()
             ptr.setsize(img.byteCount())
             layer.setPixelData(bytes(ptr.asarray()), 0, 0, img.width(),
                                img.height())
         root.addChildNode(layer, None)
         doc.refreshProjection()
Esempio n. 28
0
def run_facedetect(filename: str) -> Tuple[QImage, List[Any]]:
    image = QImage(filename)
    if image.format() != QImage.Format_RGB32:
        image = image.convertToFormat(QImage.Format_RGB32)

    image = image.scaled(image.width() * scale_factor,
                         image.height() * scale_factor,
                         Qt.IgnoreAspectRatio,
                         Qt.SmoothTransformation)

    bits = image.bits()
    bits.setsize(image.byteCount())

    array = numpy.ndarray(shape=(image.height(), image.bytesPerLine() // 4, 4), dtype=numpy.uint8,
                          buffer=bits)
    array = array[:image.height(), :image.width(), :3]

    img = cv2.imread(filename, cv2.IMREAD_COLOR)
    print(img.shape)
    print(array.shape)

    print(img)
    print()
    print(array)

    detector = dlib.get_frontal_face_detector()
    results = detector(img)
    print(results)
    results = detector(array)
    print(results)

    print("detected {} faces".format(len(results)))

    image = image.scaled(image.width() // scale_factor,
                         image.height() // scale_factor)

    return image, results
Esempio n. 29
0
    def set_colors(data: bin, fg: QColor, bg: QColor, trans: QColor) -> bin:  # pylint: disable=too-many-locals
        """
        Burns foreground and background colors into a raster image, and returns
        the results as a PNG binary
        """
        image = QImage()
        image.loadFromData(data)

        image = image.convertToFormat(QImage.Format_ARGB32)
        ucharptr = image.bits()
        ucharptr.setsize(image.byteCount() * image.height())

        fg_rgba = qRgba(fg.red(), fg.green(), fg.blue(),
                        fg.alpha()) if fg and fg.isValid() else None
        bg_rgba = qRgba(bg.red(), bg.green(), bg.blue(),
                        bg.alpha()) if bg and bg.isValid() else None

        # TODO: what's this even for?
        _ = qRgba(trans.red(), trans.green(), trans.blue(),
                  trans.alpha()) if trans else None

        for y in range(image.height()):
            start = y * image.width() * 4
            for x in range(image.width()):
                x_start = x * 4 + start
                rgba = struct.unpack('I', ucharptr[x_start:x_start + 4])[0]

                if fg_rgba is not None and rgba == 0xff000000:
                    ucharptr[x_start:x_start + 4] = struct.pack('I', fg_rgba)
                elif bg_rgba is not None and rgba == 0xffffffff:
                    ucharptr[x_start:x_start + 4] = struct.pack('I', bg_rgba)

        # convert to PNG
        png_data = QBuffer()
        image.save(png_data, "png")
        return png_data.data()
Esempio n. 30
0
def create_tile_indexed(data):
    '''
  Creates a QImage of a SNES tile. Useful for assigning palettes later.
  DO NOT USE OUTSIDE OF QApplication CONTEXT
  '''
    planes = len(data) // 8
    tile = array('B', range(64))
    img = QImage(8, 8, QImage.Format_Indexed8)
    imgbits = img.bits()
    imgbits.setsize(img.byteCount())
    if planes == 0:
        raise ValueError("Empty bytes passed")
    if planes == 1:
        for i, (j, x) in enumerate([(j, x) for j in range(8)
                                    for x in reversed(range(8))]):
            tile[i] = (data[j] >> x & 1)
    else:
        for i, (j, x) in enumerate([(j, x) for j in range(0, 16, 2)
                                    for x in reversed(range(8))]):
            tile[i] = (data[j] >> x & 1) | ((data[j + 1] >> x & 1) << 1)
        if planes == 3:
            for i, (j, x) in enumerate([(j, x) for j in range(16, 24, 1)
                                        for x in reversed(range(8))]):
                tile[i] |= ((data[j] >> x & 1) << 2)
        elif planes >= 4:
            for i, (j, x) in enumerate([(j, x) for j in range(16, 32, 2)
                                        for x in reversed(range(8))]):
                tile[i] |= ((data[j] >> x & 1) << 2) | (
                    (data[j + 1] >> x & 1) << 3)
        if planes == 8:
            for i, (j, x) in enumerate([(j, x) for j in range(32, 48, 2)
                                        for x in reversed(range(8))]):
                tile[i] |= ((data[j] >> x & 1) << 4) | ((data[j+1] >> x & 1) << 5) \
                    | ((data[j+16] >> x & 1) << 6) | ((data[j+17] >> x & 1) << 7)
    imgbits[:64] = tile
    return img
    def make_white(self, layer):
        pixelBytes = layer.pixelData(0, 0, self.currentDoc.width(),
                                     self.currentDoc.height())
        imageData = QImage(pixelBytes, self.currentDoc.width(),
                           self.currentDoc.height(), QImage.Format_RGBA8888)

        for x in range(0, self.currentDoc.width()):
            for y in range(0, self.currentDoc.height()):
                pixel = imageData.pixelColor(x, y)
                imageData.setPixelColor(x, y,
                                        QColor(255, 255, 255, pixel.alpha()))

        ptr = imageData.constBits()
        ptr.setsize(imageData.byteCount())
        layer.setPixelData(bytes(ptr.asarray()), 0, 0, self.currentDoc.width(),
                           self.currentDoc.height())
        self.currentDoc.refreshProjection()

        self.i += 1
        self.save(layer, self.path + '/' + self.file + str(self.i) + '.png')

        layer.setPixelData(pixelBytes, 0, 0, self.currentDoc.width(),
                           self.currentDoc.height())
        self.currentDoc.refreshProjection()
Esempio n. 32
0
from PyQt5.QtGui import QImage, QFont, QColor
from PyQt5.QtCore import Qt
import os, numpy as np

img = QImage(filename)
img = img.convertToFormat(QImage.Format_RGB888)
assert img.format() == QImage.Format_RGB888
assert img.width()*img.height()*3 == img.byteCount()

if inscription != "":
    img2 = QImage(img.width(), img.height(), QImage.Format_RGB888)

    from PyQt5.QtGui import QPainter
    qp = QPainter()
    try:
        qp.begin(img2) #different results than painting on img!
        qp.drawImage(0,0,img)
        qp.setPen(QColor(255,185,50))
        fx = 2
        fy = 20
        font = QFont("Arial", int(0.7*img.height()/fy))
        qp.setFont(font)
        mx = img.width() / fx
        my = img.height() / fy
        for x in range(fx):
            for y in range(fy):
                qp.drawText(x*mx, y*my, mx, my, Qt.AlignCenter,inscription)
    finally:
        qp.end()
    img = img2
Esempio n. 33
0
from PyQt5.QtGui import QImage, QFont, QColor
from PyQt5.QtCore import Qt
import os, numpy as np
from scipy.ndimage import sobel, gaussian_filter

arr = np.zeros(texture.shape)

displacement_weight = 2, 1.1
if normal_texture_filename != "":
    img = QImage(normal_texture_filename)
    img = img.convertToFormat(QImage.Format_RGB888)
    assert img.format() == QImage.Format_RGB888
    assert img.width() * img.height() * 3 == img.byteCount()
    tex_arr = np.array(img.bits().asarray(img.byteCount())).reshape(
        img.width(), img.height(), 3)
    arr += tex_arr
else:
    sigma = 1.3

    tex_arr = texture.sum(axis=-1) / 3
    tex_arr2 = np.zeros(arr.shape, dtype=np.float32)
    tex_arr2[:, :,
             0] = 0.5 - sobel(tex_arr, 0) * displacement_weight[0] / 255.0
    tex_arr2[:, :,
             1] = 0.5 - sobel(tex_arr, 1) * displacement_weight[0] / 255.0
    tex_arr2[:, :, 2] = 1
    tex_arr2 /= np.linalg.norm(tex_arr2, axis=2, keepdims=True)
    tex_arr3 = gaussian_filter(tex_arr2, sigma=sigma)
    tex_arr3 /= np.linalg.norm(tex_arr3, axis=2, keepdims=True)
    tex_arr3[:, :, :2] *= displacement_weight[1]
    arr += tex_arr3