Exemplo n.º 1
0
 def __init__(self, parent, tree, text, linkText, linkColor="blue", icon=None):
     QTreeWidgetItem.__init__(self, parent)
     self.parent = parent
     self.tree = tree
     layout = QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     self.label = QLabel()
     if icon and os.path.exists(icon):
         svg_renderer = QSvgRenderer(icon)
         image = QImage(32, 32, QImage.Format_ARGB32)
         # Set the ARGB to 0 to prevent rendering artifacts
         image.fill(0x00000000)
         svg_renderer.render(QPainter(image))
         pixmap = QPixmap.fromImage(image)
         icon = QIcon(pixmap)
         self.setIcon(0, icon)
         self.setSizeHint(0, QSize(32, 32))
     self.label.setText(text)
     layout.addWidget(self.label)
     if linkText:
         self.linkLabel = QLabel()
         self.linkLabel.setText("<a href='#' style='color: %s;'> %s</a>" % (linkColor, linkText))
         self.linkLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
         layout.addWidget(self.linkLabel)
         self.linkLabel.linkActivated.connect(self.linkClicked)
     w = QWidget()
     w.setLayout(layout)
     self.tree.setItemWidget(self, 0, w)
Exemplo n.º 2
0
    def set_thumbnail(self):
        """
        Sets thumbnail to the document widget by
        cropping if necessary.
        :return: None
        :rtype: NoneType
        """
        extension = self._displayName[self._displayName.rfind('.'):]

        QApplication.processEvents()
        doc_path = '{}/{}/{}/{}/{}{}'.format(
            source_document_location(),
            str(self.curr_profile.name),
            str(self._source_entity),
            str(self.doc_type_value()).replace(' ', '_'),
            str(self.fileUUID),
            str(extension)
        ).lower()

        ph_image = QImage(doc_path)
        ph_pixmap = QPixmap.fromImage(ph_image)
        # If width is larger than height, use height as width and height
        if ph_pixmap.width() > ph_pixmap.height():
            rectangle = QRect(0, 0, ph_pixmap.height(), ph_pixmap.height())
            ph_pixmap = ph_pixmap.copy(rectangle)
        # If height is larger than width, use width as width and height
        elif ph_pixmap.height() > ph_pixmap.width():
            rectangle = QRect(0, 0, ph_pixmap.width(), ph_pixmap.width())
            ph_pixmap = ph_pixmap.copy(rectangle)

        self.lblThumbnail.setPixmap(ph_pixmap)
        self.lblThumbnail.setScaledContents(True)
Exemplo n.º 3
0
    def getFrame(self):
        """ Camera code  """

        # TOMsMessageLog.logMessage("In cvCamera::getFrame ... ", level=Qgis.Info)

        ret, self.frame = self.cap.read(
        )  # return a single frame in variable `frame`

        if ret == True:
            # Need to change from BRG (cv::mat) to RGB image
            cvRGBImg = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
            qimg = QImage(cvRGBImg.data, cvRGBImg.shape[1], cvRGBImg.shape[0],
                          QImage.Format_RGB888)

            # Now display ...
            pixmap = QPixmap.fromImage(qimg)

            self.changePixmap.emit(pixmap)

        else:

            TOMsMessageLog.logMessage(
                "In cvCamera::useCamera: frame not returned ... ",
                level=Qgis.Info)
            self.closeCamera.emit()
Exemplo n.º 4
0
    def get_icon_pixmap(icon: str) -> QPixmap:
        """
        Returns a plugin icon's PNG file path
        :param icon: icon name (png file name)
        :return: icon png path
        """
        path = os.path.join(os.path.dirname(__file__), '..', 'images', 'icons',
                            icon)
        if not os.path.exists(path):
            return QPixmap()

        im = QImage(path)
        return QPixmap.fromImage(im)
Exemplo n.º 5
0
def get_colored_pixmap(filename, color, size):
    """Returns a colored pixmap of given size."""
    pixmap = QPixmap(filename).scaled(size, Qt.KeepAspectRatio,
                                      Qt.SmoothTransformation)
    image = QImage(pixmap.width(), pixmap.height(),
                   QImage.Format_ARGB32_Premultiplied)

    image.fill(color)

    painter = QPainter(image)
    painter.setCompositionMode(QPainter.CompositionMode_DestinationIn)
    painter.drawPixmap(0, 0, pixmap)
    painter.end()

    return QPixmap.fromImage(image)
Exemplo n.º 6
0
 def makeRectCursor(self):
     rectSize = self.calcRectSize()
     width = rectSize[0]
     height = rectSize[1]
     #make invisible rectangle when rectSize is too large
     if width > 2000:
         width = 0
     if height > 2000:
         height = 0
     image = QImage(QSize(width, height), QImage.Format_ARGB32)
     #fill with a invisible color
     image.fill(0)
     p = QPainter()
     p.begin(image)
     p.drawRect(QRect(0, 0, width - 1, height - 1))
     p.end()
     return QPixmap.fromImage(image)
Exemplo n.º 7
0
    def set_symbol(self, symbol_image: QImage):
        self.pixmap = QPixmap.fromImage(symbol_image)
        fm = QFontMetricsF(self.marker_font)

        # set item size
        self.item_size.setWidth(self.pixmap.width() + fm.width("360"))

        pixmap_height = self.pixmap.height()
        font_height = fm.height()
        if pixmap_height >= font_height:
            self.item_size.setHeight(self.pixmap.height())
        else:
            self.item_size.setHeight(fm.height())

        half_item_width = self.pixmap.width() / 2.0
        self.arrow_path = QPainterPath()
        self.arrow_path.moveTo(half_item_width, pixmap_height)
        self.arrow_path.lineTo(half_item_width, 0)
        self.arrow_path.moveTo(self.pixmap.width() * 0.25,
                               pixmap_height * 0.25)
        self.arrow_path.lineTo(half_item_width, 0)
        self.arrow_path.lineTo(self.pixmap.width() * 0.75,
                               pixmap_height * 0.25)
Exemplo n.º 8
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
Exemplo n.º 9
0
    def __init__(self,
                 geoservice,
                 image_ba,
                 parent=None,
                 extent_renderer=None):
        QWidget.__init__(self, parent)

        self.extent_renderer = extent_renderer

        self.layout = QHBoxLayout(self)
        self.layout.setContentsMargins(5, 10, 5, 10)
        self.setLayout(self.layout)

        self.service_icon = QLabel(self)
        self.service_icon.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.service_icon.resize(24, 24)

        qimg = QImage.fromData(image_ba)
        pixmap = QPixmap.fromImage(qimg)
        self.service_icon.setPixmap(pixmap)
        self.layout.addWidget(self.service_icon)

        self.service_desc_layout = QGridLayout(self)
        self.service_desc_layout.setSpacing(0)
        self.layout.addLayout(self.service_desc_layout)

        self.service_name = QLabel(self)
        self.service_name.setTextFormat(Qt.RichText)
        self.service_name.setWordWrap(True)
        self.service_name.setText(u"   <strong> {} </strong>".format(
            geoservice.get('name', u"")))
        self.service_desc_layout.addWidget(self.service_name, 0, 0, 1, 3)

        self.service_type = QLabel(self)
        self.service_type.setTextFormat(Qt.RichText)
        self.service_type.setWordWrap(True)
        self.service_type.setText(geoservice.get('type', u"").upper() + " ")
        self.service_desc_layout.addWidget(self.service_type, 1, 0)

        self.service_deteils = QLabel(self)
        self.service_deteils.setTextFormat(Qt.RichText)
        self.service_deteils.setWordWrap(True)
        self.service_deteils.setOpenExternalLinks(True)
        self.service_deteils.setText(u"<a href=\"{0}\">{1}</a>, ".format(
            Client().geoservice_info_url(geoservice.get('id', u"")),
            self.tr('details')))
        self.service_desc_layout.addWidget(self.service_deteils, 1, 1)

        self.service_report = QLabel(self)
        self.service_report.setTextFormat(Qt.RichText)
        self.service_report.setWordWrap(True)
        self.service_report.setOpenExternalLinks(True)
        self.service_report.setText(u"<a href=\"{0}\">{1}</a><div/>".format(
            Client().geoservice_report_url(geoservice.get('id', u"")),
            self.tr('report a problem')))
        self.service_desc_layout.addWidget(self.service_report, 1, 2)
        self.service_desc_layout.setColumnStretch(2, 1)

        self.status_label = QLabel(self)
        self.status_label.setTextFormat(Qt.RichText)
        self.status_label.setText(u'\u2022')

        status = geoservice.get('cumulative_status', u'')
        if status == 'works':
            self.status_label.setStyleSheet("color: green; font-size: 30px")
        if status == 'failed':
            self.status_label.setStyleSheet("color: red; font-size: 30px")
        if status == 'problematic':
            self.status_label.setStyleSheet("color: yellow; font-size: 30px")
        self.layout.addWidget(self.status_label)

        self.addButton = QToolButton()
        self.addButton.setText(self.tr("Add"))
        self.addButton.clicked.connect(self.addToMap)
        self.layout.addWidget(self.addButton)

        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)

        self.geoservice = geoservice
        self.image_ba = image_ba
Exemplo n.º 10
0
    def __init__(self, geoservice, image_ba, parent=None, extent_renderer=None):
        QWidget.__init__(self, parent)

        self.extent_renderer = extent_renderer

        self.layout = QHBoxLayout(self)
        self.layout.setContentsMargins(5, 10, 5, 10)
        self.setLayout(self.layout)

        self.service_icon = QLabel(self)
        self.service_icon.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.service_icon.resize(24, 24)

        qimg = QImage.fromData(image_ba)
        pixmap = QPixmap.fromImage(qimg)
        self.service_icon.setPixmap(pixmap)
        self.layout.addWidget(self.service_icon)

        self.service_desc_layout = QGridLayout(self)
        self.service_desc_layout.setSpacing(0)
        self.layout.addLayout(self.service_desc_layout)

        self.service_name = QLabel(self)
        self.service_name.setTextFormat(Qt.RichText)
        self.service_name.setWordWrap(True)
        self.service_name.setText(u"   <strong> {} </strong>".format(geoservice.get('name', u"")))
        self.service_desc_layout.addWidget(self.service_name, 0, 0, 1, 3)

        self.service_type = QLabel(self)
        self.service_type.setTextFormat(Qt.RichText)
        self.service_type.setWordWrap(True)
        self.service_type.setText(geoservice.get('type', u"").upper() + " ")
        self.service_desc_layout.addWidget(self.service_type, 1, 0)

        self.service_deteils = QLabel(self)
        self.service_deteils.setTextFormat(Qt.RichText)
        self.service_deteils.setWordWrap(True)
        self.service_deteils.setOpenExternalLinks(True)
        self.service_deteils.setText(u"<a href=\"{0}\">{1}</a>, ".format(
            Client().geoservice_info_url(geoservice.get('id', u"")),
            self.tr('details')
        ))
        self.service_desc_layout.addWidget(self.service_deteils, 1, 1)

        self.service_report = QLabel(self)
        self.service_report.setTextFormat(Qt.RichText)
        self.service_report.setWordWrap(True)
        self.service_report.setOpenExternalLinks(True)
        self.service_report.setText(u"<a href=\"{0}\">{1}</a><div/>".format(
            Client().geoservice_report_url(geoservice.get('id', u"")),
            self.tr('report a problem')
        ))
        self.service_desc_layout.addWidget(self.service_report, 1, 2)
        self.service_desc_layout.setColumnStretch(2, 1)


        self.status_label = QLabel(self)
        self.status_label.setTextFormat(Qt.RichText)
        self.status_label.setText(u'\u2022')


        status = geoservice.get('cumulative_status', u'')
        if status == 'works':
            self.status_label.setStyleSheet("color: green; font-size: 30px")
        if status == 'failed':
            self.status_label.setStyleSheet("color: red; font-size: 30px")
        if status == 'problematic':
            self.status_label.setStyleSheet("color: yellow; font-size: 30px")
        self.layout.addWidget(self.status_label)


        self.addButton = QToolButton()
        self.addButton.setText(self.tr("Add"))
        self.addButton.clicked.connect(self.addToMap)
        self.layout.addWidget(self.addButton)
        
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)

        self.geoservice = geoservice
        self.image_ba = image_ba
Exemplo n.º 11
0
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import QLabel
from qgis.PyQt.QtGui import QImage, QPixmap
from qgis.utils import iface
import sqlite3

UNIQUE_FIELD = "unique_field_name"
BLOB_FIELD = "picture_field_name"
FIELD_VALUE = '[%unique_field_name%]'

vl = iface.activeLayer()
pr = vl.dataProvider()
db = pr.dataSourceUri().split(' ')[0].replace('dbname=', '').replace("'", "")
conn = sqlite3.connect(db)
sql = "SELECT {0} FROM {1} WHERE {2}={3}".format(BLOB_FIELD, vl.name(),
                                                 UNIQUE_FIELD, FIELD_VALUE)
c = conn.cursor()
c.execute(sql)
rows = c.fetchone()
c.close()
conn.close()

qimg = QImage.fromData(rows[0])
pixmap = QPixmap.fromImage(qimg)

label = QLabel()
h = label.height()
w = label.width()
label.setPixmap(pixmap.scaled(w, h, Qt.KeepAspectRatio))
label.show()
Exemplo n.º 12
0
    def update_summary_sheet(self,lyr=None, force=None):
        '''
        Creates a summary sheet with thumbnail, layer metadata and online view link
        '''
        #create a layer snapshot and upload it to google drive

        if not lyr:
            lyr = self.lyr

        mapbox_style = self.service_sheet.sheet_cell('settings!A5')
        if not mapbox_style:
            logger("migrating mapbox style")
            self.service_sheet.set_style_mapbox(self.layer_style_to_json(self.lyr))
        
        if not force and not self.dirty and not self.restyled:
            return

        if self.restyled:
            self.service_sheet.set_style_qgis(self.layer_style_to_xml(self.lyr))
            self.service_sheet.set_style_sld(self.SLD_to_xml(self.lyr))
            self.service_sheet.set_style_mapbox(self.layer_style_to_json(self.lyr))
            self.saveMetadataState()
        
        canvas = QgsMapCanvas()
        canvas.resize(QSize(600,600))
        canvas.setCanvasColor(Qt.white)
        canvas.setExtent(lyr.extent())
        canvas.setLayers([lyr])
        canvas.refresh()
        canvas.update()
        settings = canvas.mapSettings()
        settings.setLayers([lyr])
        job = QgsMapRendererParallelJob(settings)
        job.start()
        job.waitForFinished()
        image = job.renderedImage()

        transparent_image = QImage(image.width(), image.height(), QImage.Format_ARGB32)
        transparent_image.fill(Qt.transparent)
        p = QPainter(transparent_image)
        mask = image.createMaskFromColor(QColor(255, 255, 255).rgb(), Qt.MaskInColor)
        p.setClipRegion(QRegion(QBitmap(QPixmap.fromImage(mask))))
        p.drawPixmap(0, 0, QPixmap.fromImage(image))
        p.end()

        tmp_path = os.path.join(self.parent.plugin_dir,self.service_sheet.name+".png")
        transparent_image.save(tmp_path,"PNG")
        image_istances = self.service_drive.list_files(mimeTypeFilter='image/png',filename=self.service_sheet.name+".png")
        for imagename, image_props in image_istances.items():
            self.service_drive.delete_file(image_props['id'])
        result = self.service_drive.upload_image(tmp_path)
        self.service_drive.add_permission(result['id'],'anyone','reader')
        webLink = result['webContentLink'] #'https://drive.google.com/uc?export=view&id='+result['id']
        logger("webLink:" + webLink)
        canvas.setDestinationCrs(QgsCoordinateReferenceSystem(4326))
        worldfile = QgsMapSettingsUtils.worldFileContent(settings)
        lonlat_min = self.transformToWGS84(QgsPointXY(canvas.extent().xMinimum(), canvas.extent().yMinimum()))
        lonlat_max = self.transformToWGS84(QgsPointXY(canvas.extent().xMaximum(), canvas.extent().yMaximum()))
        keymap_extent = [lonlat_min.x(),lonlat_min.y(),lonlat_max.x(),lonlat_max.y()]
        
        os.remove(tmp_path)
        #update layer metadata
        summary_id = self.service_sheet.add_sheet('summary', no_grid=True)
        appPropsUpdate = [
            ["keymap",webLink],
            ["worldfile",pack(worldfile)],
            ["keymap_extent", json.dumps(keymap_extent)]
        ]
        res = self.service_sheet.update_appProperties(self.spreadsheet_id,appPropsUpdate)
        
        self.saveMetadataState(metadata=self.get_layer_metadata())
        self.parent.public_db.setKey(self.spreadsheet_id, dict(self.get_layer_metadata()+appPropsUpdate),only_update=True)
        #merge cells to visualize snapshot and aaply image snapshot
        request_body = {
            'requests': [{
                'mergeCells': {
                    "range": {
                        "sheetId": summary_id,
                        "startRowIndex": 9,
                        "endRowIndex": 32,
                        "startColumnIndex": 0,
                        "endColumnIndex": 9,
                    },
                "mergeType": 'MERGE_ALL'
                }
            }]
        }
        self.service_sheet.service.spreadsheets().batchUpdate(spreadsheetId=self.spreadsheet_id, body=request_body).execute()
        self.service_sheet.set_sheet_cell('summary!A10','=IMAGE("%s",3)' % webLink)

        permissions = self.service_drive.file_property(self.spreadsheet_id,'permissions')
        for permission in permissions:
            if permission['type'] == 'anyone':
                public = True
                break
            else:
                public = False
        if public:
            update_range = 'summary!A9:B9'
            update_body = {
                "range": update_range,
                "values": [['public link', "https://enricofer.github.io/gdrive_provider/weblink/converter.html?spreadsheet_id="+self.spreadsheet_id]]
            }
            self.service_sheet.service.spreadsheets().values().update(spreadsheetId=self.spreadsheet_id,range=update_range, body=update_body, valueInputOption='USER_ENTERED').execute()

        #hide worksheets except summary
        sheets = self.service_sheet.get_sheets()
        #self.service_sheet.toggle_sheet('summary', sheets['summary'], hidden=None)
        for sheet_name,sheet_id in sheets.items():
            if not sheet_name == 'summary':
                self.service_sheet.toggle_sheet(sheet_name, sheet_id, hidden=True)
Exemplo n.º 13
0
 def imageCaptured(self, frameid, image):
     # TODO Doing a pixmap convert here is a waste but downstream needs a qpixmap for now
     # refactor later
     if self.camera:
         self.camera.unload()
     self.imagecaptured.emit(QPixmap.fromImage(image))
Exemplo n.º 14
0
 def pixmap(self):
     return QPixmap.fromImage(self.image)
Exemplo n.º 15
0
 def _renderimage(self):
     image = self.renderjob.renderedImage()
     self.previewImage.setPixmap(QPixmap.fromImage(image))
Exemplo n.º 16
0
class DrawToolBar(object):

    NameSpace = getNameSpace()

    small_pt = 5
    white_pen = QPen(Qt.white, small_pt)
    white_pen.setCapStyle(Qt.RoundCap)

    black_pen = QPen(Qt.black, small_pt)
    black_pen.setCapStyle(Qt.RoundCap)

    glass_pen = QPen(QColor(192, 192, 192, 128), 3)

    transparent_brush = QBrush(Qt.transparent)

    black_brush = QBrush(Qt.black)

    bold_12 = QFont("Arial", 12, QFont.Bold)

    # Stamp Image
    confidential = QPixmap.fromImage(
        QImage(":/imgFMV/images/stamp/confidential.png"))

    @staticmethod
    def setValues(options=None):
        ''' Function to set Drawing Values '''
        s = QSettings()

        ####### Magnifier Glass #######

        shape_type = s.value(DrawToolBar.NameSpace +
                             "/Options/magnifier/shape")
        if shape_type is not None:
            global TYPE_MAGNIFIER
            TYPE_MAGNIFIER = shape_type
            if options is not None:
                if TYPE_MAGNIFIER == 0:
                    # Square
                    options.rB_Square_m.setChecked(True)
                else:
                    # Circle
                    options.rB_Circle_m.setChecked(True)

        mFactor = s.value(DrawToolBar.NameSpace + "/Options/magnifier/factor")
        if mFactor is not None:
            global MAX_FACTOR
            MAX_FACTOR = int(mFactor)
            if options is not None:
                options.sb_factor.setValue(MAX_FACTOR)

        mSize = s.value(DrawToolBar.NameSpace + "/Options/magnifier/size")
        if mSize is not None:
            global MAX_MAGNIFIER
            MAX_MAGNIFIER = int(mSize)
            if options is not None:
                options.sl_Size.setValue(MAX_MAGNIFIER)

        ####### Drawings #######

        poly_w = s.value(DrawToolBar.NameSpace +
                         "/Options/drawings/polygons/width")
        if poly_w is not None:
            global PolyWidth
            PolyWidth = int(poly_w)
            if options is not None:
                options.poly_width.setValue(PolyWidth)

        poly_p = s.value(DrawToolBar.NameSpace +
                         "/Options/drawings/polygons/pen")
        if poly_p is not None:
            global PolyPen
            PolyPen = QPen(QColor(poly_p))
            PolyPen.setCapStyle(Qt.RoundCap)
            PolyPen.setWidth(PolyWidth)
            if options is not None:
                options.poly_pen.setColor(QColor(poly_p))

        poly_b = s.value(DrawToolBar.NameSpace +
                         "/Options/drawings/polygons/brush")
        if poly_b is not None:
            global PolyBrush
            PolyBrush = QBrush(QColor(poly_b))
            if options is not None:
                options.poly_brush.setColor(QColor(poly_b))

        point_w = s.value(DrawToolBar.NameSpace +
                          "/Options/drawings/points/width")
        if point_w is not None:
            global PointWidth
            PointWidth = int(point_w)
            if options is not None:
                options.point_width.setValue(PointWidth)

        point_p = s.value(DrawToolBar.NameSpace +
                          "/Options/drawings/points/pen")
        if point_p is not None:
            global PointPen
            PointPen = QPen(QColor(point_p))
            PointPen.setCapStyle(Qt.RoundCap)
            PointPen.setWidth(PointWidth)
            if options is not None:
                options.point_pen.setColor(QColor(point_p))

        line_w = s.value(DrawToolBar.NameSpace +
                         "/Options/drawings/lines/width")
        if line_w is not None:
            global LineWidth
            LineWidth = int(line_w)
            if options is not None:
                options.lines_width.setValue(LineWidth)

        line_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/lines/pen")
        if line_p is not None:
            global LinePen
            LinePen = QPen(QColor(line_p))
            LinePen.setCapStyle(Qt.RoundCap)
            LinePen.setWidth(LineWidth)
            if options is not None:
                options.lines_pen.setColor(QColor(line_p))

        measure_w = s.value(DrawToolBar.NameSpace +
                            "/Options/drawings/measures/width")
        if measure_w is not None:
            global MeasureWidth
            MeasureWidth = int(measure_w)
            if options is not None:
                options.measures_width.setValue(MeasureWidth)

        measure_p = s.value(DrawToolBar.NameSpace +
                            "/Options/drawings/measures/pen")
        if measure_p is not None:
            global MeasurePen
            MeasurePen = QPen(QColor(measure_p))
            MeasurePen.setCapStyle(Qt.RoundCap)
            MeasurePen.setWidth(MeasureWidth)
            if options is not None:
                options.measures_pen.setColor(QColor(measure_p))

        measure_b = s.value(DrawToolBar.NameSpace +
                            "/Options/drawings/measures/brush")
        if measure_b is not None:
            global MeasureBrush
            MeasureBrush = QBrush(QColor(measure_b))
            if options is not None:
                options.measures_brush.setColor(QColor(measure_b))

        return

    @staticmethod
    def drawOnVideo(drawPtPos, drawLines, drawPolygon, drawMDistance,
                    drawMArea, drawCesure, painter, surface, gt):
        ''' Function to paint over the video '''
        # Draw clicked points on video
        for position, pt in enumerate(drawPtPos):
            DrawToolBar.drawPointOnVideo(position + 1, pt, painter, surface,
                                         gt)

        # Draw clicked lines on video
        if len(drawLines) > 1:
            for idx, pt in enumerate(drawLines):
                if pt[0] is None:
                    continue
                else:
                    DrawToolBar.drawLinesOnVideo(pt, idx, painter, surface, gt,
                                                 drawLines)

        # Draw clicked Polygons on video
        if len(drawPolygon) > 1:
            poly = []
            if any(None == x[1] for x in drawPolygon):
                for pt in drawPolygon:
                    if pt[0] is None:
                        DrawToolBar.drawPolygonOnVideo(poly, painter, surface,
                                                       gt)
                        poly = []
                        continue
                    poly.append(pt)
                last_occurence = len(drawPolygon) - drawPolygon[::-1].index(
                    [None, None, None])
                poly = []
                for pt in range(last_occurence, len(drawPolygon)):
                    poly.append(drawPolygon[pt])
                if len(poly) > 1:
                    DrawToolBar.drawPolygonOnVideo(poly, painter, surface, gt)
            else:
                DrawToolBar.drawPolygonOnVideo(drawPolygon, painter, surface,
                                               gt)

        # Draw Measure Distance on video
        # the measures don't persist in the video
        if len(drawMDistance) > 1:
            DrawToolBar.resetMeasureDistance()
            for idx, pt in enumerate(drawMDistance):
                if pt[0] is None:
                    DrawToolBar.resetMeasureDistance()
                    continue
                else:
                    DrawToolBar.drawMeasureDistanceOnVideo(
                        pt, idx, painter, surface, gt, drawMDistance)

        # Draw Measure Area on video
        # the measures don't persist in the video
        if len(drawMArea) > 1:
            poly = []
            if any(None == x[1] for x in drawMArea):
                for pt in drawMArea:
                    if pt[0] is None:
                        DrawToolBar.drawMeasureAreaOnVideo(
                            poly, painter, surface, gt)
                        poly = []
                        continue
                    poly.append(pt)
                last_occurence = len(drawMArea) - drawMArea[::-1].index(
                    [None, None, None])
                poly = []
                for pt in range(last_occurence, len(drawMArea)):
                    poly.append(drawMArea[pt])
                if len(poly) > 1:
                    DrawToolBar.drawMeasureAreaOnVideo(poly, painter, surface,
                                                       gt)
            else:
                DrawToolBar.drawMeasureAreaOnVideo(drawMArea, painter, surface,
                                                   gt)

        # Draw Censure
        if drawCesure:
            DrawToolBar.drawCensuredOnVideo(painter, drawCesure)
            return

        return

    @staticmethod
    def drawPointOnVideo(number, pt, painter, surface, gt):
        ''' Draw Points on Video '''
        if hasElevationModel():
            pt = GetLine3DIntersectionWithPlane(GetSensor(), pt,
                                                GetFrameCenter()[2])

        scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface)

        # don't draw something outside the screen.
        if scr_x < vut.GetXBlackZone(surface) or scr_y < vut.GetYBlackZone(
                surface):
            return

        if scr_x > vut.GetXBlackZone(surface) + vut.GetNormalizedWidth(
                surface) or scr_y > vut.GetYBlackZone(
                    surface) + vut.GetNormalizedHeight(surface):
            return

        center = QPoint(scr_x, scr_y)

        painter.setPen(PointPen)
        painter.drawPoint(center)
        painter.setFont(DrawToolBar.bold_12)
        painter.drawText(center + QPoint(5, -5), str(number))
        return

    @staticmethod
    def drawLinesOnVideo(pt, idx, painter, surface, gt, drawLines):
        ''' Draw Lines on Video '''
        if hasElevationModel():
            pt = GetLine3DIntersectionWithPlane(GetSensor(), pt,
                                                GetFrameCenter()[2])

        scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface)

        center = QPoint(scr_x, scr_y)

        painter.setPen(LinePen)

        if len(drawLines) > 1:
            try:
                pt = drawLines[idx + 1]
                if hasElevationModel():
                    pt = GetLine3DIntersectionWithPlane(
                        GetSensor(), pt,
                        GetFrameCenter()[2])
                scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface)
                end = QPoint(scr_x, scr_y)
                painter.drawLine(center, end)

                # Draw Start/End Points
                painter.setPen(DrawToolBar.white_pen)
                painter.drawPoint(center)
                painter.drawPoint(end)
            except Exception:
                None
        return

    @staticmethod
    def drawPolygonOnVideo(values, painter, surface, gt):
        ''' Draw Polygons on Video '''
        poly = []
        for pt in values:
            if hasElevationModel():
                pt = GetLine3DIntersectionWithPlane(GetSensor(), pt,
                                                    GetFrameCenter()[2])
            scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface)
            center = QPoint(scr_x, scr_y)
            poly.append(center)

        polygon = QPolygonF(poly)

        path = QPainterPath()
        path.addPolygon(polygon)

        painter.setPen(PolyPen)
        painter.drawPolygon(polygon)
        painter.fillPath(path, PolyBrush)
        painter.setPen(DrawToolBar.white_pen)
        painter.drawPoints(polygon)
        return

    @staticmethod
    def resetMeasureDistance():
        global RulerTotalMeasure
        RulerTotalMeasure = 0.0

    @staticmethod
    def drawMeasureDistanceOnVideo(pt, idx, painter, surface, gt,
                                   drawMDistance):
        ''' Draw Measure Distance on Video '''
        if hasElevationModel():
            pt = GetLine3DIntersectionWithPlane(GetSensor(), pt,
                                                GetFrameCenter()[2])

        scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface)

        center = QPoint(scr_x, scr_y)

        if len(drawMDistance) > 1:
            try:
                painter.setPen(MeasurePen)

                end_pt = drawMDistance[idx + 1]

                if hasElevationModel():
                    end_pt = GetLine3DIntersectionWithPlane(
                        GetSensor(), end_pt,
                        GetFrameCenter()[2])
                scr_x, scr_y = vut.GetInverseMatrix(end_pt[1], end_pt[0], gt,
                                                    surface)
                end = QPoint(scr_x, scr_y)
                painter.drawLine(center, end)

                painter.setFont(DrawToolBar.bold_12)

                distance = round(
                    sphere.distance((pt[0], pt[1]), (end_pt[0], end_pt[1])), 2)

                text = str(distance) + " m"
                global RulerTotalMeasure
                RulerTotalMeasure += distance

                # Line lenght
                painter.setPen(MeasurePen)
                painter.drawText(end + QPoint(5, -10), text)

                painter.setPen(DrawToolBar.white_pen)
                # Total lenght
                painter.drawText(end + QPoint(5, 10),
                                 str(round(RulerTotalMeasure, 2)) + " m")

                # Draw Start/End Points
                painter.drawPoint(center)
                painter.drawPoint(end)
            except Exception:
                None
        return

    @staticmethod
    def drawMeasureAreaOnVideo(values, painter, surface, gt):
        ''' Draw Measure Area on Video '''
        a_value = sphere.polygon_area([values])

        poly = []
        lat = []
        long = []
        for pt in values:
            if hasElevationModel():
                pt = GetLine3DIntersectionWithPlane(GetSensor(), pt,
                                                    GetFrameCenter()[2])
            scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface)
            center = QPoint(scr_x, scr_y)
            poly.append(center)

            lat.append(pt[0])
            long.append(pt[1])

        lat = list(dict.fromkeys(lat))
        long = list(dict.fromkeys(long))

        # Calculate Centroid Position
        scr_x, scr_y = vut.GetInverseMatrix(
            sum(long) / len(long),
            sum(lat) / len(lat), gt, surface)

        centroid = QPoint(scr_x, scr_y)

        # Create Poligon
        polygon = QPolygonF(poly)

        path = QPainterPath()
        path.addPolygon(polygon)

        painter.setFont(DrawToolBar.bold_12)

        painter.setPen(MeasurePen)
        painter.drawPolygon(polygon)
        painter.fillPath(path, MeasureBrush)
        painter.setPen(DrawToolBar.white_pen)
        painter.drawPoints(polygon)

        # Area
        if a_value >= 10000:
            painter.drawText(centroid,
                             str(round(a_value / 1000000, 2)) + " km²")
        else:
            painter.drawText(centroid, str(round(a_value, 2)) + " m²")
        return

    @staticmethod
    def drawCensuredOnVideo(painter, drawCesure):
        ''' Draw Censure on Video '''
        try:
            for geom in drawCesure:
                painter.setPen(DrawToolBar.black_pen)
                painter.setBrush(DrawToolBar.black_brush)
                painter.drawRect(geom[0].x(), geom[0].y(), geom[0].width(),
                                 geom[0].height())

        except Exception:
            None
        return

    @staticmethod
    def drawMagnifierOnVideo(widget, dragPos, source, painter):
        ''' Draw Magnifier on Video '''
        oldTransform = painter.transform()
        painter.setTransform(oldTransform)
        painter.setBrush(DrawToolBar.transparent_brush)
        dim = min(widget.width(), widget.height())

        magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3)
        radius = magnifierSize / 2
        ring = radius - 15
        box = QSize(magnifierSize, magnifierSize)

        center = dragPos - QPoint(0, radius)
        center += QPoint(0, radius / 2)
        corner = center - QPoint(radius, radius)

        xy = center * MAX_FACTOR - QPoint(radius, radius)

        # only set the dimension to the magnified portion
        zoomPixmap = QPixmap(box)
        zoomPixmap.fill(Qt.black)

        painter_p = QPainter(zoomPixmap)
        painter_p.setRenderHint(QPainter.HighQualityAntialiasing)
        painter_p.translate(-xy)
        painter_p.scale(MAX_FACTOR, MAX_FACTOR)
        painter_p.drawImage(widget.surface.videoRect(), source,
                            widget.surface.sourceRect())

        painter_p.end()

        clipPath = QPainterPath()
        center = QPointF(center)

        # Shape Type
        if TYPE_MAGNIFIER == 0:
            # Square
            clipPath.addRect(center.x(), center.y(), magnifierSize,
                             magnifierSize)
            clipPath.translate(-radius, -radius)
        else:
            # Circle
            clipPath.addEllipse(center, ring, ring)

        painter.setClipPath(clipPath)
        painter.drawPixmap(corner, zoomPixmap)
        painter.setPen(DrawToolBar.glass_pen)
        painter.drawPath(clipPath)
        return

    @staticmethod
    def drawStampOnVideo(widget, painter):
        ''' Draw Stamp Confidential on Video '''
        painter.drawPixmap(widget.surface.videoRect(),
                           DrawToolBar.confidential,
                           widget.surface.sourceRect())
Exemplo n.º 17
0
    # print(qgs.libraryPaths())
    # print(QgsProviderRegistry.instance().pluginList())

    # wrap in dialog
    dlg = QDialog()
    layout = QVBoxLayout(dlg)
    image_lbl = QLabel(dlg)
    layout.addWidget(image_lbl)
    # layout.setMargin(0)

    # First WMS, with tileset
    image = render_wms_to_image(xyz=False)
    if image.isNull():
        qgs.exitQgis()
        sys.exit(1)
    image_lbl.setPixmap(QPixmap.fromImage(image))

    dlg.setWindowTitle('WMS Scene Render Test')
    dlg.exec_()

    # Then XYZ
    image = render_wms_to_image(xyz=True)

    # image = thumbnail_image(item_type="PSScene4Band", item_id="20160831_143848_0c79")
    if image.isNull():
        qgs.exitQgis()
        sys.exit(1)
    image_lbl.setPixmap(QPixmap.fromImage(image))

    # b1 = QPushButton("ok", dlg)
Exemplo n.º 18
0
    def hacer5(self):
        self.tempdir = configuracioQvista.tempdir
        fic_tmp = os.path.join(self.tempdir, "temporal.png")
        self.pixmap = QPixmap(fic_tmp)
        # self.pixmap=self.canvas.grab() # no acaba de ir bien, me carga en pixmap tambien el circulo pintado
        # tamaño del pixmap
        hp = self.pixmap.height()  # alto imagen
        wp = self.pixmap.width()  # ancho imagen salvada
        # radio.
        if hp < wp:
            self.rP = hp / 2
        else:
            self.rP = wp / 2

        self.xcP = wp / 2
        self.ycP = hp / 2
        # self.rP = math.sqrt(math.pow((self.xcP-self.xrP), 2) + math.pow((self.ycP-self.yrP), 2))  # radio pantalla
        pcX = self.xcP - self.rP
        pcY = self.ycP - self.rP  # punto inicio crop
        self.an = 2 * self.rP
        self.al = self.an  # an, ancho para crop   al, alto para crop
        # escala= self.rP /self.rM                                                   # escala, como relacion de radiopantalla a radiomundo
        # pmin= QPoint();
        # pmin.setX(pcX);
        # pmin.setY(pcY+self.al);
        # self.Pmin = self.toMapCoordinates(pmin)
        # pmax= QPoint();
        # pmax.setX(pcX+self.an);
        # pmax.setY(pcY);
        # self.Pmax = self.toMapCoordinates(pmax)

        # calculo area de recorte para hacer el crop
        rect = QRect(pcX, pcY, self.an, self.al)
        # hago crop
        cropped_pixmap = self.pixmap.copy(rect)

        # escalo el pixmap al tamaño que quiero
        self.scaled_pixmap = cropped_pixmap.scaled(
            self.lado, self.lado, Qt.KeepAspectRatioByExpanding,
            Qt.SmoothTransformation)
        # de pixmap a image
        image = QImage(self.scaled_pixmap.toImage())
        image = image.convertToFormat(QImage.Format_ARGB32)

        # preparo imagen de salida transparente y del tamaño del de entrada....
        out_img = QImage(image.width(), image.width(), QImage.Format_ARGB32)
        out_img.fill(Qt.transparent)

        # Create a texture brush and paint a circle with the original image onto
        # the output image: Chapeau!!
        brush = QBrush(image)  # Create texture brush
        painter = QPainter(out_img)  # Paint the output image
        painter.setBrush(brush)  # Use the image texture brush
        # painter.setPen(Qt.NoPen)     # Don't draw an outline
        # pen= QPen(QColor(121,144,155),  1, Qt.SolidLine)    #qVista claro
        pen = QPen(self.color, 1, Qt.SolidLine)  #qVista claro
        painter.setPen(pen)
        painter.setRenderHint(QPainter.Antialiasing, True)  # Use AA
        painter.drawEllipse(0, 0, image.width(),
                            image.width())  # Actually draw the circle
        painter.end()  # We are done (segfault if you forget this)

        # de out_img a pixmap
        self.scaled_pixmap = QPixmap.fromImage(out_img)

        # muestro ese pixmap en label...
        self.label.setPixmap(self.scaled_pixmap)

        # y lo salvo como temporal2
        fic_tmp = os.path.join(self.tempdir, "temporal2.png")
        self.fileName = fic_tmp

        if self.fileName:
            # Guardo el pixmap como png
            self.scaled_pixmap.save(self.fileName)
            # Calculo info para el PQW
            # rango mundo x e y

            xdist = self.xmax - self.xmin
            ydist = self.ymax - self.ymin
            # ancho y alto de la imagen
            iheight = self.scaled_pixmap.height()
            iwidth = self.scaled_pixmap.width()

            # Preparo nombre del PGW
            split_nombre = os.path.splitext(self.fileName)
            filenamePgw = split_nombre[0] + ".pgw"

            # Escribo PGW
            wld = open(filenamePgw, "w")
            wld.writelines("%s\n" % (xdist / iwidth))
            wld.writelines("0.0\n")
            wld.writelines("0.0\n")
            wld.writelines("%s\n" % (ydist / iheight))
            wld.writelines("%s\n" % self.xmin)
            wld.writelines("%s\n" % self.ymin)
            wld.close

        # #  muestro datos de georeferenciacion
        # literal= "xmin,ymin=" + str(round(self.Pmin.x(),3)) +"  "+ str(round(self.Pmin.y(),3))
        # self.parent.xmin_ymin.setText(literal)
        # literal= "xmax,ymax=" + str(round(self.Pmax.x(),3)) +"  "+ str(round(self.Pmax.y(),3))
        # self.parent.xmax_ymax.setText(literal)

        try:
            self.reset()
        except:
            pass