def paintEvent(self, event):
     painter = QPainter(self)
     try:
         painter.drawImage(event.rect(), self.image)
     except:
         pass
     painter.end()
Beispiel #2
0
 def paintEvent(self, ev):
     """Called when paint is needed, finds out which page to magnify."""
     layout = self.parent().surface().pageLayout()
     pos = self.geometry().center() - self.parent().surface().pos()
     page = layout.pageAt(pos)
     if not page:
         return
     pagePos = pos - page.pos()
     
     newPage = Page(page, self._scale)
     if not newPage.same_page(self._page):
         if self._page:
             self._page.magnifier = None
         self._page = newPage
         self._page.magnifier = self
     
     relx = pagePos.x() / float(page.width())
     rely = pagePos.y() / float(page.height())
     
     image = cache.image(self._page)
     img_rect = QRect(self.rect())
     if not image:
         cache.generate(self._page)
         image = cache.image(self._page, False)
         if image:
             img_rect.setWidth(self.width() * image.width() / self._page.width())
             img_rect.setHeight(self.height() * image.height() / self._page.height())
     if image:
         img_rect.moveCenter(QPoint(relx * image.width(), rely * image.height()))
         p = QPainter(self)
         p.drawImage(self.rect(), image, img_rect)
         p.setRenderHint(QPainter.Antialiasing, True)
         p.setPen(QPen(QColor(192, 192, 192, 128), 6))
         p.drawEllipse(self.rect().adjusted(2, 2, -2, -2))
Beispiel #3
0
    def paintEvent(self, event):
        super(DetailedProgress, self).paintEvent(event)
        if not self._current_progress:
            return

        painter = QPainter(self)
        width = self.width()
        height = self.height()
        aspect_ratio = float(width)/height
        nr_realizations = len(self._current_progress)
        fm_size = len(self._current_progress[0][1])
        self.grid_height = math.ceil(math.sqrt(nr_realizations / aspect_ratio))
        self.grid_width = math.ceil(self.grid_height * aspect_ratio)
        sub_grid_size = math.ceil(math.sqrt(fm_size))
        cell_height = height / self.grid_height
        cell_width = width / self.grid_width

        foreground_image = QImage(self.grid_width*sub_grid_size, self.grid_height*sub_grid_size, QImage.Format_ARGB32)
        foreground_image.fill(QColor(0, 0, 0, 0))

        for index, (iens, progress) in enumerate(self._current_progress):
            y = int(iens / self.grid_width)
            x = int(iens - (y * self.grid_width))
            self.draw_window(x * sub_grid_size, y * sub_grid_size, progress, foreground_image)
        painter.drawImage(self.contentsRect(), foreground_image)

        for index, (iens, progress) in enumerate(self._current_progress):
            y = int(iens / self.grid_width)
            x = int(iens - (y * self.grid_width))
            if iens == self.selected_realization:
                painter.setPen(QColor(240, 240, 240))
            else:
                painter.setPen(QColor(80, 80, 80))
            painter.drawRect(x * cell_width, y * cell_height, cell_width-1, cell_height-1)
            painter.drawText(x * cell_width + cell_width / 2, y * cell_height + cell_height / 2, str(iens))
Beispiel #4
0
 def _do_paint_rgb24(self, img_data, x, y, width, height, rowstride, options, callbacks):
     image = QImage(img_data, width, height, rowstride, QImage.Format_RGB888)
     pe = QPainter(self._backing)
     rect = QRectF(x, y, width, height)
     src = QRectF(0, 0, width, height)
     pe.drawImage(rect, image, src)
     return True
def get_movie_icon(file_id):
  
  icon_file   = os.path.join(MOVIE_DIR, "movie_%03d.png" % file_id)
  border_file = os.path.join(MOVIE_DIR, "clip.png")
  
  if not os.path.isfile(icon_file):
    icon_file = os.path.join(MOVIE_DIR, "movie_%03d.png" % 999)
  
  icon   = QImage(icon_file)
  border = QImage(border_file)
  
  x_pos = 10
  y_pos = 45
  
  x_offset = 29
  y_offset = 88
  
  out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
  out.fill(QColor(0, 0, 0, 0).rgba())  
  painter = QPainter(out)
  
  painter.drawImage(QRect(x_pos, y_pos, border.width(), border.height()), border, border.rect())
  painter.drawImage(QRect(x_pos + x_offset, y_pos + y_offset, icon.width(), icon.height()), icon, icon.rect())
  
  painter.end()
  
  return out
Beispiel #6
0
    def updateSlice(self):

        if self.ctslice_rgba is None:
            return

        img = self.ctslice_rgba.copy()

        if self.seeds is not None:
            if self.mode_draw:
                if self.contour_mode == 'fill':
                    self.composeRgba(img, self.seeds,
                                     self.seeds_colortable)
                elif self.contour_mode == 'contours':
                    self.get_contours(img, self.seeds)

            else:
                self.overRgba(img, self.seeds,
                              self.seeds_colortable)

        if self.contours is not None:
            if self.contour_mode == 'fill':
                self.composeRgba(img, self.contours,
                                 CONTOURS_COLORTABLE)

            elif self.contour_mode == 'contours':
                self.get_contours(img, self.contours)

        image = QImage(img.flatten(),
                     self.slice_size[0], self.slice_size[1],
                     QImage.Format_ARGB32).scaled(self.imagesize)
        painter = QPainter(self.image)
        painter.drawImage(0, 0, image)
        painter.end()

        self.update()
Beispiel #7
0
    def rerender_pdf_image(self):
        if self.ratio > RATIO_MIN:
            self.pdf_image = self.page1.renderToImage(PDF_BASE_RESOLUTION / self.ratio,
                                                     PDF_BASE_RESOLUTION / self.ratio,
                                                     self.x, self.y, self.w, self.h)
        else:
            # image1 = self.page1.renderToImage(PDF_BASE_RESOLUTION / self.ratio,
            #                                   PDF_BASE_RESOLUTION / self.ratio,
            #                                   self.x, self.y, self.w, self.h)
            # image2 = self.page2.renderToImage(PDF_BASE_RESOLUTION, # / self.ratio,
            #                                   PDF_BASE_RESOLUTION # / self.ratio,
            #                                   )
            #                                   # self.x, self.y, self.w, self.h)
            self.pdf_image = QImage(self.w, self.h, self.image1.format())
            self.pdf_image.fill(QtCore.Qt.white)

            painter = QPainter()
            painter.begin(self.pdf_image)
            painter.drawImage(self.pdf_image.rect(),
                              self.image1,
                              QRect(self.x * self.ratio/self.begin_ratio,
                                    self.y * self.ratio/self.begin_ratio,
                                    self.w * self.ratio/self.begin_ratio,
                                    self.h * self.ratio/self.begin_ratio))
            painter.end()
            
            x1 = MAGIC_RECT.x() / self.ratio - self.x
            y1 = MAGIC_RECT.y() / self.ratio - self.y
            h1 = MAGIC_RECT.height() / self.ratio
            w1 = MAGIC_RECT.width() / self.ratio
 def paintEvent(self, event):
     painter = QPainter(self)
     try:
         painter.drawImage(event.rect(), self.image)
     except:
         pass
     painter.end()
Beispiel #9
0
 def updateScene(self):
     '''
     Clear the displayed scene using self.__lastclearcolor,
     then draw the scaled current image.
     '''
     # get the scaled scene size
     labelwidth = int(self.__scalefactor * self.__scenewidth + 0.5)
     labelheight = int(self.__scalefactor * self.__sceneheight + 0.5)
     # Create the new pixmap for the label to display
     newpixmap = QPixmap(labelwidth, labelheight)
     newpixmap.fill(self.__lastclearcolor)
     if self.__sceneimage != None:
         # Draw the scaled image to the pixmap
         mypainter = QPainter(newpixmap)
         trgrect = QRectF(0.0, 0.0, float(labelwidth), float(labelheight))
         srcrect = QRectF(0.0, 0.0, float(self.__scenewidth),
                          float(self.__sceneheight))
         mypainter.drawImage(trgrect, self.__sceneimage, srcrect,
                             Qt.AutoColor)
         mypainter.end()
     # Assign the new pixmap to the label
     self.__label.setPixmap(newpixmap)
     # set the label size and values
     # so the scrollarea knows of the new size
     self.__label.setMinimumSize(labelwidth, labelheight)
     self.__label.resize(labelwidth, labelheight)
     # update the label from the new pixmap
     self.__label.update()
    def compose_image(self):
        """
        This loops through all the tiles and then composes a single map canvas renderable image
        :return: a renderable image
        :rtype: QImage
        """

        width = (self.xmax - self.xmin + 1) * self.layerDef.TILE_SIZE
        height = (self.ymax - self.ymin + 1) * self.layerDef.TILE_SIZE
        image = QImage(width, height, QImage.Format_ARGB32_Premultiplied)
        image.fill(Qt.transparent)
        p = QPainter(image)
        for tile in self.tiles.values():
            if not tile.pixel_data:
                continue

            x = tile.x - self.xmin
            y = tile.y - self.ymin
            rect = QRect(x * self.layerDef.TILE_SIZE, y * self.layerDef.TILE_SIZE,
                         self.layerDef.TILE_SIZE, self.layerDef.TILE_SIZE)

            timg = QImage()
            timg.loadFromData(tile.pixel_data)
            p.drawImage(rect, timg)
        return image
def get_cutin(cutin_id):

    if cutin_id == -1:
        return None

    cutin_file = os.path.join(CUTIN_DIR, "cutin_ico_%03d.png" % cutin_id)
    cutin_border_file = os.path.join(CUTIN_DIR, "border.png")

    if not os.path.isfile(cutin_file):
        cutin_file = os.path.join(CUTIN_DIR, "cutin_ico_%03d.png" % 999)

    cutin = QImage(cutin_file)
    border = QImage(cutin_border_file)

    x_pos = 307
    y_pos = 91

    border_x = x_pos - ((border.width() - cutin.width()) / 2)
    border_y = y_pos - ((border.height() - cutin.height()) / 2)

    out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
    out.fill(QColor(0, 0, 0, 0).rgba())
    painter = QPainter(out)

    painter.drawImage(QRect(x_pos, y_pos, cutin.width(), cutin.height()),
                      cutin, cutin.rect())
    painter.drawImage(
        QRect(border_x, border_y, border.width(), border.height()), border,
        border.rect())

    painter.end()

    return out
    def updateSlice(self):

        if self.ctslice_rgba is None:
            return

        img = self.ctslice_rgba.copy()

        if self.seeds is not None:
            if self.mode_draw:
                if self.contour_mode == 'fill':
                    self.composeRgba(img, self.seeds, self.seeds_colortable)
                elif self.contour_mode == 'contours':
                    self.get_contours(img, self.seeds)

            else:
                self.overRgba(img, self.seeds, self.seeds_colortable)

        if self.contours is not None:
            if self.contour_mode == 'fill':
                self.composeRgba(img, self.contours, CONTOURS_COLORTABLE)

            elif self.contour_mode == 'contours':
                self.get_contours(img, self.contours)

        image = QImage(img.flatten(), self.slice_size[0], self.slice_size[1],
                       QImage.Format_ARGB32).scaled(self.imagesize)
        painter = QPainter(self.image)
        painter.drawImage(0, 0, image)
        painter.end()

        self.update()
def get_sprite(sprite_id):

    sprite_file = get_sprite_file(sprite_id)

    if sprite_file == None:
        return None

    sprite_file = os.path.join(SPRITE_DIR, sprite_file)

    if not os.path.isfile(sprite_file):
        sprite_file = os.path.join(SPRITE_DIR,
                                   "bustup_%02d_%02d.png" % (99, 99))

    out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
    out.fill(QColor(0, 0, 0, 0).rgba())
    painter = QPainter(out)

    sprite = QImage(sprite_file)

    # Center the sprite on our image.
    sprite_x = (out.width() - sprite.width()) / 2
    sprite_y = 0

    painter.drawImage(
        QRect(sprite_x, sprite_y, sprite.width(), sprite.height()), sprite,
        sprite.rect())
    painter.end()

    return out
def get_ammo(ammo_id, x, y):

    if ammo_id == -1:
        return None

    ammo_file = os.path.join(AMMO_DIR, "kotodama_ico_%03d.png" % ammo_id)
    ammo_border_file = os.path.join(AMMO_DIR, "border.png")

    if not os.path.isfile(ammo_file):
        ammo_file = os.path.join(AMMO_DIR, "kotodama_ico_%03d.png" % 999)

    ammo = QImage(ammo_file)
    border = QImage(ammo_border_file)

    x_pos = x
    y_pos = y

    border_x = x_pos - ((border.width() - ammo.width()) / 2)
    border_y = y_pos - ((border.height() - ammo.height()) / 2)

    out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
    out.fill(QColor(0, 0, 0, 0).rgba())
    painter = QPainter(out)

    painter.drawImage(QRect(x_pos, y_pos, ammo.width(), ammo.height()), ammo,
                      ammo.rect())
    painter.drawImage(
        QRect(border_x, border_y, border.width(), border.height()), border,
        border.rect())

    painter.end()

    return out
def get_sprite(sprite_id):

  sprite_file = get_sprite_file(sprite_id)
  
  if sprite_file == None:
    return None
  
  sprite_file = os.path.join(SPRITE_DIR, sprite_file)
  
  if not os.path.isfile(sprite_file):
    sprite_file = os.path.join(SPRITE_DIR, "bustup_%02d_%02d.png" % (99, 99))
  
  out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
  out.fill(QColor(0, 0, 0, 0).rgba())
  painter = QPainter(out)
  
  sprite = QImage(sprite_file)
  
  # Center the sprite on our image.
  sprite_x = (out.width() - sprite.width()) / 2
  sprite_y = 0
  
  painter.drawImage(QRect(sprite_x, sprite_y, sprite.width(), sprite.height()), sprite, sprite.rect())
  painter.end()
  
  return out
Beispiel #16
0
    def add_piece_func(o, piece_id, mask_image, offset):
        # o.source_image required (QImage)
        L.debug('add_piece_func %d %r' % (piece_id, offset))

        pieceImage = QImage(mask_image)
        piecePainter = QPainter(pieceImage)
        piecePainter.setCompositionMode(QPainter.CompositionMode_SourceIn)
        piecePainter.drawImage(
            QPoint(),
            _safeQImageCopy(o.source_image, QRect(offset, mask_image.size())))
        piecePainter.end()

        # save pieceImage as pieces/piece<id>.png
        imgfile = 'piece%d.png' % piece_id
        pieceImage.save(os.path.join(o.board.imagefolder, imgfile))
        dominant_colors = find_colors(pieceImage)
        # add piece to puzzleboard
        o.board.pieces.append(
            Piece(
                id=piece_id,
                image=imgfile,
                x0=offset.x(),
                y0=offset.y(),
                w=pieceImage.width(),
                h=pieceImage.height(),
                dominant_colors=dominant_colors,
            ))
def get_cutin(cutin_id):
  
  if cutin_id == -1:
    return None
  
  cutin_file =        os.path.join(CUTIN_DIR, "cutin_ico_%03d.png" % cutin_id)
  cutin_border_file = os.path.join(CUTIN_DIR, "border.png")
  
  if not os.path.isfile(cutin_file):
    cutin_file = os.path.join(CUTIN_DIR, "cutin_ico_%03d.png" % 999)
  
  cutin  = QImage(cutin_file)
  border = QImage(cutin_border_file)
  
  x_pos = 307
  y_pos = 91
  
  border_x = x_pos - ((border.width() - cutin.width()) / 2)
  border_y = y_pos - ((border.height() - cutin.height()) / 2)
  
  out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
  out.fill(QColor(0, 0, 0, 0).rgba())
  painter = QPainter(out)
  
  painter.drawImage(QRect(x_pos, y_pos, cutin.width(), cutin.height()), cutin, cutin.rect())
  painter.drawImage(QRect(border_x, border_y, border.width(), border.height()), border, border.rect())
  
  painter.end()
  
  return out
def get_ammo(ammo_id, x, y):
  
  if ammo_id == -1:
    return None
  
  ammo_file =        os.path.join(AMMO_DIR, "kotodama_ico_%03d.png" % ammo_id)
  ammo_border_file = os.path.join(AMMO_DIR, "border.png")
  
  if not os.path.isfile(ammo_file):
    ammo_file = os.path.join(AMMO_DIR, "kotodama_ico_%03d.png" % 999)
  
  ammo  = QImage(ammo_file)
  border = QImage(ammo_border_file)
  
  x_pos = x
  y_pos = y
  
  border_x = x_pos - ((border.width() - ammo.width()) / 2)
  border_y = y_pos - ((border.height() - ammo.height()) / 2)
  
  out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
  out.fill(QColor(0, 0, 0, 0).rgba())
  painter = QPainter(out)
  
  painter.drawImage(QRect(x_pos, y_pos, ammo.width(), ammo.height()), ammo, ammo.rect())
  painter.drawImage(QRect(border_x, border_y, border.width(), border.height()), border, border.rect())
  
  painter.end()
  
  return out
Beispiel #19
0
    def print_(self):
        """Prints the document."""
        self._stop = False
        resolution = self.resolution()
        p = self.printer()
        p.setFullPage(True)
        p.setResolution(resolution)
        
        center = p.paperRect().center()
        painter = QPainter(p)
        
        pages  = self.pageList()
        if p.pageOrder() != QPrinter.FirstPageFirst:
            pages.reverse()

        total = len(pages)
        
        opts = self.renderOptions()
        document = self.document()
        
        for num, pageNum in enumerate(pages, 1):
            if self._stop:
                return p.abort()
            self.progress(num, total, pageNum)
            if num > 1:
                p.newPage()
            with lock(document):
                opts.write(document)
                page = document.page(pageNum - 1)
                img = page.renderToImage(resolution, resolution)
            rect = img.rect()
            rect.moveCenter(center)
            painter.drawImage(rect, img)
        
        return painter.end()
    def basefinished(self):
        if self.basereply.error() != QNetworkReply.NoError:
            return
        self.basepixmap = QPixmap()
        self.basepixmap.loadFromData(self.basereply.readAll())
        if self.basepixmap.size() != self.rect.size():
            self.basepixmap = self.basepixmap.scaled(self.rect.size(),
                                                     Qt.KeepAspectRatio,
                                                     Qt.SmoothTransformation)
        self.setPixmap(self.basepixmap)

        # make marker pixmap
        self.mkpixmap = QPixmap(self.basepixmap.size())
        self.mkpixmap.fill(Qt.transparent)
        br = QBrush(QColor(Config.dimcolor))
        painter = QPainter()
        painter.begin(self.mkpixmap)
        painter.fillRect(0, 0, self.mkpixmap.width(), self.mkpixmap.height(),
                         br)
        for marker in self.radar['markers']:
            if 'visible' not in marker or marker['visible'] == 1:
                pt = getPoint(marker["location"], self.point, self.zoom,
                              self.rect.width(), self.rect.height())
                mk2 = QImage()
                mkfile = 'teardrop'
                if 'image' in marker:
                    mkfile = marker['image']
                if os.path.dirname(mkfile) == '':
                    mkfile = os.path.join('markers', mkfile)
                if os.path.splitext(mkfile)[1] == '':
                    mkfile += '.png'
                mk2.load(mkfile)
                if mk2.format != QImage.Format_ARGB32:
                    mk2 = mk2.convertToFormat(QImage.Format_ARGB32)
                mkh = 80  # self.rect.height() / 5
                if 'size' in marker:
                    if marker['size'] == 'small':
                        mkh = 64
                    if marker['size'] == 'mid':
                        mkh = 70
                    if marker['size'] == 'tiny':
                        mkh = 40
                if 'color' in marker:
                    c = QColor(marker['color'])
                    (cr, cg, cb, ca) = c.getRgbF()
                    for x in range(0, mk2.width()):
                        for y in range(0, mk2.height()):
                            (r, g, b,
                             a) = QColor.fromRgba(mk2.pixel(x, y)).getRgbF()
                            r = r * cr
                            g = g * cg
                            b = b * cb
                            mk2.setPixel(x, y,
                                         QColor.fromRgbF(r, g, b, a).rgba())
                mk2 = mk2.scaledToHeight(mkh, 1)
                painter.drawImage(pt.x - mkh / 2, pt.y - mkh / 2, mk2)

        painter.end()

        self.wmk.setPixmap(self.mkpixmap)
Beispiel #21
0
 def updateTerritoryOwner(self, name, owner):
     t = self.game.board.getTerritory(name)
     p = self.game.getPlayer(owner)
     color = QColor(*p.color)
     color.setAlpha(200)
     territoryImage = QImage(t.image.size(), QImage.Format_ARGB32_Premultiplied)
     p = QPainter()
     p.begin(territoryImage)
     p.drawImage(0, 0, self.game.board.image)
     p.setCompositionMode(QPainter.CompositionMode_DestinationIn)
     p.drawImage(0, 0, t.image)
     p.end()
     coloredTerritoryImage = QImage(territoryImage.size(), QImage.Format_ARGB32_Premultiplied)
     coloredTerritoryImage.fill(0)
     p.begin(coloredTerritoryImage)
     p.fillRect(territoryImage.rect(), color)
     p.setCompositionMode(QPainter.CompositionMode_DestinationIn)
     p.drawImage(0, 0, t.image)
     p.end()
     p.begin(self.ownershipMap)
     p.drawImage(0, 0, territoryImage)
     p.drawImage(0, 0, coloredTerritoryImage)
     p.end()
     self.scaledOwnershipMap = self.ownershipMap.scaled(self.imageSize())
     self.update()
Beispiel #22
0
    def print_(self):
        """Prints the document."""
        self._stop = False
        resolution = self.resolution()
        p = self.printer()
        p.setFullPage(True)
        p.setResolution(resolution)

        center = p.paperRect().center()
        painter = QPainter(p)

        pages = self.pageList()
        if p.pageOrder() != QPrinter.FirstPageFirst:
            pages.reverse()

        total = len(pages)

        opts = self.renderOptions()
        document = self.document()

        for num, pageNum in enumerate(pages, 1):
            if self._stop:
                return p.abort()
            self.progress(num, total, pageNum)
            if num > 1:
                p.newPage()
            with lock(document):
                opts.write(document)
                page = document.page(pageNum - 1)
                img = page.renderToImage(resolution, resolution)
            rect = img.rect()
            rect.moveCenter(center)
            painter.drawImage(rect, img)

        return painter.end()
Beispiel #23
0
 def convert(self, event):
     node = event.config.node
     buff = ""
     if str(node.dataType()).find("video") != -1:
         if VIDEO_API_EXISTS:
             try:
                 md = video.VideoDecoder(node)
                 if event.config.frames == 1:
                     img = md.thumbnailAtPercent(event.config.percent, event.config.size)
                 else:
                     img = QImage(event.config.size * event.config.frames / 2, event.config.size * 2, 4)
                     img.fill(0)
                     painter = QPainter(img)
                     for y in range(0, 2):
                         try:
                             for x in range(1, event.config.frames / 2 + 1):
                                 try:
                                     frame = md.thumbnailAtPercent(
                                         (x + ((event.config.frames / 2) * y)) * (100 / event.config.frames),
                                         event.config.size,
                                     )
                                     painter.drawImage((x - 1) * event.config.size, y * event.config.size, frame)
                                 except RuntimeError, e:
                                     raise e
                         except RuntimeError:
                             break
                     painter.end()
                 self.emit(SIGNAL("scaledFinished"), event.config, img)
                 return
             except:
                 pass
         self.emit(SIGNAL("scaledFinished"), event.config, None)
         return
     img = QImage()
     load = None
     buff = ""
     if str(node.dataType()).find("jpeg") != -1 and node.size() < self.imageMaximumSize:
         try:
             buff = self.jpegInternalThumbnail(node)
             if buff:
                 load = img.loadFromData(buff, "jpeg")
                 if load == False:
                     buff = ""
         except IOError:
             buff = ""
     if not len(buff) and node.size() < self.imageMaximumSize:
         try:
             f = node.open()
             buff = f.read()
             f.close()
             load = img.loadFromData(buff)
         except IOError:
             load = False
     if load:
         img = img.scaled(QSize(event.config.size, event.config.size), Qt.KeepAspectRatio, Qt.FastTransformation)
         self.emit(SIGNAL("scaledFinished"), event.config, img)
         return
     self.emit(SIGNAL("scaledFinished"), event.config, None)
     return
    def updateSlice(self):
        if self.ctslice_rgba is None:
            return

        img = self.ctslice_rgba.copy()

        # if self.seeds is not None:
        #     if self.mode_draw:
        #         if self.contour_mode == 'fill':
        #             self.composeRgba(img, self.seeds,
        #                              self.seeds_colortable)
        #         elif self.contour_mode == 'contours':
        #             self.get_contours(img, self.seeds)
        #     else:
        #         self.overRgba(img, self.seeds,
        #                       self.seeds_colortable)

        if self.contours is not None:
            # if self.contour_mode == 'fill':
            if self.contours_mode_is_fill:
                self.composeRgba(img, self.contours.transpose().ravel(order="F"), CONTOURS_COLORTABLE)
            # elif self.contour_mode == 'contours':
            else:
                self.get_contours(img, self.contours)

        # masking out pixels under circle
        # for i in self.circle_m:
        #     img[i, :] = [0, 0, 255, 255]

        image = QImage(img.flatten(), self.slice_size[0], self.slice_size[1], QImage.Format_ARGB32).scaled(
            self.imagesize
        )
        painter = QPainter(self.image)
        painter.drawImage(0, 0, image)

        if self.show_mode == self.SHOW_CONTOURS:  # and self.centers is not None:
            if self.centers is not None:
                pts = self.centers.nonzero()
                pen = QPen(Qt.red, 3)
                painter.setPen(pen)
                for i in range(len(pts[0])):
                    painter.drawPoint(pts[1][i] * self.grid[0], pts[0][i] * self.grid[1])

        if self.circle_active:
            pen = QPen(Qt.red, 3)
            painter.setPen(pen)
            center_offset = 0  # 0.5
            radius_offset = 0  # 0.5
            painter.drawEllipse(
                QPoint(
                    (self.mouse_cursor[0] + center_offset) * self.grid[0],
                    (self.mouse_cursor[1] + center_offset) * self.grid[1],
                ),
                (self.circle_r + radius_offset) * self.grid[0],
                (self.circle_r + radius_offset) * self.grid[1],
            )
        painter.end()

        self.update()
Beispiel #25
0
    def updateSlice(self):
        if self.ctslice_rgba is None:
            return

        img = self.ctslice_rgba.copy()

        # if self.seeds is not None:
        #     if self.mode_draw:
        #         if self.contour_mode == 'fill':
        #             self.composeRgba(img, self.seeds,
        #                              self.seeds_colortable)
        #         elif self.contour_mode == 'contours':
        #             self.get_contours(img, self.seeds)
        #     else:
        #         self.overRgba(img, self.seeds,
        #                       self.seeds_colortable)

        if self.contours is not None:
            # if self.contour_mode == 'fill':
            if self.contours_mode_is_fill:
                self.composeRgba(img,
                                 self.contours.transpose().ravel(order='F'),
                                 CONTOURS_COLORTABLE)
            # elif self.contour_mode == 'contours':
            else:
                self.get_contours(img, self.contours)

        # masking out pixels under circle
        # for i in self.circle_m:
        #     img[i, :] = [0, 0, 255, 255]

        image = QImage(img.flatten(), self.slice_size[0], self.slice_size[1],
                       QImage.Format_ARGB32).scaled(self.imagesize)
        painter = QPainter(self.image)
        painter.drawImage(0, 0, image)

        if self.show_mode == self.SHOW_CONTOURS:  # and self.centers is not None:
            if self.centers is not None:
                pts = self.centers.nonzero()
                pen = QPen(Qt.red, 3)
                painter.setPen(pen)
                for i in range(len(pts[0])):
                    painter.drawPoint(pts[1][i] * self.grid[0],
                                      pts[0][i] * self.grid[1])

        if self.circle_active:
            pen = QPen(Qt.red, 3)
            painter.setPen(pen)
            center_offset = 0  #0.5
            radius_offset = 0  #0.5
            painter.drawEllipse(
                QPoint((self.mouse_cursor[0] + center_offset) * self.grid[0],
                       (self.mouse_cursor[1] + center_offset) * self.grid[1]),
                (self.circle_r + radius_offset) * self.grid[0],
                (self.circle_r + radius_offset) * self.grid[1])
        painter.end()

        self.update()
Beispiel #26
0
    def _blendTile(self, stack_id, tile_nr):
        """
        Blend all of the QImage layers of the patch
        specified by (stack_id, tile_nr) into a single QImage.
        """
        qimg = None
        p = None
        for i, (visible, layerOpacity,
                layerImageSource) in enumerate(reversed(self._sims)):
            image_type = layerImageSource.image_type()
            if issubclass(image_type, QGraphicsItem):
                with self._cache:
                    patch = self._cache.layer(stack_id, layerImageSource,
                                              tile_nr)
                if patch is not None:
                    assert isinstance(patch, image_type), \
                        "This ImageSource is producing a type of image that is not consistent with it's declared image_type()"
                    # This is a QGraphicsItem, so we don't blend it into the final tile.
                    # (The ImageScene will just draw it on top of everything.)
                    # But this is a convenient place to update the opacity/visible state.
                    if patch.opacity() != layerOpacity or patch.isVisible(
                    ) != visible:
                        patch.setOpacity(layerOpacity)
                        patch.setVisible(visible)
                    patch.setZValue(
                        i
                    )  # The sims ("stacked image sources") are ordered from
                    # top-to-bottom (see imagepump.py), but in Qt,
                    # higher Z-values are shown on top.
                    # Note that the current loop is iterating in reverse order.
                continue

            # No need to fetch non-visible image tiles.
            if not visible or layerOpacity == 0.0:
                continue

            with self._cache:
                patch = self._cache.layer(stack_id, layerImageSource, tile_nr)

            # patch might be a QGraphicsItem instead of QImage,
            # in which case it is handled separately,
            # not composited into the tile.

            if patch is not None:
                assert isinstance(patch, QImage), \
                    "Unknown tile layer type: {}. Expected QImage or QGraphicsItem".format(type(patch))
                if qimg is None:
                    qimg = QImage(self.tiling.imageRects[tile_nr].size(),
                                  QImage.Format_ARGB32_Premultiplied)
                    qimg.fill(0xffffffff)  # Use a hex constant instead.
                    p = QPainter(qimg)
                p.setOpacity(layerOpacity)
                p.drawImage(0, 0, patch)

        if p is not None:
            p.end()

        return qimg
Beispiel #27
0
def saveSprites(folder, sprites):
    if sprites:
        height = max([s.height() for s, s2x in sprites.values()])
        width = sum([s.width() for s, s2x in sprites.values()])
        img = QImage(width, height, QImage.Format_ARGB32)
        img.fill(QColor(Qt.transparent))
        img2x = QImage(width * 2, height * 2, QImage.Format_ARGB32)
        img2x.fill(QColor(Qt.transparent))
        painter = QPainter(img)
        painter.begin(img)
        painter2x = QPainter(img2x)
        painter2x.begin(img2x)
        spritesheet = {
            NO_ICON: {
                "width": 0,
                "height": 0,
                "x": 0,
                "y": 0,
                "pixelRatio": 1
            }
        }
        spritesheet2x = {
            NO_ICON: {
                "width": 0,
                "height": 0,
                "x": 0,
                "y": 0,
                "pixelRatio": 1
            }
        }
        x = 0
        for name, sprites in sprites.iteritems():
            s, s2x = sprites
            painter.drawImage(x, 0, s)
            painter2x.drawImage(x * 2, 0, s2x)
            spritesheet[name] = {
                "width": s.width(),
                "height": s.height(),
                "x": x,
                "y": 0,
                "pixelRatio": 1
            }
            spritesheet2x[name] = {
                "width": s2x.width(),
                "height": s2x.height(),
                "x": x * 2,
                "y": 0,
                "pixelRatio": 2
            }
            x += s.width()
        painter.end()
        painter2x.end()
        img.save(os.path.join(folder, "spriteSheet.png"))
        img2x.save(os.path.join(folder, "*****@*****.**"))
        with open(os.path.join(folder, "spriteSheet.json"), 'w') as f:
            json.dump(spritesheet, f)
        with open(os.path.join(folder, "*****@*****.**"), 'w') as f:
            json.dump(spritesheet2x, f)
Beispiel #28
0
    def paintEvent(self, event):
        super(DetailedProgress, self).paintEvent(event)
        if not self._current_progress:
            return

        painter = QPainter(self)
        width = self.width()
        height = self.height()
        aspect_ratio = float(width) / height
        nr_realizations = max([iens
                               for iens, _, _ in self._current_progress]) + 1
        fm_size = max(
            [len(progress) for _, progress, _ in self._current_progress])
        self.grid_height = math.ceil(math.sqrt(nr_realizations / aspect_ratio))
        self.grid_width = math.ceil(self.grid_height * aspect_ratio)
        sub_grid_size = math.ceil(math.sqrt(fm_size))
        cell_height = height / self.grid_height
        cell_width = width / self.grid_width

        foreground_image = QImage(self.grid_width * sub_grid_size,
                                  self.grid_height * sub_grid_size,
                                  QImage.Format_ARGB32)
        foreground_image.fill(QColor(0, 0, 0, 0))

        for index, (iens, progress, _) in enumerate(self._current_progress):
            y = int(iens / self.grid_width)
            x = int(iens - (y * self.grid_width))
            self.draw_window(x * sub_grid_size, y * sub_grid_size, progress,
                             foreground_image)
        painter.drawImage(self.contentsRect(), foreground_image)

        for index, (iens, progress,
                    state) in enumerate(self._current_progress):
            y = int(iens / self.grid_width)
            x = int(iens - (y * self.grid_width))

            painter.setPen(QColor(80, 80, 80))
            painter.drawText(x * cell_width, y * cell_height, cell_width,
                             cell_height, Qt.AlignHCenter | Qt.AlignVCenter,
                             str(iens))

            if iens == self.selected_realization:
                pen = QPen(QColor(240, 240, 240))
            elif (self.has_realization_failed(progress)):
                pen = QPen(QColor(*self.state_colors['Failure']))
            elif (state == JobStatusType.JOB_QUEUE_RUNNING):
                pen = QPen(QColor(*self.state_colors['Running']))
            else:
                pen = QPen(QColor(80, 80, 80))

            thickness = 4
            pen.setWidth(thickness)
            painter.setPen(pen)
            painter.drawRect((x * cell_width) + (thickness / 2),
                             (y * cell_height) + (thickness / 2),
                             cell_width - (thickness - 1),
                             cell_height - (thickness - 1))
Beispiel #29
0
 def _do_paint_rgb24(self, img_data, x, y, width, height, rowstride,
                     options, callbacks):
     image = QImage(img_data, width, height, rowstride,
                    QImage.Format_RGB888)
     pe = QPainter(self._backing)
     rect = QRectF(x, y, width, height)
     src = QRectF(0, 0, width, height)
     pe.drawImage(rect, image, src)
     return True
Beispiel #30
0
def _safeQImageCopy(source, rect):
    '''A modified version of QImage::copy, which avoids rendering errors even if rect is outside the bounds of the source image.'''
    targetRect = QRect(QPoint(), rect.size())
    # copy image
    target = QImage(rect.size(), source.format())
    p = QPainter(target)
    p.drawImage(targetRect, source, rect)
    p.end()
    return target
Beispiel #31
0
 def paintEvent(self, event):
     if not self.image: return
     p = QPainter(self)
     ers, sorig = event.rect().size(), self.image.size()
     img_scaled = self.image.scaled(ers, Qt.KeepAspectRatio)
     p.drawImage(QPoint(0, 0), img_scaled)
     p.setRenderHint(QPainter.Antialiasing)
     p.setPen(Qt.green)
     p.drawText(50, 50, self.filename)
    def _runImpl(self):

        processed = set()
        self._dataPending.wait()
        if self._numLayers == 0:
            return
        bbox = QRect()
        toUpdate = numpy.zeros((len(self._tiling),), dtype=numpy.uint8)
        while len(self._queue) > 0:
            self._dataPending.clear()

            layerNr, patchNr, image, tiling, numLayers = self._queue.popleft()
            if tiling != self._tiling or numLayers != self._numLayers:
                continue            
            if (layerNr, patchNr) in processed:
                continue
            processed.add((layerNr, patchNr))

            rect = self._tiling._imageRect[patchNr]
            bbox = bbox.united(rect)

            self._imageLayersNext[layerNr,patchNr] = image
            toUpdate[patchNr] = 1


        firstOpaqueLayer = 1000000000000000000
        for i, (visible, layerOpacity, layerImageSource) in enumerate(self._stackedIms):
            if visible and layerOpacity == 1.0 and layerImageSource.isOpaque():
                firstOpaqueLayer = i
                break

        for patchNr in toUpdate.nonzero()[0]: 
            self._compositeNext[patchNr] = QImage(self._tiling._imageRect[patchNr].size(), QImage.Format_ARGB32_Premultiplied)
            self._compositeNext[patchNr].fill(Qt.white)
            p = QPainter(self._compositeNext[patchNr])

            for i, v in enumerate(reversed(self._stackedIms)):
                visible, layerOpacity, layerImageSource = v
                if not visible:
                    continue

                layerNr = len(self._stackedIms) - i - 1
                if layerNr > firstOpaqueLayer:
                    continue

                patch = self._imageLayersNext[layerNr, patchNr]
                p.setOpacity(layerOpacity)
                if patch is not None:
                    p.drawImage(0,0, patch)
            p.end()

        w = numpy.equal(self._compositeNext, None)
        self._compositeCurrent = numpy.where(numpy.equal(self._compositeNext, None), self._compositeCurrent, self._compositeNext)
        self._compositeNext[:] = None

        self.patchAvailable.emit(bbox)
Beispiel #33
0
 def paintEvent(self, event):
     painter = QPainter(self)
     if self.border:
         size = self.size()
         painter.setPen(Colors.eyegrade_blue)
         painter.drawRoundedRect(0, 0, size.width() - 2, size.height() - 2,
                                 10, 10)
         painter.drawImage(5, 5, self.image)
     else:
         painter.drawImage(event.rect(), self.image)
        def paintEvent(event):
            painter = QPainter(self.label_image)

            painter.setRenderHint(QPainter.SmoothPixmapTransform, True)

            w = self.label_image.size().width()
            h = self.label_image.size().height()

            painter.scale(w / 80.0, h / 60.0)
            painter.drawImage(0, 0, self.image)

            if 35 != None and 45 != None:
                pen = QPen()
                pen.setColor(Qt.white)
                pen.setWidth(0.2)
                painter.setPen(pen)

                from_x, from_y, to_x, to_y = [35, 25, 45, 35]

                from_x = from_x * self.image_pixel_width + 1
                from_y = from_y * self.image_pixel_width + 1
                to_x = to_x * self.image_pixel_width + 1
                to_y = to_y * self.image_pixel_width + 1

                cross_x = from_x + (to_x - from_x) / 2.0
                cross_y = from_y + (to_y - from_y) / 2.0

                if to_x - from_x > 5 or to_y - from_y > 5:
                    lines = [
                        QLine(from_x, from_y, from_x + self.crosshair_width,
                              from_y),
                        QLine(from_x, from_y, from_x,
                              from_y + self.crosshair_width),
                        QLine(to_x, to_y, to_x, to_y - self.crosshair_width),
                        QLine(to_x, to_y, to_x - self.crosshair_width, to_y),
                        QLine(from_x, to_y, from_x,
                              to_y - self.crosshair_width),
                        QLine(from_x, to_y, from_x + self.crosshair_width,
                              to_y),
                        QLine(to_x, from_y, to_x,
                              from_y + self.crosshair_width),
                        QLine(to_x, from_y, to_x - self.crosshair_width,
                              from_y)
                    ]
                    painter.drawLines(lines)

                lines = [
                    QLine(cross_x - self.crosshair_width, cross_y,
                          cross_x + self.crosshair_width, cross_y),
                    QLine(cross_x, cross_y - self.crosshair_width, cross_x,
                          cross_y + self.crosshair_width)
                ]
                painter.drawLines(lines)

            self.update_spotmeter_roi_label()
Beispiel #35
0
 def paintEvent(self, ev):
     image = self.viewer.image()
     painter = QPainter(self)
     if self.size() == image.size():
         painter.drawImage(ev.rect(), image, ev.rect())
     else:
         s = image.size()
         s.scale(self.size(), Qt.KeepAspectRatio)
         r = QRect()
         r.setSize(s)
         r.moveCenter(self.rect().center())
         painter.drawPixmap(r, self.viewer.pixmap(s))
Beispiel #36
0
    def mousePressEvent(self, e):
        if self.piece:
            if e.button() == Qt.LeftButton:
                p = QPainter(self.pieces)
                p.drawImage(QPoint((self.x-2)*51, (self.y-2)*51), self.piece.getImage())
                self.update()
                self.dropedSignal.emit(self.piece.color, self.piece.shape)
                self.piece = None

            elif e.button() == Qt.RightButton:
                self.piece.flip()
                self.update()
Beispiel #37
0
 def paintEvent(self, ev):
     image = self.viewer.image()
     painter = QPainter(self)
     if self.size() == image.size():
         painter.drawImage(ev.rect(), image, ev.rect())
     else:
         s = image.size()
         s.scale(self.size(), Qt.KeepAspectRatio)
         r = QRect()
         r.setSize(s)
         r.moveCenter(self.rect().center())
         painter.drawPixmap(r, self.viewer.pixmap(s))
Beispiel #38
0
    def _blendTile( self, stack_id, tile_nr): 
        """
        Blend all of the QImage layers of the patch
        specified by (stack_id, tile_nr) into a single QImage.
        """
        qimg = None
        p = None
        for i, (visible, layerOpacity, layerImageSource) in enumerate(reversed(self._sims)):
            image_type = layerImageSource.image_type()
            if issubclass(image_type, QGraphicsItem):
                with self._cache:
                    patch = self._cache.layer(stack_id, layerImageSource, tile_nr )
                if patch is not None:
                    assert isinstance(patch, image_type), \
                        "This ImageSource is producing a type of image that is not consistent with it's declared image_type()"
                    # This is a QGraphicsItem, so we don't blend it into the final tile.
                    # (The ImageScene will just draw it on top of everything.)
                    # But this is a convenient place to update the opacity/visible state.
                    if patch.opacity() != layerOpacity or patch.isVisible() != visible:
                        patch.setOpacity(layerOpacity)
                        patch.setVisible(visible)
                    patch.setZValue(i)  # The sims ("stacked image sources") are ordered from 
                                        # top-to-bottom (see imagepump.py), but in Qt,
                                        # higher Z-values are shown on top.
                                        # Note that the current loop is iterating in reverse order.
                continue

            # No need to fetch non-visible image tiles.
            if not visible or layerOpacity == 0.0:
                continue

            with self._cache:
                patch = self._cache.layer(stack_id, layerImageSource, tile_nr )
            
            # patch might be a QGraphicsItem instead of QImage,
            # in which case it is handled separately,
            # not composited into the tile.

            if patch is not None:
                assert isinstance(patch, QImage), \
                    "Unknown tile layer type: {}. Expected QImage or QGraphicsItem".format(type(patch))
                if qimg is None:
                    qimg = QImage(self.tiling.imageRects[tile_nr].size(), QImage.Format_ARGB32_Premultiplied)
                    qimg.fill(0xffffffff) # Use a hex constant instead.
                    p = QPainter(qimg)
                p.setOpacity(layerOpacity)
                p.drawImage(0,0, patch)
        
        if p is not None:
            p.end()

        return qimg
Beispiel #39
0
 def on_actionPrint_triggered(self):
     if self.printer is None:
         self.printer = QPrinter(QPrinter.HighResolution)
         self.printer.setPageSize(QPrinter.Letter)
     form = QPrintDialog(self.printer, self)
     if form.exec_():
         painter = QPainter(self.printer)
         rect = painter.viewport()
         size = self.image.size()
         size.scale(rect.size(), Qt.KeepAspectRatio)
         painter.setViewport(rect.x(), rect.y(), size.width(),
                             size.height())
         painter.drawImage(0, 0, self.image)
Beispiel #40
0
    def paintEvent(self, event):
        if self.isBlanked:
            return

        img = self.getImage(self.currentPage)
        if img is None:
            return

        x = (self.frameSize().width() - img.width())/2
        y = (self.frameSize().height() - img.height())/2

        painter = QPainter(self)
        painter.drawImage(x, y, img, 0, 0, 0, 0)
Beispiel #41
0
 def wait(self):
     array_data = self._arrayreq.wait()
     rectf = self.rectf
     if array_data.handedness_switched: # array_data should be of type slicingtools.ProjectedArray
         rectf = QRectF(rectf.height(), rectf.width())
     
     from PyQt4.QtGui import QPainter
     img = QImage( QSize( self.rectf.width(), self.rectf.height() ), QImage.Format_ARGB32_Premultiplied)
     img.fill(0xffffffff)
     p = QPainter(img)
     p.drawImage(0,0, img)
     DummyItem(self.rectf).paint(p, None)
     return img
Beispiel #42
0
 def wait(self):
     array_data = self._arrayreq.wait()
     rectf = self.rectf
     if array_data.handedness_switched: # array_data should be of type slicingtools.ProjectedArray
         rectf = QRectF(rectf.height(), rectf.width())
     
     from PyQt4.QtGui import QPainter
     img = QImage( QSize( self.rectf.width(), self.rectf.height() ), QImage.Format_ARGB32_Premultiplied)
     img.fill(0xffffffff)
     p = QPainter(img)
     p.drawImage(0,0, img)
     DummyItem(self.rectf).paint(p, None)
     return img
Beispiel #43
0
def convert_pic_umi(filename, out_file):
    data = ConstBitStream(filename=filename)

    magic = data.read("bytes:4")
    size = data.read("uintle:32")
    ew = data.read("uintle:16")
    eh = data.read("uintle:16")
    width = data.read("uintle:16")
    height = data.read("uintle:16")

    unk1 = data.read("uintle:32")
    chunks = data.read("uintle:32")

    image = QImage(width, height, QImage.Format_ARGB32)
    image.fill(0)
    painter = QPainter(image)

    for i in range(chunks):
        version = data.read("uintle:32")
        x = data.read("uintle:16")
        y = data.read("uintle:16")
        w = data.read("uintle:16")
        h = data.read("uintle:16")

        offset = data.read("uintle:32")
        size = data.read("uintle:32")

        # if not i == 1:
        # continue

        print w, h, size, offset

        temp_pos = data.bytepos
        data.bytepos = offset
        chunk = data.read(size * 8)
        data.bytepos = temp_pos

        chunk = decompress_umi(chunk)
        chunk = adjust_scanline(chunk, w, h)
        dump_to_file(chunk)
        chunk = QImage(chunk, w, h, QImage.Format_ARGB32)
        chunk.fill(0)
        # chunk.save("test.bmp")
        painter.drawImage(QRectF(x, y, w, h), chunk, QRectF((chunk.rect())))
        # break

    painter.end()
    image.save(out_file)


################################################################################
 def paintEvent(self, event):
     if not self.resources:
         return
     paint = QPainter(self)
     for e in self.resources.edges:
             if e == self.selectedEdge:
                 paint.setPen(self.colors["selected"])
             else:
                 paint.setPen(self.colors["line"])
             self.drawArrow(paint, self.vertices[e.e1].x() + self.size / 2, self.vertices[e.e1].y() + self.size / 2,
                          self.vertices[e.e2].x() + self.size / 2, self.vertices[e.e2].y() + self.size / 2)
     for v in self.vertices.keys():
         pen = paint.pen()
         paint.setPen(Qt.red)
         if self.selectedVertex == self.vertices[v]:
             paint.drawRect(self.vertices[v])
         if isinstance(v, VM):
             paint.drawImage(self.vertices[v], self.computericon)
         elif isinstance(v, Storage):
             paint.drawImage(self.vertices[v], self.storageicon)
         elif isinstance(v, NetElement):
             if v.router:
                 paint.drawImage(self.vertices[v], self.routericon)
             else:
                 paint.drawImage(self.vertices[v], self.switchicon)
     paint.setPen(self.colors["line"])
     if self.edgeDraw:
         self.drawArrow(paint, self.curEdge[0].x() + self.size / 2, self.curEdge[0].y() + self.size / 2,
                        QCursor.pos().x() - self.mapToGlobal(self.geometry().topLeft()).x(),
                        QCursor.pos().y() - self.mapToGlobal(self.geometry().topLeft()).y())
     paint.end()
Beispiel #45
0
 def paintEvent(self, event):
     if not self.demand:
         return
     paint = QPainter(self)
     for e in self.demand.edges:
             if e == self.selectedEdge:
                 paint.setPen(self.colors["selected"])
             else:
                 paint.setPen(self.colors["line"])
             self.drawArrow(paint, self.vertices[e.e1].x() + self.size / 2, self.vertices[e.e1].y() + self.size / 2,
                          self.vertices[e.e2].x() + self.size / 2, self.vertices[e.e2].y() + self.size / 2)
     for v in self.vertices.keys():
         if isinstance(v,VM):
             if self.selectedVertex != self.vertices[v]:
                 paint.drawImage(self.vertices[v], self.computericon)
             else:
                 paint.drawImage(self.vertices[v], self.computerselectedicon)
         elif isinstance(v,DemandStorage):
             if self.selectedVertex != self.vertices[v]:
                 paint.drawImage(self.vertices[v], self.storageicon)
             else:
                 paint.drawImage(self.vertices[v], self.storageselectedicon)
     paint.setPen(self.colors["line"])
     if self.edgeDraw:
         self.drawArrow(paint, self.curEdge[0].x() + self.size / 2, self.curEdge[0].y() + self.size / 2,
                        QCursor.pos().x() - self.mapToGlobal(self.geometry().topLeft()).x(),
                        QCursor.pos().y() - self.mapToGlobal(self.geometry().topLeft()).y())
     paint.end()
Beispiel #46
0
 def paintEvent(self, event):
     """
     Draw the QImage on screen.
     """
     textPosX,textPosY = 10,200
     painter = QPainter(self)
     painter.drawImage(painter.viewport(), self._image)
     innerFont = QFont()
     innerFont.setPointSize(12)
     painter.setFont(innerFont)
     painter.setPen(QColor(QtCore.Qt.white))
     painter.drawText(10,180,'Current Action:')
     painter.drawText(10,200,self._currentMovement)
     self.drawMoreText(painter,10,300,['Control Buttons:',
     'w,s - Walking Forwards/Backwards',
     'q,e - Walking Left/Right',
     'a,d - Turning Left/Right',
     'x - stopping',
     'Space - standing up',
     'Ctrl - crouch',
     'Escape,Enter - restMode, wakeUp',
     '1 - Grabbing small',
     '2 - Grabbing large',
     '3 - Grabbing Kuscheltier',
     '4 - Grabbing bottle'])
     self.drawMoreText(painter,self.width()-300-25,300,['Dialog Control:({})'.format(self._attitude),
     'u - Introduction',
     'i - Ask for object',
     'h - Object is Somat',
     'j - Object is Muesli',
     'k - Object is Bottle',
     'l - Object is Kuscheltier',
     'n - Wertstoff',
     'm - Altpapier', 
     'o - Ask for help',
     'z - Ask proband to repeat sentence',
     'p - Repeat task',
     '0(Null) - construct initial state',
     't - Goodbye',
     'b - thanks',
     '# - Start free Speech(PopUp)'])
     self.drawMoreText(painter,100,50,['Movement Speeds','Forward: {}'.format(self._currentSpeeds['Forward']),'Leftward: {}'.format(self._currentSpeeds['Leftward']),'CounterClockwise: {}'.format(self._currentSpeeds['CounterClockwise'])])
     pen = QPen()
     pen.setColor(QColor(QtCore.Qt.red))
     pen.setWidth(5)
     painter.setPen(pen)
     painter.drawEllipse(20,15,60,30)
     pen.setColor(QColor(QtCore.Qt.blue))
     painter.setPen(pen)
     painter.drawPolygon(self.rotatePolygon(arrowPolygon,math.degrees(self._motionProxy.getAngles('HeadYaw',True)[0]),[30,20]))
def get_trial(scene_info, show_bg = True, show_sprite = True, show_box = True):
  
  case_num = scene_info.chapter
  sprite_id = scene_info.sprite
  
  if case_num > 6 or case_num <= 0:
    case_num = 1
  
  out = None
  
  if show_bg:
    if scene_info.movie >= 0:
      out = get_movie(scene_info.movie)
    elif scene_info.flash >= 0:
      out = get_flash(scene_info.flash)
    elif scene_info.bgd >= 0:
      out = get_bgd(scene_info.bgd)
    else:
      # out = QImage(os.path.join(BG_DIR, "bg_%03d.png" % (199 + case_num)))
      out = get_bg(199 + case_num)
  else:
    out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
    out.fill(QColor(0, 0, 0, 0).rgba())
  
  if not out.format() is QImage.Format_ARGB32_Premultiplied:
    out = out.convertToFormat(QImage.Format_ARGB32_Premultiplied)
  
  painter = QPainter(out)
  painter.setRenderHint(QPainter.Antialiasing, True)
  
  if show_sprite:
    sprite_id.sprite_type = SPRITE_TYPE.stand
    
    sprite = get_sprite(sprite_id)
    if sprite:
      painter.drawImage(out.rect(), sprite, sprite.rect())
  
  if not scene_info.img_filter == IMG_FILTERS.unfiltered:
    painter.end()
    out = filter_image(out, scene_info.img_filter)
    painter = QPainter(out)
    painter.setRenderHint(QPainter.Antialiasing, True)
  
  if show_box:
  
    box = get_box(scene_info)
    painter.drawImage(out.rect(), box, box.rect())
  
  return out
def get_trial(scene_info, show_bg=True, show_sprite=True, show_box=True):

    case_num = scene_info.chapter
    sprite_id = scene_info.sprite

    if case_num > 6 or case_num <= 0:
        case_num = 1

    out = None

    if show_bg:
        if scene_info.movie >= 0:
            out = get_movie(scene_info.movie)
        elif scene_info.flash >= 0:
            out = get_flash(scene_info.flash)
        elif scene_info.bgd >= 0:
            out = get_bgd(scene_info.bgd)
        else:
            # out = QImage(os.path.join(BG_DIR, "bg_%03d.png" % (199 + case_num)))
            out = get_bg(199 + case_num)
    else:
        out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied)
        out.fill(QColor(0, 0, 0, 0).rgba())

    if not out.format() is QImage.Format_ARGB32_Premultiplied:
        out = out.convertToFormat(QImage.Format_ARGB32_Premultiplied)

    painter = QPainter(out)
    painter.setRenderHint(QPainter.Antialiasing, True)

    if show_sprite:
        sprite_id.sprite_type = SPRITE_TYPE.stand

        sprite = get_sprite(sprite_id)
        if sprite:
            painter.drawImage(out.rect(), sprite, sprite.rect())

    if not scene_info.img_filter == IMG_FILTERS.unfiltered:
        painter.end()
        out = filter_image(out, scene_info.img_filter)
        painter = QPainter(out)
        painter.setRenderHint(QPainter.Antialiasing, True)

    if show_box:

        box = get_box(scene_info)
        painter.drawImage(out.rect(), box, box.rect())

    return out
    def paintEvent(self, event):
        """ When there is more space then necessary, display the image centered
        on a black background, surrounded by a light gray border """
        QWidget.paintEvent(self, event)
        qp = QPainter(self)
        qp.fillRect(self.rect(), Qt.black)
        image = self.buffer.qimage

        if image is not None:
            offset = QPoint((self.width() - image.width()) / 2, (self.height() - image.height()) / 2)
            qp.setPen(Qt.lightGray)
            qp.drawRect(QRect(offset - QPoint(1, 1), image.size() + QSize(1, 1)))
            qp.drawImage(offset, image)

        qp.end()
 def filePrint(self):
     if self.image.isNull():
         return
     if self.printer is None:
         self.printer = QPrinter(QPrinter.HighResolution)
         self.printer.setPageSize(QPrinter.Letter)
     form = QPrintDialog(self.printer, self)
     if form.exec_():
         painter = QPainter(self.printer)
         rect = painter.viewport()
         size = self.image.size()
         size.scale(rect.size(), Qt.KeepAspectRatio)
         painter.setViewport(rect.x(), rect.y(), size.width(),
                             size.height())
         painter.drawImage(0, 0, self.image)
def replace_all_colors(image, color):
  
  new_img = image.copy()
  
  if not new_img.format() is QImage.Format_ARGB32_Premultiplied:
    new_img = new_img.convertToFormat(QImage.Format_ARGB32_Premultiplied)
  
  color_img = QImage(new_img.width(), new_img.height(), QImage.Format_ARGB32_Premultiplied)
  color_img.fill(color.rgba())
  
  painter = QPainter(new_img)
  painter.setCompositionMode(QPainter.CompositionMode_SourceAtop)
  painter.drawImage(new_img.rect(), color_img, color_img.rect())
  painter.end()
  
  return new_img
Beispiel #52
0
    def _renderTile( self, stack_id, tile_nr ):
        qimg = QImage(self.tiling.imageRects[tile_nr].size(), QImage.Format_ARGB32_Premultiplied)
        qimg.fill(Qt.white)

        p = QPainter(qimg)
        for i, v in enumerate(reversed(self._sims)):
            visible, layerOpacity, layerImageSource = v
            if not visible:
                continue

            patch = self._cache.layer(stack_id, layerImageSource, tile_nr )
            if patch is not None:
                p.setOpacity(layerOpacity)
                p.drawImage(0,0, patch)
        p.end()
        return qimg
def replace_all_colors(image, color):
  
  new_img = image.copy()
  
  if not new_img.format() is QImage.Format_ARGB32_Premultiplied:
    new_img = new_img.convertToFormat(QImage.Format_ARGB32_Premultiplied)
  
  color_img = QImage(new_img.width(), new_img.height(), QImage.Format_ARGB32_Premultiplied)
  color_img.fill(color.rgba())
  
  painter = QPainter(new_img)
  painter.setCompositionMode(QPainter.CompositionMode_SourceAtop)
  painter.drawImage(new_img.rect(), color_img, color_img.rect())
  painter.end()
  
  return new_img
Beispiel #54
0
    def render(self,fname):
      contentsSize = self.contentFrame.contentsSize()
      contentsSize -= QSize(self.m_scrollPosition.x(), self.m_scrollPosition.y())
      frameRect = QRect(QPoint(0, 0), contentsSize)
      #if not self.m_clipRect.isEmpty():
      #    frameRect = self.m_clipRect

      viewportSize = self.contentPage.viewportSize()
      self.contentPage.setViewportSize(contentsSize)

      image = QImage(frameRect.size(), QImage.Format_ARGB32)
      image.fill(qRgba(255, 255, 255, 0))

      painter = QPainter()

      # We use tiling approach to work-around Qt software rasterizer bug
      # when dealing with very large paint device.
      # See http://code.google.com/p/phantomjs/issues/detail?id=54.
      tileSize = 4096
      htiles = (image.width() + tileSize - 1) / tileSize
      vtiles = (image.height() + tileSize - 1) / tileSize
      for x in range(htiles):
          for y in range(vtiles):
              tileBuffer = QImage(tileSize, tileSize, QImage.Format_ARGB32)
              tileBuffer.fill(qRgba(255, 255, 255, 0))

              # Render the web page onto the small tile first
              painter.begin(tileBuffer)
              painter.setRenderHint(QPainter.Antialiasing, True)
              painter.setRenderHint(QPainter.TextAntialiasing, True)
              painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
              painter.translate(-frameRect.left(), -frameRect.top())
              painter.translate(-x * tileSize, -y * tileSize)
              self.contentFrame.render(painter, QRegion(frameRect))
              painter.end()

              # Copy the tile to the main buffer
              painter.begin(image)
              painter.setCompositionMode(QPainter.CompositionMode_Source)
              painter.drawImage(x * tileSize, y * tileSize, tileBuffer)
              painter.end()

      self.contentPage.setViewportSize(viewportSize)

      image.save(fname)

      return True
Beispiel #55
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.fillRect(self.rect(), QColor('#101010'))

        image = self._image

        if image is not None:
            if self.height() < 240:
                fast_scaler = QTransform()
                scale = 297 / image.height()
                if self.mirror:
                    fast_scaler.scale(-scale, scale)
                else:
                    fast_scaler.scale(scale, scale)
                rect = event.rect()
                painter.drawPixmap(
                    rect,
                    QPixmap.fromImage(
                        image.transformed(fast_scaler)).scaledToHeight(
                            self.height(), Qt.SmoothTransformation), rect)
            else:
                transform = QTransform()
                scale = min(self.width() / image.width(),
                            self.height() / image.height())
                if self.mirror:
                    transform.translate(
                        (self.width() + image.width() * scale) / 2,
                        (self.height() - image.height() * scale) / 2)
                    transform.scale(-scale, scale)
                else:
                    transform.translate(
                        (self.width() - image.width() * scale) / 2,
                        (self.height() - image.height() * scale) / 2)
                    transform.scale(scale, scale)

                inverse_transform, invertible = transform.inverted()
                rect = inverse_transform.mapRect(event.rect()).adjusted(
                    -1, -1, 1, 1).intersected(image.rect())

                painter.setTransform(transform)

                if self.height() > 400:
                    painter.drawPixmap(rect, QPixmap.fromImage(image), rect)
                else:
                    painter.drawImage(rect, image, rect)

        painter.end()
Beispiel #56
0
    def image(self):
        width = (self.xmax - self.xmin + 1) * self.TILE_SIZE
        height = (self.ymax - self.ymin + 1) * self.TILE_SIZE
        image = QImage(width, height, QImage.Format_ARGB32_Premultiplied)
        p = QPainter(image)
        for tile in self.tiles.values():
            if not tile.data:
                continue

            x = tile.x - self.xmin
            y = tile.y - self.ymin
            rect = QRect(x * self.TILE_SIZE, y * self.TILE_SIZE, self.TILE_SIZE, self.TILE_SIZE)

            timg = QImage()
            timg.loadFromData(tile.data)
            p.drawImage(rect, timg)
        return image
Beispiel #57
0
    def doubleCacheImage(self, idx, force=None):
        self.cacheImage(idx, force)

        # now we want to add another image to the same layer
        self.cacheImage(idx+1, force)
        painter = QPainter()
        painter.begin(self.pdfImages[idx])
        painter.setOpacity(0.5)

        image2 = self.getImage(idx+1).copy()
        mask = image2.createMaskFromColor(image2.pixel(0, 0), 1)
        image2.setAlphaChannel(mask)

        painter.drawImage(0, 0, image2,
                          sw = self.pdfImages[idx].width()/2,
                          sh = self.pdfImages[idx].height()/2)
        painter.end()
    def image(self):
        width = (self.xmax - self.xmin + 1) * self.TILE_SIZE
        height = (self.ymax - self.ymin + 1) * self.TILE_SIZE
        image = QImage(width, height, QImage.Format_ARGB32_Premultiplied)
        p = QPainter(image)
        for tile in self.tiles.values():
            if not tile.data:
                continue

            x = tile.x - self.xmin
            y = tile.y - self.ymin
            rect = QRect(x * self.TILE_SIZE, y * self.TILE_SIZE, self.TILE_SIZE, self.TILE_SIZE)

            timg = QImage()
            timg.loadFromData(tile.data)
            p.drawImage(rect, timg)
        return image
Beispiel #59
0
 def saveSlice(self, filename):
     """Legacy code."""
     #print "Saving in ", filename, "slice #", self.sliceNumber, "axis", self._axis
     result_image = QImage(self.scene().image.size(), self.scene().image.format())
     p = QPainter(result_image)
     for patchNr in range(self.patchAccessor.patchCount):
         bounds = self.patchAccessor.getPatchBounds(patchNr)
         if self.openglWidget is None:
             p.drawImage(0, 0, self.scene().image)
         else:
             p.drawImage(bounds[0], bounds[2], self.imagePatches[patchNr])
     p.end()
     #horrible way to transpose an image. but it works.
     transform = QTransform()
     transform.rotate(90)
     result_image = result_image.mirrored()
     result_image = result_image.transformed(transform)
     result_image.save(QString(filename))