示例#1
0
 def changeBackground(self):
     filename = QFileDialog.getOpenFileName(self, self.trUtf8("Change Background"), \
         QDesktopServices.storageLocation(QDesktopServices.PicturesLocation), \
         self.trUtf8("Image Files (*.png *.gif *.jpg *.jpeg *.bmp *.mng *ico)"))
     if filename == "":
         return
     image = QImage(filename)
     if image.isNull():
         QMessageBox.information(self, self.trUtf8("Change Background"), \
                 self.trUtf8("不能读取图像文件,请检查文件格式是否正确,或者图片是否已经损坏。"))
         return
     if image.width() < 800 or image.height() < 600:
         answer = QMessageBox.information(self, self.trUtf8("Change Background"), \
                 self.trUtf8("不建议设置小于800x600的图片作为背景图案。如果继续,可能会使快捷面板显示错乱。是否继续?"),
                 QMessageBox.Yes | QMessageBox.No,
                 QMessageBox.No)
         if answer == QMessageBox.No:
             return
     self._makeBackground(image)
     moveToCenter(self)
     self.canvas.positWidgets()
     self.update()
     with self.platform.getSettings() as settings:
         settings.setValue("background", filename)
示例#2
0
    def __init__(self, parent=None):
        super(LegendWidget, self).__init__(parent)
        self.setupUi(self)
        self.canvasimage = QImage()
        self.items = {}
        self.framerect = QRect()

        self.legendareabrush = QBrush(QColor(255, 255, 255, 200))
        self.legendareapen = QPen(QColor(255, 255, 255, 20))
        self.legendareapen.setWidth(0.5)
        self.previewImage.mousePressEvent = self.previewImagePressEvent
        self.previewImage.resizeEvent = self.update
        self.btnExpand.pressed.connect(self.layerTree.expandAllNodes)
        self.btnCollapse.pressed.connect(self.layerTree.collapseAllNodes)
        self.canvas = None
示例#3
0
    def load_document(self, photo_path):
        if photo_path:
            self._ph_image = QImage(photo_path)

            if self._ph_image.isNull():
                return False

            self._photo_path = photo_path

            ph_pixmap = QPixmap.fromImage(self._ph_image)

            self._lbl_photo.setPixmap(ph_pixmap)
            self._scale_factor = 1.0

            self._aspect_ratio = ph_pixmap.width() / ph_pixmap.height()

            self._fit_to_window_act.setEnabled(True)
            self._print_act.setEnabled(True)
            self._fit_to_window_act.trigger()

            self.update_actions()
            return ph_pixmap

        return True
示例#4
0
    def __init__(self, w, h, thermal_image, parent=None):
        super(ThermalImageBar, self).__init__(parent)

        self.setAttribute(Qt.WA_StaticContents)
        self.parent = parent
        self.width = w
        self.height = h
        self.thermal_image = thermal_image

        self.setMaximumSize(w * thermal_image.image_pixel_width, h)
        self.setMinimumSize(w * thermal_image.image_pixel_width, h)

        self.image = QImage(QSize(w * thermal_image.image_pixel_width, h),
                            QImage.Format_RGB32)
        self.update_image()
 def _updateImage(self):
     """
     Retrieve a new image from Nao.
     """
     self._alImage = self.video_service.getImageRemote(self._imgClient)
     self.video_service.setParam(vision_definitions.kCameraSelectID, 2)
     self._alImage3d = self.video_service.getImageRemote(self._imgClient2)
     print len(self._alImage3d[6])
     self.video_service.setParam(vision_definitions.kCameraSelectID, 0)
     print self._alImage3d[0] * self._alImage3d[1]
     self._image = QImage(
         self._alImage[6],  # Pixel array.
         self._alImage[0],  # Width.
         self._alImage[1],  # Height.
         QImage.Format_RGB888)
示例#6
0
def convert_shtx_4bit(data):

    width = to_u16(data[0:2])
    height = to_u16(data[2:4])
    unk = data[4:12]
    p = 12

    palette = []

    for i in range(16):
        palette.append(qRgba(data[p], data[p + 1], data[p + 2], data[p + 3]))
        p += 4

    pixels = data[p:p + (width * height / 2)]
    pixels2 = bytearray()

    for b in pixels:
        pixels2.append(b & 0x0F)
        pixels2.append(b >> 4)

    img = QImage(pixels2, width, height, QImage.Format_Indexed8)
    img.setColorTable(palette)

    return img
    def edit_item(self):
        self.action = "edit"

        if self.listWidgetAlyObj.currentRow() < 0:
            return

        #print self.listWidgetAlyObj.currentRow()

        selected_item_data = self.listWidgetAlyObj.currentItem().data(
            Qt.UserRole).toString()
        self.xml_name = str(selected_item_data)
        #print selected_item_data

        if self.xml_name.endswith("_ObjectFinder.xml"):
            self.hide()
            time.sleep(0.600)
            self.alyvix_finder_controller = AlyvixObjectFinderView(self)
            self.alyvix_finder_controller.show()
            return

        if self.xml_name.endswith("_CustomCode.xml"):
            self.hide()
            time.sleep(0.600)
            self.alyvix_finder_controller = AlyvixCustomCodeView(self)
            self.alyvix_finder_controller.show()
            return

        screen_manager = ScreenManager()
        self.hide()
        time.sleep(0.600)
        img_color = cv2.imread(str(self.xml_name).replace(
            "xml",
            "png"))  #screen_manager.grab_desktop(screen_manager.get_color_mat)
        #print "imgggg", self.path + os.sep + self.xml_name
        image = QImage(self.path + os.sep +
                       self.xml_name.replace("xml", "png"))
        #print self.path, self.robot_file_name, self.xml_name

        if self.xml_name.endswith("_RectFinder.xml"):
            self.alyvix_finder_controller = AlyvixRectFinderView(self)
        elif self.xml_name.endswith("_ImageFinder.xml"):
            self.alyvix_finder_controller = AlyvixImageFinderView(self)
        elif self.xml_name.endswith("_TextFinder.xml"):
            self.alyvix_finder_controller = AlyvixTextFinderView(self)

        #self.alyvix_rect_finder_controller.set_path(self.full_file_name)
        self.alyvix_finder_controller.set_bg_pixmap(image)
        self.alyvix_finder_controller.showFullScreen()
def get_event_icon(file_id):
  
  icon_file = os.path.join(EVENT_DIR, "gallery_icn_%03d.png" % file_id)
  
  if not os.path.isfile(icon_file):
    icon_file = os.path.join(EVENT_DIR, "gallery_icn_%03d.png" % 999)
  
  icon = QImage(icon_file)
  
  x_pos = 35
  y_pos = 80
  
  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, icon.width(), icon.height()), icon, icon.rect())
  
  painter.end()
  
  return out
示例#9
0
文件: io.py 项目: etrushkin/sconcho
def export_scene(canvas, width, height, dpi, exportFileName):
    """ This function exports the scene to a file. """

    # need this to make sure we take away focus from
    # any currently selected legend items
    canvas.clearFocus()

    with HiddenStitchManager(canvas):

        # NOTE: We seem to need the 1px buffer region to avoid
        # the image being cut off
        margin = 10
        theScene = visible_bounding_rect(canvas.items())
        theScene.adjust(-margin, -margin, margin, margin)

        # check if user requested an svg file
        svg = True if QFileInfo(exportFileName).completeSuffix() == "svg" \
                else False

        if svg:
            generator = QSvgGenerator()
            generator.setFileName(exportFileName)
            generator.setSize(QSize(width, height))
            generator.setViewBox(QRect(0, 0, width, height))
            generator.setTitle("sconcho generated SVG image")
            generator.setDescription("this svg image was exported from "
                                     "a sconcho project")
            generator.setResolution(dpi)
        else:
            generator = QImage(width + 2 * margin, height + 2 * margin,
                               QImage.Format_ARGB32_Premultiplied)
            generator.fill(1)

            inchesToMeter = 39.3700787
            generator.setDotsPerMeterX(dpi * inchesToMeter)
            generator.setDotsPerMeterY(dpi * inchesToMeter)

        painter = QPainter(generator)
        painter.setRenderHints(QPainter.SmoothPixmapTransform
                               | QPainter.HighQualityAntialiasing
                               | QPainter.TextAntialiasing)
        painter.setBackgroundMode(Qt.TransparentMode)

        canvas.render(painter, QRectF(), theScene)
        painter.end()

        if not svg:
            generator.save(exportFileName)
示例#10
0
def imageFromPath(path):
    if (path[:7] == 'http://' or path[:8] == 'https://'
            or path[:7] == 'file://'):
        #fetch remote image
        data = urllib2.urlopen(path).read()
        image = QImage()
        image.loadFromData(data)
    else:
        image = QImage(path)
    return image
示例#11
0
文件: mainwindow.py 项目: richli/dame
    def update_image(self, tabname):
        """Refresh the image in the tab.

        tabname can be: "left", "right", "split", "fade"

        """
        if tabname in ("left", "right"):
            logging.info("Refreshing image {}".format(tabname))
            header = self.sir_files[tabname]['header']
            sirdata = self.sir_files[tabname]['data']
            nsx = header.nsx
            nsy = header.nsy
            vmin = self.sir_files[tabname].setdefault('vmin', header.v_min)
            vmax = self.sir_files[tabname].setdefault('vmax', header.v_max)
            anodata = header.anodata
            v_offset = -vmin
            v_scale = 255 / (vmax - vmin)

            # Scale the SIR image to the range of 0,255
            sir_scale = ma.masked_less_equal(sirdata, anodata, copy=True)
            sir_scale += v_offset
            sir_scale *= v_scale
            sir_scale = sir_scale.filled(0)  # all nodata values are set to 0
            # Clip to 0,255
            sir_scale[sir_scale < 0] = 0
            sir_scale[sir_scale > 255] = 255
            # Ensure uint8 data and C contiguous data
            sir_scale = np.require(sir_scale, np.uint8, 'C')

            # Construct image from sir_scale
            # http://www.swharden.com/blog/2013-06-03-realtime-image-pixelmap-from-numpy-array-data-in-qt/
            # Note that I use the bytesPerLine option here. Without it, the
            # data must be 32-bit aligned (4 bytes). This means with uint8 data
            # that the image width must be a multiple of 4. This does not apply
            # to all SIR images, so I set bytesPerLine to be
            # nsx (items) * 1 (bytes/item)
            image = QImage(sir_scale.data, nsx, nsy, nsx,
                           QImage.Format_Indexed8)
            # ctab = []
            # for i in xrange(256):
            #     ctab.append(QtGui.qRgb(i,i,i))
            # image.setColorTable(ctab)

            # Save pixmap
            pixmap = QPixmap.fromImage(image)
            self.sir_files[tabname]['pixmap'] = pixmap
        else:
            logging.warning("Can't use update_image for {}".format(tabname))
def run_script(iface):
    canvas = iface.mapCanvas()

    img = QImage(QSize(1920, 1080), QImage.Format_ARGB32_Premultiplied)
    color = QColor(255, 255, 255)
    p = QPainter(img)

    for path in paths:
        #accessibilityLayer.setDataProvider(path)

        # http://www.qgisworkshop.org/html/workshop/python_in_qgis_tutorial2.html
        rlayer = iface.addRasterLayer(path)
        # http://gis.stackexchange.com/questions/26846
        rlayer.loadNamedStyle(
            '/home/matthewc/microaccessibility/times/colors.qml')

        # add the vector layers
        poly = iface.addVectorLayer(
            'dbname=\'matthewc\' host=localhost port=5432 user=\'matthewc\' password=\'password\' sslmode=disable key=\'tid\' srid=4326 type=POLYGON table="public"."ucsb_final_polygon" (way) sql=',
            'poly', 'postgres')
        poly.loadNamedStyle('/home/matthewc/microaccessibility/times/poly.qml')

        line = iface.addVectorLayer(
            'dbname=\'matthewc\' host=localhost port=5432 user=\'matthewc\' password=\'password\' sslmode=disable key=\'tid\' srid=4326 type=LINESTRING table="public"."ucsb_final_line" (way) sql=',
            'line', 'postgres')
        line.loadNamedStyle('/home/matthewc/microaccessibility/times/line.qml')

        renderer = canvas.mapRenderer()

        img.fill(color.rgb())
        p.begin(img)
        p.setRenderHint(QPainter.Antialiasing)
        renderer.setOutputSize(img.size(), img.logicalDpiX())
        renderer.render(p)

        p.setFont(QFont("Ubuntu", 48, QFont.Bold))
        p.setPen(QColor(0, 0, 0))
        p.drawText(10, 58, parseToTime(path))

        p.end()
        img.save(path + ".png", "png")

        QgsMapLayerRegistry.instance().removeMapLayer(rlayer.id())
        QgsMapLayerRegistry.instance().removeMapLayer(poly.id())
        QgsMapLayerRegistry.instance().removeMapLayer(line.id())
示例#13
0
    def thumbnailAtPercent(self, *args):
        """
        thumbnailAtPercent(VideoDecoder self, uint8_t timeInPercent, int32_t scaledSize=64) -> RCPtrImage
        thumbnailAtPercent(VideoDecoder self, uint8_t timeInPercent) -> RCPtrImage

        Take a percent of video length and scale size as parameters.
        Return a QImage containg a thumbnail of the video at percent x of the duration, scaled size by default is 64.
        Returned class use ref counting.
        If error occurs throw a std::string containing error message.

        """
        val = _video.VideoDecoder_thumbnailAtPercent(self, *args)
        return QImage(val.data(), val.width(), val.height(), 5)


        return val
示例#14
0
    def thumbnailAt(self, *args):
        """
        thumbnailAt(VideoDecoder self, int64_t timeInSeconds, int32_t scaledSize=64) -> RCPtrImage
        thumbnailAt(VideoDecoder self, int64_t timeInSeconds) -> RCPtrImage

        Take a time in seconds and scale size as parameters.
        Return a QImage containg a thumbnail of the video at time x in seconds, scaled size by default is 64.
        Returned class use ref counting.
        If error occurs throw a std::string containing error message.

        """
        val = _video.VideoDecoder_thumbnailAt(self, *args)
        return QImage(val.data(), val.width(), val.height(), 5)  


        return val
示例#15
0
def sliceImg(width, height, axisLabels, perpAxisLabel, perpAxisValue):
    print perpAxisLabel, perpAxisValue
    img = QImage(width, height, QImage.Format_ARGB32)
    img.fill(0)

    p = QPainter(img)
    p.setPen(QColor(255,255,255))
    p.setBrush(QBrush(QColor(255,255,255)))
    def arrow(p, From, To, label):
        p.drawLine(From, To)
        p.drawText(To, label)

    offset = 10
    arrow(p, QPoint(offset, offset), QPoint(offset, height-offset), axisLabels[1])
    arrow(p, QPoint(offset, offset), QPoint(width-offset,  offset), axisLabels[0])
    p.drawText(2*offset, 2*offset, "%s=%d" % (perpAxisLabel, perpAxisValue))
    fm = p.fontMetrics()
    size = fm.size(Qt.TextSingleLine, "updown")

    p.drawText(numpy.random.randint(offset, width-offset-size.width()), numpy.random.randint(offset, height-offset-size.height()), "updown")

    dots = []
    numPixels = 0
    while numPixels < 30:
        r = numpy.random.randint(1, 255)
        rx, ry = numpy.random.randint(offset, width-offset), numpy.random.randint(offset, height-offset)
        if img.pixel(rx,ry) != 0:
            continue
        p.setPen(QPen(QColor(r,r,r)))
        p.drawPoint(rx, ry)
        dots.append(((rx,ry), r))
        numPixels += 1

    p.end()
    
    
    img.save('test.png')

    a = qimage2ndarray.rgb_view(img)
    a = a[:,:,0].squeeze().swapaxes(0,1)

    for (rx,ry), r in dots:
        assert QColor.fromRgba(img.pixel(rx,ry)).red() == r, "QColor.fromRgba(img.pixel(rx,ry)).red() == %d != %d" % (QColor.fromRgba(img.pixel(rx,ry)).red(), r)
        assert(a[rx,ry] == r), "a[%d,%d] == %d != %d)" % (rx, ry, a[rx,ry], r)
    return (a, dots)
示例#16
0
    def maybe_get_icon(self):
        u"""
        Get icon for the site as a QImage if we haven’t already.

        Get the site icon, either the 'rel="icon"' or the favicon, for
        the web page at url or passed in as page_html and store it as
        a QImage. This function can be called repeatedly and loads the
        icon only once.
        """
        if self.site_icon:
            return
        if not with_pyqt:
            self.site_icon = None
            return
        page_request = urllib2.Request(self.icon_url)
        if self.user_agent:
            page_request.add_header('User-agent', self.user_agent)
        page_response = urllib2.urlopen(page_request)
        if 200 != page_response.code:
            self.get_favicon()
            return
        page_soup = soup(page_response)
        try:
            icon_url = page_soup.find(name='link', attrs={'rel':
                                                          'icon'})['href']
        except (TypeError, KeyError):
            self.get_favicon()
            return
        # The url may be absolute or relative.
        if not urlparse.urlsplit(icon_url).netloc:
            icon_url = urlparse.urljoin(self.url,
                                        urllib.quote(icon_url.encode('utf-8')))
        icon_request = urllib2.Request(icon_url)
        if self.user_agent:
            icon_request.add_header('User-agent', self.user_agent)
        icon_response = urllib2.urlopen(icon_request)
        if 200 != icon_response.code:
            self.site_icon = None
            return
        self.site_icon = QImage.fromData(icon_response.read())
        max_size = QSize(self.max_icon_size, self.max_icon_size)
        icon_size = self.site_icon.size()
        if icon_size.width() > max_size.width() \
                or icon_size.height() > max_size.height():
            self.site_icon = self.site_icon.scaled(max_size,
                                                   Qt.KeepAspectRatio,
                                                   Qt.SmoothTransformation)
def font_bmp_to_alpha(filename):
  
  image = QImage(filename)
  image = image.convertToFormat(QImage.Format_ARGB32_Premultiplied)
  
  # Because the game uses 8bit grayscale bitmaps for its fonts with white as
  # fully visible and black as fully transparent, I'm using a naive technique
  # that averages the RGB value of a pixel and sets that as its alpha value.
  # I'm sure this will do fun stuff to other images, but it does the job
  # for the game's fonts, and that's all that really matters. ヽ(´ー`)ノ
  for i in range(image.width()):
    for j in range(image.height()):
      color = QColor(image.pixel(i, j))
      alpha = (color.red() + color.green() + color.blue()) / 3
      color.setAlpha(alpha)
      image.setPixel(i, j, color.rgba())
  
  return image
示例#18
0
class LoadedImage(QLabel):
  def __init__(self):
    QLabel.__init__(self)
    #self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
    self.node = None
    self.angle = 0
    self.factor = 1
    self.imgWidth = 0
    self.baseImage = QImage()
    self.cpixmap = QPixmap()
    self.matrix = QMatrix()


  def load(self, node, type):
    self.node = node
    file = self.node.open()
    buff = file.read()
    file.close()
    self.baseImage.loadFromData(buff, type)


  def adjust(self, imgwidth):
    self.imgWidth = imgwidth
    self.currentImage = self.baseImage.scaled(QSize(self.imgWidth, self.imgWidth), Qt.KeepAspectRatio, Qt.FastTransformation)
    self.setPixmap(QPixmap.fromImage(self.currentImage))
    self.adjustSize()


  def resize(self, zoomer):
    w = self.currentImage.width() * zoomer
    self.currentImage = self.baseImage.scaled(QSize(w, w), Qt.KeepAspectRatio, Qt.FastTransformation)
    self.setPixmap(QPixmap.fromImage(self.currentImage))
    self.adjustSize()


  def rotate(self, angle):
    matrix = QMatrix()
    matrix.rotate(angle)
    self.currentImage = self.currentImage.transformed(matrix)
    self.baseImage = self.baseImage.transformed(matrix)
    self.setPixmap(QPixmap.fromImage(self.currentImage))
    self.adjustSize()


  def fitbest(self):
    self.currentImage = self.baseImage.scaled(QSize(self.imgWidth, self.imgWidth), Qt.KeepAspectRatio, Qt.FastTransformation)
    self.setPixmap(QPixmap.fromImage(self.currentImage))
    self.adjustSize()


  def notSupported(self):
    #self.setPixmap(None)
    self.setText("Format Not Supported")
    self.adjustSize()
def get_artwork_icon(file_id):

    icon_file = os.path.join(GALLERY_DIR,
                             "gallery_thumbnail_a_%03d.png" % file_id)

    if not os.path.isfile(icon_file):
        icon_file = os.path.join(GALLERY_DIR, "gallery_ico_a_none.png")

    icon = QImage(icon_file)

    x_pos = 326
    y_pos = 66

    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, icon.width(), icon.height()), icon,
                      icon.rect())
    painter.end()

    return out
示例#20
0
def get_grayscale(data, w, h, crop=True):
    table = []
    for i in range(256):
        table.append((255 << 24) | (i << 16) | (i << 8) | i)
    image = QImage(data, w, h, QImage.Format_Indexed8)
    image.setColorTable(table)
    image = image.convertToFormat(QImage.Format_ARGB32)

    if crop:
        image = image.copy(0, 0, w - 2, h - 2)
    return image
示例#21
0
 def renderScene(self, s, exportFilename=None):
     img = QImage(310, 290, QImage.Format_ARGB32_Premultiplied)
     img.fill(0)
     p = QPainter(img)
     s.render(p)
     s.joinRendering()
     s.render(p)
     p.end()
     if exportFilename is not None:
         img.save(exportFilename)
     return byte_view(img)
示例#22
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self.setSizePolicy(QtGui.QSizePolicy.Expanding,
                        QtGui.QSizePolicy.Expanding)
     self.setFocusPolicy(QtCore.Qt.StrongFocus)
     self.computericon = QImage(":/pics/pics/computer.png")
     self.storageicon = QImage(":/pics/pics/storage.png")
     self.routericon = QImage(":/pics/pics/router.png")
     self.computerselectedicon = QImage(":/pics/pics/computer_selected.png")
     self.storageselectedicon = QImage(":/pics/pics/storage_selected.png")
     self.routerselectedicon = QImage(":/pics/pics/router_selected.png")
示例#23
0
    def setup_texture(self, img_path):
#        self.texture = glGenTextures(1)
#        
#        glBindTexture(GL_TEXTURE_2D, self.texture)
#        
#        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
#        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
#        
#        img = QImage(img_path)
#        img = QGLWidget.convertToGLFormat(img)
#        
#        glTexImage2D(GL_TEXTURE_2D, 0, 3, img.width(), img.height(),
#            0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits().asstring(img.numBytes()))
#            
#        glBindTexture(GL_TEXTURE_2D, 0)

        self.texture = QImage(img_path)
示例#24
0
 def __init__(self, mobj, parent):
     super(FuncItem, self).__init__(mobj, parent)
     self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
     #self.funcImage = QImage('icons/classIcon/Function.png').scaled(15,33)
     iconmap_file = (path.join(config.settings[config.KEY_ICON_DIR],
                               'classIcon/Function.png'))
     self.funcImage = QImage(iconmap_file).scaled(15, 33)
     self.bg = QtGui.QGraphicsRectItem(self)
     self.bg.setAcceptHoverEvents(True)
     self.gobj = QtGui.QGraphicsPixmapItem(
         QtGui.QPixmap.fromImage(self.funcImage), self.bg)
     #self.gobj = QtGui.QGraphicsPixmapItem(QtGui.QPixmap('../icons/classIcon/Function.png'))
     self.gobj.setAcceptHoverEvents(True)
     self.gobj.mobj = self.mobj
     classname = self.mobj.className
     funcdoc = (element(self.mobj.path)).expr
     self.gobj.setToolTip(funcdoc)
示例#25
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self._image = QImage()

        self._img_width = 640
        self._img_length = 480
        self.resize(self._img_width, self._img_length)

        self._camera_id = 0
        self._video_proxy = None
        self._al_image = None
        self._img_client = ""

        commandModule.nao_camera_register(self)
        # startTimer runs timerEvent every 100ms
        self.startTimer(100)
示例#26
0
文件: kinect.py 项目: oidelima/armlab
    def convertDepthFrame(self):
        try:
            self.DepthHSV[..., 0] = self.currentDepthFrame
            self.DepthHSV[..., 1] = 0x9F
            self.DepthHSV[..., 2] = 0xFF

            self.workspacemask = np.zeros((480, 640, 1)).astype(np.uint8)
            self.workspacemask[self.currentDepthFrame < 724.5, 0] = 255
            cv2.imwrite("workspacemask.jpg", self.workspacemask)

            self.DepthCM = cv2.cvtColor(self.DepthHSV, cv2.COLOR_HSV2RGB)
            self.roiContours(self.DepthCM, 400)
            img = QImage(self.DepthCM, self.DepthCM.shape[1],
                         self.DepthCM.shape[0], QImage.Format_RGB888)
            return img
        except:
            return None
示例#27
0
def array_to_pixmap(arr):
    arr = np.array(arr)

    if arr.dtype in (np.float, np.float16, np.float32, np.float64):
        arr = arr * 255
    elif arr.dtype in (np.int16, np.uint16):
        arr = arr // 256

    arr = arr.clip(0, 255).astype(np.uint8)

    if len(arr.shape) == 2 or (len(arr.shape) == 3 and arr.shape[2] == 1):
        arr = cv.cvtColor(arr, cv.COLOR_GRAY2BGRA)
    elif len(arr.shape) == 3 and arr.shape[2] == 3:
        arr = cv.cvtColor(arr, cv.COLOR_BGR2BGRA)

    image = QImage(arr.data, arr.shape[1], arr.shape[0], QImage.Format_ARGB32)
    return QPixmap.fromImage(image)
示例#28
0
 def _getPng(self, width=None, height=None):
     image = QImage(self.web_page.viewportSize(), QImage.Format_ARGB32)
     painter = QPainter(image)
     self.web_page.mainFrame().render(painter)
     painter.end()
     if width:
         image = image.scaledToWidth(width, Qt.SmoothTransformation)
     if height:
         image = image.copy(0, 0, width, height)
     b = QBuffer()
     image.save(b, "png")
     return bytes(b.data())
示例#29
0
    def json_to_node(self, jsnode):
        node_class = globals()[jsnode["class"]]
        node_symbol = globals()[jsnode["symbol"]]

        symbol = node_symbol()
        symbol.name = jsnode["text"].encode("utf-8")
        if self.unescape:
            symbol.name = symbol.name.decode("string-escape")
        node = node_class(symbol)
        assert node.symbol is symbol
        node.lookup = jsnode["lookup"]
        node.image_src = jsnode["image_src"]
        if node.image_src is not None:
            node.image = QImage(node.image_src)

        if isinstance(symbol, Terminal) or isinstance(symbol, FinishSymbol):
            node.prev_term = self.last_terminal
            if self.last_terminal is not None:
                self.last_terminal.next_term = node
            self.last_terminal = node

        if "lbox" in jsnode:
            temp = self.last_terminal
            self.last_terminal = None
            lbox_root = self.json_to_node(jsnode["lbox"])
            lbox_root.magic_backpointer = node
            node.symbol.ast = lbox_root
            node.symbol.parser = lbox_root
            self.last_terminal = temp
            self.language_boxes.append(
                (lbox_root, jsnode["language"], jsnode["whitespaces"]))

        children = []
        last_child = None
        for c in jsnode["children"]:
            cnode = self.json_to_node(c)
            cnode.parent = node
            cnode.left = last_child
            if last_child:
                last_child.right = cnode
            children.append(cnode)
            last_child = cnode
        node.children = children

        return node
示例#30
0
 def maybe_get_icon(self):
     if self.site_icon:
         return
     if not with_pyqt:
         self.site_icon = None
         return
     try:
         icon_data = self.get_data_from_url(self.full_icon_url)
     except:
         AudioDownloader.maybe_get_icon(self)
     else:
         self.site_icon = QImage.fromData(icon_data)
         max_size = QSize(self.max_icon_size, self.max_icon_size)
         ico_size = self.site_icon.size()
         if ico_size.width() > max_size.width() \
                 or ico_size.height() > max_size.height():
             self.site_icon = self.site_icon.scaled(
                 max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)