def draw_image(self, x, y, width, height, path, crop=None):
     image = QImage(path)
     rect = QRectF(self.pts(x), self.pts(y), self.pts(width),
                   self.pts(height))
     if crop is None:
         self.painter.drawImage(rect, image)
     else:
         sx, sy, sw, sh = crop
         source_rect = QRectF(
             sx * image.width(),
             sy * image.height(),
             sw * image.width(),
             sh * image.height(),
         )
         self.painter.drawImage(rect, image, source_rect)
 def _finish_loading_image(self, image: QImage, path: str):
     path = Path(path)
     self.loading = False
     if image.width() == 0:
         self.clear_image()
         return
     self.image = image
     self.path = path
     orientation, flip = load_exif_data(path)
     metadata = self.metadata_storage_engine.load(Path(path))
     if metadata is None:
         metadata = Metadata(original_orientation=orientation)
     self.flip = flip
     self.original_orientation = metadata.original_orientation
     self.suggested_orientation = None
     self.orientation_was_selected_manually = metadata.orientation_was_selected_manually
     self.orientation_was_selected_automatically = metadata.orientation_was_selected_automatically
     self.set_orientation(orientation)
     self.repaint()
     self._image_workers.schedule_suggestion_prediction(
         path=path,
         orientation=orientation,
         image=image,
         result_changed_callback=self.update_suggested_orientation,
         processing_started_callback=self.
         orientation_prediction_processing_started,
         processing_completed_callback=self.
         orientation_prediction_processing_completed,
     )
     self.update_progressbar()
Beispiel #3
0
    def setup_category_view(self):
        self.current_view = StepViews.CATEGORY_VIEW
        i, j = 0, 0

        for category in self.categories:
            data = urllib.request.urlopen(category["icons"][0]["url"]).read()

            label = ClickableLabel(self)
            label.setScaledContents(True)
            label.setFixedSize(190, 190)
            label.dataId = category["id"]
            label.clicked.connect(self.category_click)

            image = QImage(32, 32, QImage.Format_RGB32)
            image.loadFromData(data)

            painter = QPainter(image)
            painter.setPen(QPen(QColor("white")))
            painter.setFont(QFont("Roboto", 22, QFont.Bold))
            painter.drawText(QRect(0, 0, image.width(),
                                   image.height() - 25),
                             Qt.AlignCenter | Qt.AlignBottom, category["name"])
            painter.end()

            pixmap = QPixmap(image)
            label.setPixmap(pixmap)
            self.layout.addWidget(label, i, j)

            j += 1

            if j % 4 == 0:
                i += 1
                j = 0
Beispiel #4
0
    def scaleImage(self, pixels, path):
        dircache = QDir(self.mDir + QDir.separator() + "imagecache")
        if dircache.exists() == False:
            s = QDir(self.mDir)
            s.mkdir("imagecache")

        ima = QImage(path)
        wids = ima.width()
        heis = ima.height()
        if (wids > pixels or heis > pixels):
            imarescale = ima.scaledToWidth(
                pixels, Qt.SmoothTransformation) if (
                    wids > heis) else ima.scaledToHeight(
                        pixels, Qt.SmoothTransformation)

            newImagePath = dircache.path() + QDir.separator(
            ) + "_temp_scaled_" + QFileInfo(path).fileName()
            imawriter = QImageWriter()
            imawriter.setFileName(newImagePath)
            #    imawriter.setFormat("png");
            if (imawriter.write(imarescale)):
                #qDebug()<<"si path"<<newImagePath
                return newImagePath
            else:
                #qDebug()<<"no path"<<newImagePath;
                return path

        return path
Beispiel #5
0
 def show_image(self,
                pattern,
                use_grayscale=False,
                alpha=0,
                beta=0,
                gamma=0):
     # if not self.connected:
     #     self.print_text_signal.emit("Impossible to show image: projector is not connected!")
     #     return
     loaded_image = QImage(pattern).convertToFormat(
         QImage.Format.Format_RGB32)
     values = loaded_image.bits()
     pixel_values = np.array(values).reshape(loaded_image.height(),
                                             loaded_image.width(), 4)
     if use_grayscale:
         thickness = DLPColorCalibrator.my_log_function(
             1, alpha, beta, gamma)
         tmp, corrected_values = DLPColorCalibrator.my_color_correction(
             pixel_values, alpha, beta, gamma, thickness)
         corrected_values_tr = corrected_values.copy()
         corrected_image = QImage(corrected_values_tr,
                                  corrected_values_tr.shape[1],
                                  corrected_values_tr.shape[0],
                                  QImage.Format_RGB32)
         self.img = QPixmap(corrected_image)
     else:
         self.img = QPixmap(loaded_image)
     if self.horizontal_mirror:
         self.img = self.img.transformed(QTransform().scale(-1, 1))
     if self.vertical_mirror:
         self.img = self.img.transformed(QTransform().scale(1, -1))
     self.display_image_signal.emit(self.img)
     self.setPixmap(self.img)
Beispiel #6
0
 def qimage_to_numpy(self, image: QImage) -> Image:
     image = image.convertToFormat(QImage.Format.Format_RGB32)
     width = image.width()
     height = image.height()
     ptr = image.constBits()
     arr = np.array(ptr).reshape((height, width, 4))[:, :, :3]
     return arr
Beispiel #7
0
 def setImage(self, dir):
     img = QImage(dir)
     self.img_w = img.width()
     self.img_h = img.height()
     self.img = cv2.imread(dir)
     self.qp.begin(self.backView)
     self.qp.drawImage(self.backView.rect(), img)
     self.qp.end()
Beispiel #8
0
    def QImageToCV(image: QImage) -> ndarray:
        if image.format() != QImage.Format_RGB888:
            image = image.convertToFormat(QImage.Format_RGB888)

        width = image.width()
        height = image.height()

        ptr = image.bits()
        arr = array(ptr).reshape(height, width, 3)

        return arr
Beispiel #9
0
    def __init__(self, object_set: int, palette_index: int):
        png = QImage(str(data_dir.joinpath("gfx.png")))

        png.convertTo(QImage.Format_RGB888)

        rows_per_object_set = 256 // 64

        y_offset = 12 * rows_per_object_set * Block.HEIGHT

        self.png_data = png.copy(QRect(0, y_offset, png.width(), png.height() - y_offset))

        self.palette_group = load_palette_group(object_set, palette_index)
Beispiel #10
0
def testImage():
    width, height = 100, 100
    im = QImage(width, height, QImage.Format_ARGB32)

    for x in range(im.width()):
        for y in range(im.height()):
            if x % 2 == 0:
                im.setPixel(x, y, QColor('white').rgb())
            else:
                im.setPixel(x, y, QColor('black').rgb())
            # im.setPixel(x, y, QColor(255, x*2.56, y*2.56, 255).rgb())
    im.save('test.png')
Beispiel #11
0
 def requestImage(self, url, size, requestedSize):
     url = QUrl(url)
     image = QImage(url.toLocalFile())
     width, height = image.width(), image.height()
     if size:
         size.setWidth(width)
         size.setHeight(height)
     if requestedSize.width() > 0:
         width = requestedSize.width()
     if requestedSize.height() > 0:
         height = requestedSize.height()
     return image.scaled(min(width, THUMBNAIL_SIZE),
                         min(height, THUMBNAIL_SIZE), Qt.KeepAspectRatio)
Beispiel #12
0
 def show_image(self, cv_image):
     self.resize(200, 200)
     rgb_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
     h, w, ch = rgb_image.shape
     bytes_per_line = ch * w
     qt_image = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888)
     img_w = qt_image.width()
     img_h = qt_image.height()
     proportion = img_w / img_h
     self.resize(self.width() * proportion, self.height())
     qt_image = qt_image.scaled(self.width(), self.height())
     self.setPixmap(QPixmap(qt_image))
     self.parent_node_instance.update_shape()
Beispiel #13
0
 def requestImage(self, url, size, requestedSize):
     url = QUrl(url)
     image = QImage(url.toLocalFile())
     width, height = image.width(), image.height()
     if size:
         size.setWidth(width)
         size.setHeight(height)
     if requestedSize.width() > 0:
         width = requestedSize.width()
     if requestedSize.height() > 0:
         height = requestedSize.height()
     return image.scaled(min(width, THUMBNAIL_SIZE),
                         min(height, THUMBNAIL_SIZE), Qt.KeepAspectRatio)
Beispiel #14
0
    def initUI(self):
        image = QImage(self.file_name)
        if image.width() > image.height():
            pixmap = QPixmap(image.scaledToWidth(self.length_max))
        else:
            pixmap = QPixmap(image.scaledToHeight(self.length_max))

        label = QLabel(self)
        label.setPixmap(pixmap)

        vbox = QVBoxLayout(self)
        vbox.addWidget(label)
        vbox.setSizeConstraint(QLayout.SetFixedSize)
        self.setLayout(vbox)
Beispiel #15
0
    def __load_image(self, data):
        # type: (QByteArray) -> None
        """Creates and caches the QImage from the data.

        :param data: the data returned by the network request for the image
        """
        image = QImage()
        loaded = image.loadFromData(data)
        if loaded:
            width = image.width()
            height = image.height()
            size = (width, height)
            centre_x = width / 2
            centre_y = height / 2
            centre = (centre_x, centre_y)
            _IMAGE_CACHE[self] = image
            _PIXMAP_CACHE[self] = {}

            # Cache the full-size pixmap
            get_pixmap(self, centre, size, size)
Beispiel #16
0
def qimg_to_rgb_arr(qimg: QImage) -> RGBArrayF:
    """Convert a :class:`QtGui.QImage` to an :data:`RGBArrayF`
    """
    fmt = QImage.Format_RGB32
    if qimg.format() != fmt:
        qimg = qimg.convertToFormat(fmt)

    width, height = qimg.width(), qimg.height()
    num_pixels = width * height

    bfr = qimg.constBits()
    int_arr = np.frombuffer(bfr, dtype=np.uint8, count=num_pixels * 4)

    bgra_arr = int_arr.reshape((height, width, 4)) / 255

    # Format_RGB32 stored as 0xffRRGGBB
    # so take only the first 3 items but in reverse
    rgb_arr = bgra_arr[..., 2::-1]

    return rgb_arr
Beispiel #17
0
    def populateScene(self):

        self.scene = QGraphicsScene(self)

        image = QImage(":/qt4logo.png")
        xx: int = 0
        nitems: int = 0
        for i in range(-11000, 11000, 110):
            xx += 1
            yy: int = 0
            for j in range(-7000, 7000, 70):
                yy += 1
                x = (i + 11000) / 22000.0
                y = (j + 7000) / 14000.0

                color = QColor(
                    image.pixel(int(image.width() * x),
                                int(image.height() * y)))
                item = Chip(color, xx, yy)
                item.setPos(QPointF(i, j))
                self.scene.addItem(item)
                nitems += 1
    def saveYoloFormat(self,
                       filename,
                       shapes,
                       imagePath,
                       imageData,
                       classList,
                       lineColor=None,
                       fillColor=None,
                       databaseSrc=None):
        imgFolderPath = os.path.dirname(imagePath)
        imgFolderName = os.path.split(imgFolderPath)[-1]
        imgFileName = os.path.basename(imagePath)
        #imgFileNameWithoutExt = os.path.splitext(imgFileName)[0]
        # Read from file path because self.imageData might be empty if saving to
        # Pascal format
        image = QImage()
        image.load(imagePath)
        imageShape = [
            image.height(),
            image.width(), 1 if image.isGrayscale() else 3
        ]
        writer = YOLOWriter(imgFolderName,
                            imgFileName,
                            imageShape,
                            localImgPath=imagePath)
        writer.verified = self.verified

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

        writer.save(targetFile=filename, classList=classList)
        return
Beispiel #19
0
class Mp4Sink:
    """A QRemoteDesktop Mock."""
    def __init__(self):
        self._buffer: QImage = None

    @property
    def screen(self):
        return self._buffer

    def notifyImage(self, x: int, y: int, img: QImage, w: int, h: int):
        p = QPainter(self._buffer)
        p.drawImage(x, y, img, 0, 0, w, h)

    def resize(self, w: int, h: int):
        self._buffer = QImage(w, h, QImage.Format_ARGB32_Premultiplied)

    def width(self) -> int:
        return self._buffer.width()

    def height(self) -> int:
        return self._buffer.height()

    def update(self):
        pass
Beispiel #20
0
    def _draw_scoreboard(self, painter, sizes, voter_num):
        scale = self.details.scale
        contest = self.details.contest

        # Display scoreboard background rectangle
        self._draw_rectangle(painter, QPoint(0, 0),
                             QPoint(sizes.width, sizes.height),
                             self.colors.light_grey)

        # Display voter details
        self._draw_rectangle(painter, QPoint(0, 0),
                             QPoint(sizes.width, 30 * scale), self.colors.main)
        self._draw_text(
            painter, QPoint(10 * scale, 15 * scale),
            "Now Voting: {} ({}/{})".format(contest.voters[voter_num],
                                            voter_num + 1, contest.num_voters),
            self.fonts.voter_header, self.colors.white_text, Qt.AlignLeft)

        # Display contest title
        self._draw_rectangle(painter, QPoint(0, 30 * scale),
                             QPoint(sizes.width, 30 * scale),
                             self.colors.accent)
        self._draw_text(painter, QPoint(10 * scale, 45 * scale),
                        "{} Results".format(self.details.title),
                        self.fonts.contest_header, self.colors.accent_text,
                        Qt.AlignLeft)

        # Draw background rectangles for entry details
        left_col = int(
            self.contest.num_entries / 2) + self.contest.num_entries % 2
        right_col = self.contest.num_entries - left_col
        self._draw_rectangle(painter,
                             QPoint(10 * scale, 70 * scale),
                             QPoint(sizes.rectangle,
                                    0 * scale + 35 * scale * left_col),
                             self.colors.white,
                             border=self.colors.grey_text,
                             border_width=0.5 * scale)
        self._draw_rectangle(painter,
                             QPoint(20 * scale + sizes.rectangle, 70 * scale),
                             QPoint(sizes.rectangle,
                                    0 * scale + 35 * scale * right_col),
                             self.colors.white,
                             border=self.colors.grey_text,
                             border_width=0.5 * scale)

        entries = self.contest.results_after_voter(voter_num)
        for i, entry in enumerate(entries):
            if i < left_col:
                x_offset = 0
                y_offset = i
            else:
                x_offset = 10 * scale + sizes.rectangle
                y_offset = i - left_col

            # Display the entry's country flag
            if self.details.display_flags:
                try:
                    flag = QImage(
                        self.app_context.get_resource(join(
                            "flags", entry.flag)))
                    flag = flag.scaledToWidth(20 * scale,
                                              Qt.SmoothTransformation)
                    self._draw_rectangle(
                        painter,
                        QPoint(
                            27 * scale - flag.width() / 2.0 + x_offset,
                            87 * scale - flag.height() / 2.0 +
                            35 * scale * y_offset),
                        QPoint(flag.width() + 0.5,
                               flag.height() + 0.5),
                        self.colors.white,
                        border=self.colors.grey_text,
                        border_width=0.5 * scale)
                    painter.drawImage(
                        QPoint(
                            27 * scale - flag.width() / 2.0 + x_offset,
                            87 * scale - flag.height() / 2.0 +
                            35 * scale * y_offset), flag)
                except FileNotFoundError:
                    continue

            # Display entry details
            self._draw_text(
                painter,
                QPoint(20 * scale + x_offset + sizes.flag_offset,
                       80 * scale + 35 * scale * y_offset), entry.country,
                self.fonts.country, self.colors.country_text, Qt.AlignLeft)
            self._draw_text(
                painter,
                QPoint(20 * scale + x_offset + sizes.flag_offset,
                       94 * scale + 35 * scale * y_offset),
                "{} – {}".format(entry.artist, entry.song),
                self.fonts.entry_details, self.colors.black, Qt.AlignLeft)

            # Display the entry's total number of received points
            if entry.dq_statuses[voter_num]:
                self._draw_rectangle(
                    painter,
                    QPoint(
                        30 * scale + x_offset + sizes.flag_offset +
                        sizes.entry_details,
                        77 * scale + 35 * scale * y_offset),
                    QPoint(29 * scale, 20 * scale), self.colors.grey_text)
                self._draw_text(
                    painter,
                    QPoint(
                        44.5 * scale + x_offset + sizes.flag_offset +
                        sizes.entry_details,
                        87 * scale + 35 * scale * y_offset),
                    "{}".format(entry.display_pts[voter_num]),
                    self.fonts.total_pts, self.colors.black, Qt.AlignHCenter)
            else:
                self._draw_rectangle(
                    painter,
                    QPoint(
                        30 * scale + x_offset + sizes.flag_offset +
                        sizes.entry_details,
                        77 * scale + 35 * scale * y_offset),
                    QPoint(29 * scale, 20 * scale), self.colors.main)
                self._draw_text(
                    painter,
                    QPoint(
                        44.5 * scale + x_offset + sizes.flag_offset +
                        sizes.entry_details,
                        87 * scale + 35 * scale * y_offset),
                    "{}".format(entry.display_pts[voter_num]),
                    self.fonts.total_pts, self.colors.white_text,
                    Qt.AlignHCenter)

            # Display the entry's number of points received by the current voter
            if len(entry.votes[voter_num]) > 0:
                self._draw_rectangle(
                    painter,
                    QPoint(
                        59 * scale + x_offset + sizes.flag_offset +
                        sizes.entry_details,
                        77 * scale + 35 * scale * y_offset),
                    QPoint(24 * scale, 20 * scale), self.colors.accent)

                try:
                    votes_string = int(float(entry.votes[voter_num]))
                except ValueError:
                    votes_string = entry.votes[voter_num]
                self._draw_text(
                    painter,
                    QPoint(
                        71 * scale + x_offset + sizes.flag_offset +
                        sizes.entry_details,
                        87 * scale + 35 * scale * y_offset), str(votes_string),
                    self.fonts.awarded_pts, self.colors.accent_text,
                    Qt.AlignHCenter)

            # Draw a dividing line between entries
            if i + 1 != left_col and i + 1 != self.contest.num_entries:
                painter.setPen(QPen(self.colors.grey_text, 0.5 * scale))
                painter.drawLine(
                    QPoint(10 * scale + x_offset,
                           104.5 * scale + 35 * scale * y_offset),
                    QPoint(10 * scale + x_offset + sizes.rectangle,
                           104.5 * scale + 35 * scale * y_offset))
Beispiel #21
0
class View(QWidget):
    previous = Signal()
    next = Signal()

    def __init__(self, window):
        super(View, self).__init__(window)

        self.setFocusPolicy(Qt.StrongFocus)
        self.shiftKey = False
        self.ctrlKey = False
        self.lastMousePos = QPoint()
        self.lastTabletPos = QPoint()
        self.mode = 'add'
        self.maskOnly = False

        self.refresh = QTimer(self)
        self.refresh.setSingleShot(True)
        self.refresh.timeout.connect(self.repaint)

        self.addCursor = makeCursor('images/cursor-add.png',
                                    QColor.fromRgbF(0.5, 0.5, 1.0))
        self.delCursor = makeCursor('images/cursor-del.png',
                                    QColor.fromRgbF(1.0, 0.5, 0.5))
        self.setCursor(self.addCursor)

        self.imagefile = None
        self.maskfile = None
        self.image = QImage()
        self.mask = QImage(self.image.size(), QImage.Format_RGB32)
        self.mask.fill(Qt.black)
        self.changed = False
        self.update()

        self.path = list()

        self.load_threads = QThreadPool()
        self.load_threads.setMaxThreadCount(4)

    def load(self, filename):
        self.load_threads.start(LoadTask(self, filename))

    def save(self):
        if self.maskfile and self.changed:
            self.load_threads.waitForDone()
        if self.maskfile and self.changed:
            bitmap = self.mask.createMaskFromColor(
                QColor.fromRgbF(1.0, 0.0, 1.0).rgb())
            bitmap.save(str(self.maskfile), "PNG")
            self.changed = False

    def update(self):
        widgetRatio = self.width() / self.height()
        aspectRatio = self.image.width() / max(1, self.image.height())
        if aspectRatio >= widgetRatio:
            width = self.width()
            height = self.width() / aspectRatio
        else:
            width = self.height() * aspectRatio
            height = self.height()
        self.rc = QRectF((self.width() - width) / 2.0,
                         (self.height() - height) / 2.0, width, height)
        self.repaint()

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

    def paintEvent(self, event):
        p = QPainter(self.mask)
        for (mode, p1, p2, weight) in self.path:
            if mode == 'add':
                p.setPen(
                    QPen(QColor.fromRgbF(1.0, 0.0, 1.0), (weight * 10.0)**2,
                         Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
            else:
                p.setPen(
                    QPen(QColor.fromRgbF(0.0, 0.0, 0.0), (weight * 10.0)**2,
                         Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
            p.drawLine(realCoords(p1, self.mask.rect()),
                       realCoords(p2, self.mask.rect()))
            self.changed = True
        self.path = list()
        p.end()

        p = QPainter(self)
        p.setCompositionMode(QPainter.CompositionMode_SourceOver)
        if not self.maskOnly:
            p.drawImage(self.rc, self.image)
            p.setCompositionMode(QPainter.CompositionMode_Plus)
        p.drawImage(self.rc, self.mask)
        p.end()

    def closeEvent(self, event):
        self.refresh.stop()
        event.accept()

    def enterEvent(self, event):
        self.setFocus(Qt.OtherFocusReason)

    def keyPressEvent(self, event):
        k = event.key()
        if k == Qt.Key_Shift:
            self.shiftKey = True
        if k == Qt.Key_Control:
            self.ctrlKey = True

        if k == Qt.Key_Space:
            self.maskOnly = not self.maskOnly
            self.repaint()

    def keyReleaseEvent(self, event):
        k = event.key()
        mod = event.modifiers()
        if k == Qt.Key_Shift:
            self.shiftKey = False
        if k == Qt.Key_Control:
            self.ctrlKey = False

    def mousePressEvent(self, event):
        x = event.x()
        y = event.y()
        self.lastMousePos = event.pos()

        if event.button() == Qt.ExtraButton1:
            if self.mode == 'add':
                self.mode = 'del'
                self.setCursor(self.delCursor)
            else:
                self.mode = 'add'
                self.setCursor(self.addCursor)
        elif event.button() == Qt.ExtraButton2:
            self.maskOnly = not self.maskOnly
            self.repaint()
        elif event.button() == Qt.ExtraButton3:
            self.previous.emit()
        elif event.button() == Qt.ExtraButton4:
            self.next.emit()

    def mouseMoveEvent(self, event):
        x = event.x()
        y = event.y()
        dx = x - self.lastMousePos.x()
        dy = y - self.lastMousePos.y()
        self.lastMousePos = event.pos()

        # if event.buttons() & Qt.LeftButton:
        # elif event.buttons() & Qt.MiddleButton:
        # elif event.buttons() & Qt.RightButton:

    def wheelEvent(self, event):
        dx = event.angleDelta().x() / 8
        dy = event.angleDelta().y() / 8
        # self.cameraZoom.emit(dy / 15)

    def tabletEvent(self, event):
        if event.device() == QTabletEvent.Stylus and event.pointerType(
        ) == QTabletEvent.Pen:
            if event.type() == QEvent.TabletPress:
                self.tabletPressEvent(event)
            elif event.type() == QEvent.TabletRelease:
                self.tabletReleaseEvent(event)
            elif event.type() == QEvent.TabletMove:
                if event.pressure() > 0.0:
                    self.tabletMoveEvent(event)
            else:
                print('tabletEvent', event.device(), event.type(),
                      event.pointerType())
        else:
            print('tabletEvent', event.device(), event.type(),
                  event.pointerType())

    def tabletPressEvent(self, event):
        if event.buttons() & Qt.LeftButton:
            self.lastTabletPos = normalizeCoords(event.posF(), self.rc)
        if event.buttons() & Qt.MiddleButton:
            if self.mode == 'add':
                self.mode = 'del'
                self.setCursor(self.delCursor)
            else:
                self.mode = 'add'
                self.setCursor(self.addCursor)
        if event.buttons() & Qt.RightButton:
            self.next.emit()

    def tabletReleaseEvent(self, event):
        self.lastTabletPos = normalizeCoords(event.posF(), self.rc)

    def tabletMoveEvent(self, event):
        self.path.append((self.mode, self.lastTabletPos,
                          normalizeCoords(event.posF(),
                                          self.rc), event.pressure()))
        self.lastTabletPos = normalizeCoords(event.posF(), self.rc)
        if not self.refresh.isActive():
            self.refresh.start(50)
Beispiel #22
0
class Picture(object):
    def __init__(self, path):
        super(Picture, self).__init__()

        self.path = path
        self.name = self.path.split("/")[-1]
        self.extension = os.path.splitext(self.path)[1]
        self.scale = 1.0
        self.image = QImage(self.path)
        self.thumbnail = self.image.scaled(QSize(110, 110),
                                           aspectMode=Qt.KeepAspectRatio,
                                           mode=Qt.SmoothTransformation)
        self.resolution = "Resolution: " + str(self.image.width()) + "x" + str(
            self.image.height()) + "px"

    def deletePicture(self):
        os.remove(self.path)

    def verticalFlip(self):
        self.image = self.image.mirrored(vertically=True, horizontally=False)
        self.thumbnail = self.image.scaled(QSize(110, 110),
                                           aspectMode=Qt.KeepAspectRatio,
                                           mode=Qt.SmoothTransformation)
        self.image.save(self.path)

    def horizontalFlip(self):
        self.image = self.image.mirrored(horizontally=True, vertically=False)
        self.thumbnail = self.image.scaled(QSize(110, 110),
                                           aspectMode=Qt.KeepAspectRatio,
                                           mode=Qt.SmoothTransformation)
        self.image.save(self.path)

    def zoomIn(self):
        self.scale = self.scale * 0.9

    def zoomOut(self):
        self.scale = self.scale * 1.1

    def rotateCW(self):
        transform = QTransform()
        transform.translate(self.image.width() / 2, self.image.height() / 2)
        transform.rotate(90)

        self.image = self.image.transformed(transform)
        self.image.save(self.path)
        self.thumbnail = self.image.scaled(QSize(110, 110),
                                           aspectMode=Qt.KeepAspectRatio,
                                           mode=Qt.SmoothTransformation)

    def rotateCCW(self):
        transform = QTransform()
        transform.translate(self.image.width() / 2, self.image.height() / 2)
        transform.rotate(-90)

        self.image = self.image.transformed(transform)
        self.image.save(self.path)

        self.thumbnail = self.image.scaled(QSize(110, 110),
                                           aspectMode=Qt.KeepAspectRatio,
                                           mode=Qt.SmoothTransformation)

    def saveImage(self):
        self.image.save(self.path)
Beispiel #23
0
class GalleryMiniature(QDialog):
    def __init__(self, pid=0, filename=0):
        super().__init__()
        #self.resize(800,600)
        self.pid = pid
        #print(filename)
        self.filename = filename
        layout = QHBoxLayout()
        self.baseLabel = MovableLabel()
        self.baseLabel.setFrameShape(QFrame.StyledPanel)
        self.baseLabel.setAlignment(Qt.AlignCenter)
        self.baseLabel.getRectCoords.connect(self.getRectCoordsSlot)
        self.miniLabel = QLabel()
        self.miniLabel.setAlignment(Qt.AlignCenter)
        self.base_image = QImage()
        self.mini_image = QImage()
        self.base_image_scaled = 0
        #self.filename = 0
        self.pix = 0
        self.currentIndex = 0
        self.real_size = 0

        layout.addWidget(self.baseLabel)
        layout.addWidget(self.miniLabel)

        def openMenu(position):
            menu = QMenu()
            openAction = menu.addAction('Открыть')
            saveAction = menu.addAction('Сохранить')
            menu.addSeparator()
            nextAction = menu.addAction('Следующий')
            menu.addSeparator()
            quitAction = menu.addAction('Выход')
            action = menu.exec_(self.mapToGlobal(position))

            if action == openAction:
                fileName = QFileDialog.getOpenFileName(
                    self, "Изображение", "photos",
                    "Фото (*.png *.jpg *.bmp *.JPG)")
                if len(fileName) > 1:
                    self.filename = fileName[0]
                    self.show_images()

            if action == saveAction:
                if self.filename:
                    print('os.path.basename(self.filename)')
                    path = os.path.basename(self.filename)
                    root_ext = os.path.splitext(path)
                    print(root_ext)
                    if self.pid:
                        root_ext = [str(pid) + '_001']
                    minifile = os.path.join(
                        os.path.join('photos', 'miniatures'),
                        root_ext[0] + '.png')
                    if self.pix:
                        self.pix.save(minifile, "PNG")
                        print(minifile)

            if action == nextAction:
                if self.base_image:
                    self.get_face_image()

            if action == quitAction:
                self.close()

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(openMenu)

        self.setLayout(layout)

        if self.filename:
            self.show_images()
        else:
            screen = QGuiApplication.primaryScreen()
            screenSize = screen.availableSize()
            sy = int((screenSize.height() - 20) / 4)
            sx = int((screenSize.width() - 20) / 4)
            self.setGeometry(sx, sy, int(screenSize.width() / 4),
                             int(screenSize.height() / 4))

    def show_images(self):
        #print(self.filename)
        self.base_image.load(self.filename)
        self.real_size = (self.base_image.width(), self.base_image.height())
        screen = QGuiApplication.primaryScreen()
        screenSize = screen.availableSize()
        sy = int((screenSize.height() - 20) / 2)
        sx = int((screenSize.width() - 20) / 2)
        if not self.base_image_scaled:
            self.base_image_scaled = self.base_image.scaled(
                sx, sy, Qt.KeepAspectRatio)
            self.setGeometry(sx - int(self.base_image_scaled.width()),
                             sy - int(self.base_image_scaled.height() / 2),
                             self.base_image_scaled.width() * 2,
                             self.base_image_scaled.height())
        else:
            self.base_image_scaled = self.base_image.scaled(
                int(self.base_image_scaled.width()),
                int(self.base_image_scaled.height()), Qt.KeepAspectRatio)
            self.setGeometry(sx - int(self.base_image_scaled.width()),
                             sy - int(self.base_image_scaled.height() / 2),
                             self.base_image_scaled.width() * 2,
                             self.base_image_scaled.height())
        self.baseLabel.setPixmap(QPixmap.fromImage(self.base_image_scaled))
        #self.miniLabel.setPixmap(QPixmap.fromImage(self.base_image))
        self.get_face_image()

    def getRectCoordsSlot(self, coords):
        print(coords)
        if self.base_image:
            self.get_face_image(coords)

    def get_round_miniature(self, image):
        size = (300, 300)
        img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        im = Image.fromarray(img)
        #im = image #Image.open(image.png)
        im = crop(im, size)
        im.putalpha(prepare_mask(size, 4))
        #im.save(filename)
        qim = ImageQt(im)
        self.pix = QPixmap.fromImage(qim)
        self.miniLabel.setPixmap(self.pix)
        #self.miniature = QImage(filename)

    def get_face_image(self, coords=0):
        with open(self.filename, 'rb') as f:
            chunk = f.read()
            chunk_arr = np.frombuffer(chunk, dtype=np.uint8)
        image = cv2.imdecode(chunk_arr, cv2.IMREAD_COLOR)
        if coords == 0:
            print(self.filename)

            #image = cv2.imread(self.filename)
            # !!!!!!!!!!!! Обязательно указать правильный путь к файлу !!!!!!!!!!!!
            # !!!!!!!!!!!! Путь до xml есть в https://github.com/opencv/opencv/tree/master/data/haarcascades !!!!!!!!!!!!
            face_cascade = cv2.CascadeClassifier(
                os.path.join('xml', 'haarcascade_frontalface_default.xml'))
            # !!!!!!!!!!!! Необходимо настроить параметры так как находит не все лица !!!!!!!!!!!!
            faces_coord = face_cascade.detectMultiScale(image,
                                                        scaleFactor=1.2,
                                                        minNeighbors=5,
                                                        minSize=(110, 110))

            if (len(faces_coord) > 0):
                for i, face in enumerate(faces_coord):
                    (x, y, w, h) = face
                    height, width, channels = image.shape
                    s = int(min(width * 0.1, height * 0.1))
                    if y - s >= 0:
                        y = y - s
                        h = h + s
                    if x - s >= 0:
                        x = x - s
                        w = w + s
                    h = h + s if y + h + s < height else h
                    w = w + s if x + w + s < width else w
                    if i == self.currentIndex:
                        crop_image = image[y:y + h, x:x + w]
                        #cv2.imshow("Face", crop_image)
                        self.get_round_miniature(crop_image)
                        break
                    #cv2.waitKey(0)
                #crop_image.save()
            self.currentIndex = 0 if self.currentIndex + 1 >= len(
                faces_coord) else self.currentIndex + 1
        else:
            if self.real_size:
                #image = cv2.imread(self.filename)
                #x_scale =  self.base_image.width() /  self.base_image_scaled.width()
                #y_scale = self.base_image.height() / self.base_image_scaled.height()
                x_scale = self.base_image.width(
                ) * self.base_image_scaled.width() / (
                    self.base_image_scaled.width() * self.baseLabel.width())
                y_scale = self.base_image.height(
                ) * self.base_image_scaled.height() / (
                    self.base_image_scaled.height() * self.baseLabel.height())
                print(
                    (int(coords[0][1] * y_scale), int(coords[1][1] * y_scale),
                     int(coords[0][0] * x_scale), int(coords[1][0] * x_scale)))
                crop_image = image[int(coords[0][1] *
                                       y_scale):int(coords[1][1] * y_scale),
                                   int(coords[0][0] *
                                       x_scale):int(coords[1][0] * x_scale)]
                self.get_round_miniature(crop_image)
class ScribbleArea(QWidget):
    def __init__(self, parent=None):
        super(ScribbleArea, self).__init__(parent)
        self.myPenColors = [
            QColor("green"),
            QColor("purple"),
            QColor("red"),
            QColor("blue"),
            QColor("yellow"),
            QColor("pink"),
            QColor("orange"),
            QColor("brown"),
            QColor("grey"),
            QColor("black")
        ]
        self.setAttribute(Qt.WA_AcceptTouchEvents)
        self.setAttribute(Qt.WA_StaticContents)
        self.image = QImage()

        self.modified = False

    def s_print(self):
        pass

    def clearImage(self):
        self.image.fill(qRgb(255, 255, 255))
        self.modified = True
        self.update()

    def openImage(self, fileName):
        loadedImage = QImage()
        if not loadedImage.load(fileName):
            return False

        newSize = loadedImage.size().expandedTo(self.size())
        self.resizeImage(loadedImage, newSize)
        self.image = loadedImage
        self.modified = False
        self.update()
        return True

    def saveImage(self, fileName, fileFormat):

        visibleImage = self.image.copy()
        self.resizeImage(visibleImage, self.size())

        if visibleImage.save(fileName, fileFormat):
            self.modified = False
            return True
        else:
            return False

    def paintEvent(self, event):
        painter = QPainter(self)
        rect = event.rect()
        painter.drawImage(rect.topLeft(), self.image, rect)

    def resizeEvent(self, event):
        if self.width() > self.image.width() or self.height(
        ) > self.image.height():
            newWidth = max(self.width() + 128, self.image.width())
            newHeight = max(self.height() + 128, self.image.height())
            self.resizeImage(self.image, QSize(newWidth, newHeight))
            self.update()
        super(ScribbleArea, self).resizeEvent(event)

    def resizeImage(self, image, newSize):
        if self.image.size() == newSize:
            return

        newImage = QImage(newSize, QImage.Format_RGB32)
        newImage.fill(qRgb(255, 255, 255))
        painter = QPainter(newImage)
        painter.drawImage(QPoint(0, 0), self.image)
        self.image = newImage

    #
    # def print(self, )
    # {
    # #ifndef QT_NO_PRINTER:
    #     QPrinter printer(QPrinter.HighResolution)
    #
    #     QPrintDialog *printDialog = new QPrintDialog(&printer, this)
    #     if (printDialog.exec() == QDialog.Accepted) {
    #         QPainter painter(&printer)
    #         QRect rect = painter.viewport()
    #         QSize size = self.image.size()
    #         size.scale(rect.size(), Qt.KeepAspectRatio)
    #         painter.setViewport(rect.x(), rect.y(), size.width(), size.height())
    #         painter.setWindow(self.image.rect())
    #         painter.drawImage(0, 0, image)
    #     }
    # #endif // QT_NO_PRINTER
    # }
    #
    def event(self, event):
        if event.type() == QEvent.TouchBegin or event.type(
        ) == QEvent.TouchUpdate or event.type() == QEvent.TouchEnd:
            touchPoints = event.touchPoints()
            for touchPoint in touchPoints:
                if touchPoint.state() == Qt.TouchPointStationary:
                    continue
                else:
                    rect = touchPoint.rect()
                    if rect.isEmpty():
                        diameter = 50 * touchPoint.pressure()
                        rect.setSize(QSizeF(diameter, diameter))

                    painter = QPainter(self.image)
                    painter.setPen(Qt.NoPen)
                    painter.setBrush(self.myPenColors[touchPoint.id() %
                                                      len(self.myPenColors)])
                    painter.drawEllipse(rect)
                    painter.end()

                    self.modified = True
                    rad = 2
                    self.update(rect.toRect().adjusted(-rad, -rad, +rad, +rad))

        else:
            return super(ScribbleArea, self).event(event)
        return True
Beispiel #25
0
class Bot(QQuickPaintedItem):
    def __init__(self, parent=None):
        super(Bot, self).__init__(parent)

        self._map = None
        self.image = QImage(300, 300, QImage.Format_RGBA8888)
        self.image.fill('#000000ff')
        self.timer = QTimer()
        self.position = QPoint()
        self.around = None
        self.angle = 0
        self.last_front = False
        self.timer.timeout.connect(lambda: self.drawCircle(self.position))

    def paint(self, painter):
        painter.drawImage(QRect(0, 0, self.width(), self.height()), self.image)

    def setMap(self, map: Map):
        if not map:
            return
        print('Map', map)
        self._map = map
        self._map.clicked.connect(self.handleClick)
        self.image = QImage(self.map.image.width(), self.map.image.height(),
                            QImage.Format_RGBA8888)
        self.image.fill('#000000ff')

    def getMap(self) -> Map:
        return self._map

    map = Property(Map, getMap, setMap)

    @Slot(QPoint)
    def handleClick(self, point: QPoint):
        self.position = point
        self.around = False
        self.drawCircle(point)
        self.timer.start(100)

    def mousePressEvent(self, event):
        a, b = event.pos().x() * self.image.width() / self.width(), event.pos(
        ).y() * self.image.height() / self.height()

    def mouseMoveEvent(self, event):
        a, b = event.pos().x() * self.image.width() / self.width(), event.pos(
        ).y() * self.image.height() / self.height()

    @Slot(QPoint)
    def drawCircle(self, point: QPoint):
        a = point.x()
        b = point.y()
        angle_step_size = 64
        radius = 90
        initPoint = QPoint(-1, -1)
        finalPoint = initPoint
        firstPoint = finalPoint
        self.image.fill('#000000ff')
        painter = QPainter(self.image)
        lidarPoints = []
        painter.setPen('#00ff00')
        painter.drawRect(point.x() - 1, point.y() - 1, 2, 2)
        front = QPoint(math.cos(self.angle), math.sin(self.angle))
        self.image.setPixelColor(point + front, QColor('#0000ff'))

        painter.setPen('#ff0000')
        for step in range(0, angle_step_size - 1):
            angle = 2 * math.pi * step / angle_step_size + self.angle
            initPoint = finalPoint
            for r in range(1, radius):
                x = point.x() + r * math.cos(angle)
                y = point.y() + r * math.sin(angle)
                finalPoint = QPoint(x, y)
                if not self.map.pixel(x, y):
                    break
            if initPoint != QPoint(-1, -1):
                painter.drawLine(initPoint, finalPoint)
            else:
                firstPoint = finalPoint
            lidarPoints.append(finalPoint - point)

        painter.drawLine(finalPoint, firstPoint)
        painter.end()
        self.update()
        self.runObstacleAvoidance(point, lidarPoints)

    def runObstacleAvoidance(self, point, lidarPoints):
        # Calculate distance
        # Target 287, 293
        destiny = QPoint(287, 293)
        ao = destiny - point

        rcoli = 2
        # Get only the front, right, back and left values
        lpoints = [
            lidarPoints[int(i * (len(lidarPoints) + 1) / 4)] for i in range(4)
        ]
        dist = lambda d: (d.x()**2 + d.y()**2)**0.5
        dist2 = lambda d, d2: ((d.x() - d2.x())**2 + (d.y() - d2.y())**2)**0.5
        dists = [dist(p) for p in lpoints]

        # Calculate next point
        nextPoint = point
        if dists[0] < rcoli and not self.around:
            self.around_point = copy.copy(point)
        self.around = dists[0] < rcoli or self.around

        # Bug algorithm
        if not self.around:
            if abs(ao.x()) > abs(ao.y()):
                if ao.x() > 0:
                    nextPoint += QPoint(1, 0)
                    self.angle = 0
                else:
                    nextPoint += QPoint(-1, 0)
                    self.angle = math.pi
            else:
                if ao.y() > 0:
                    nextPoint += QPoint(0, 1)
                    self.angle = math.pi / 2
                else:
                    nextPoint += QPoint(0, -1)
                    self.angle = 3 * math.pi / 2
        else:
            if dist2(self.around_point, point) + dist2(destiny, point) - dist2(
                    destiny, self.around_point) < 3 and dist2(
                        self.around_point, point) > 3:
                self.around = False
            elif dists[3] < rcoli:
                if dists[0] > rcoli:
                    self.position += QPoint(math.cos(self.angle),
                                            math.sin(self.angle))
                else:
                    self.angle += math.pi / 2
            elif dists[0] < rcoli:
                self.position += QPoint(math.cos(self.angle),
                                        math.sin(self.angle))
                self.angle += math.pi / 2
            elif dists[1] < rcoli:
                self.angle += math.pi
            else:
                self.position += QPoint(math.cos(self.angle - math.pi / 2),
                                        math.sin(self.angle - math.pi / 2))
                self.angle -= math.pi / 2
Beispiel #26
0
 def run(self):
     # next() raises a StopIteration exception when the generator ends.
     # If this exception is unhandled by run(), it causes thread termination.
     # If wdg internal C++ object was destroyed by main thread (form closing)
     # a RuntimeError exception is raised and causes thread termination too.
     # Thus, no further synchronization is needed.
     import exiftool
     with exiftool.ExifTool() as e:
         while True:
             try:
                 filename = next(self.fileListGen)
                 # get orientation
                 try:
                     # read metadata from sidecar (.mie) if it exists, otherwise from image file.
                     profile, metadata = e.get_metadata(
                         filename,
                         tags=("colorspace", "profileDescription",
                               "orientation", "model", "rating",
                               "FileCreateDate"),
                         createsidecar=False)
                 except ValueError:
                     metadata = {}
                 # get image info
                 tmp = [
                     value for key, value in metadata.items()
                     if 'orientation' in key.lower()
                 ]
                 orientation = tmp[
                     0] if tmp else 1  # metadata.get("EXIF:Orientation", 1)
                 # EXIF:DateTimeOriginal seems to be missing in many files
                 tmp = [
                     value for key, value in metadata.items()
                     if 'date' in key.lower()
                 ]
                 date = tmp[
                     0] if tmp else ''  # metadata.get("EXIF:ModifyDate", '')
                 tmp = [
                     value for key, value in metadata.items()
                     if 'rating' in key.lower()
                 ]
                 rating = tmp[
                     0] if tmp else 0  # metadata.get("XMP:Rating", 5)
                 rating = ''.join(['*'] * int(rating))
                 transformation = exiftool.decodeExifOrientation(
                     orientation)
                 # get thumbnail
                 img = e.get_thumbNail(filename, thumbname='thumbnailimage')
                 # no thumbnail found : try preview
                 if img.isNull():
                     img = e.get_thumbNail(
                         filename, thumbname='PreviewImage'
                     )  # the order is important : for jpeg PreviewImage is full sized !
                 # all failed : open image
                 if img.isNull():
                     img = QImage(filename)
                 # remove possible black borders, except for .NEF
                 if filename[-3:] not in ['nef', 'NEF']:
                     bBorder = 7
                     img = img.copy(
                         QRect(0, bBorder, img.width(),
                               img.height() - 2 * bBorder))
                 pxm = QPixmap.fromImage(img)
                 if not transformation.isIdentity():
                     pxm = pxm.transformed(transformation)
                 # set item caption and tooltip
                 item = QListWidgetItem(
                     QIcon(pxm), basename(filename))  # + '\n' + rating)
                 item.setToolTip(
                     basename(filename) + ' ' + date + ' ' + rating)
                 # set item mimeData to get filename=item.data(Qt.UserRole)[0] transformation=item.data(Qt.UserRole)[1]
                 item.setData(Qt.UserRole, (filename, transformation))
                 self.wdg.addItem(item)
             # for clean exiting we catch all exceptions and force break
             except OSError:
                 continue
             except:
                 break
def peek_image(path):
    im = QImage(path)
    return im.width(), im.height()
    def setImage(self, image: QtGui.QImage):
        self.viewer.setImage(image)
        self.setGeometry(self.x(), self.y(), image.width(), image.height())

        mask = QtGui.QPixmap.fromImage(image.createAlphaMask())
        self.setMask(mask)
Beispiel #29
0
class Robotic_Viewer_NG(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle('A Wonderfull Name')
        self.resize(1080,720)
        self.setWindowIcon(QIcon(QPixmap('smallLogo.png')))
        self.setStyleSheet("QMainWindow {background: '#f1fcb3';}")
        self.setMinimumWidth(960)
        self.setMinimumHeight(720)

        ## Création des widgets
        self.settingsWidget = QWidget(self)
        ## Configuration des signals/slots
        self.timeSimu = 90
        self.time = 0
        self.rythmSim = QTimer()
        self.rythmSim.timeout.connect(self.simulationStep)
        self.buildGameElements()
        ## Configuration des widgets
        self.mapPx = QImage('TableCDFR2020.png').scaledToWidth(self.width()*2/3,aspectmode='KeepAspectRatio')
        self.scaleFactor = 300/self.mapPx.width()
        self.buildSettingsGroupBox(self.settingsWidget)
        self.settingsWidget.setStyleSheet("background: '#94e4f7';")
        self.fitToWindow()

    def buildGameElements(self):
        # Création d'une stratégie de jeux        
        self.robotM = VirtualRobot('MarioBot')
        self.robotG = VirtualRobot('GuiguiBot')
        self.robots = [ self.robotM , self.robotG ]

        self.brain = Strategy()
        self.brain.addRobot(self.robotM)
        self.brain.addRobot(self.robotG)

        self.robotM_traget = Circle(0,0,5)
        self.robotG_traget = Circle(0,0,5)

        # Création d'action supplémentaires
        self.act1 = Action('ManuelM',90,25,np.deg2rad(0))
        self.act2 = Action('ManuelG',70,25,np.deg2rad(180))

        self.brain.addAction(self.act1.getID(),self.act1)
        self.brain.addAction(self.act2.getID(),self.act2)

        # Création d'element de jeux externes
        l_cercA = Circle(80,-30,30)
        l_cercB = Circle(30,330,30)
        l_cercC = Circle(80,330,30)
        l_cercD = Circle(30,-30,40)

        self.staticElts = [l_cercA,l_cercB,l_cercC,l_cercD]

        i = 0
        for elt in self.staticElts :
            elt.setID(elt.getID()+' '+repr(i))
            print(elt)
            i = i +1

        self.rstElmtPos()

    def rstElmtPos(self):
        self.robotM.setStaticState(90,25,np.deg2rad(0))
        self.robotG.setStaticState(70,25,np.deg2rad(180))

        self.repaint()

    def rstElmtStat(self):
        #self.staticElts = [self.cercA,self.cercB,self.cercC,self.cercD]
        self.repaint()

    def paintEvent(self, event):
        mapP = QPainter()
        mapP.begin(self)
        mapP.drawImage(self.centralGP.x(),self.centralGP.y(),self.mapPx)
        mapP.end()

        self.drawRobot(self.robotM,'blue')
        self.drawRobot(self.robotG,'purple')
        self.drawElts(self.staticElts,'black','pink')
        self.drawElts([self.robotM_traget,self.robotG_traget],'red','white')

    def drawElts(self,elt_list,colorElt,colotTxt):
        for elt in elt_list :
            l_pp = self.getRealFromUiCoord(elt.getX(),elt.getY())
            eltP = QPainter()
            eltP.begin(self)
            eltP.setBrush(QBrush(QColor(colorElt)))

            myPen = QPen()
            myPen.setBrush(QBrush(QColor(colotTxt)))

            if 'rect' in elt.getID() :
                l_pw = elt.getWidth()/self.scaleFactor
                l_pl = elt.getLength()/self.scaleFactor
                eltP.drawRect(l_pp.getX()-(l_pw/2),l_pp.getY()-(l_pl/2),l_pw,l_pl)

                eltP.setPen(myPen)
                eltP.drawText(l_pp.getX()-(l_pw/4),l_pp.getY(),l_pw,l_pl,1,elt.getID())
            elif 'circle' in elt.getID() :
                l_pr = elt.getRayon()/self.scaleFactor
                eltP.drawEllipse(l_pp.getX()-(l_pr/2),l_pp.getY()-(l_pr/2),l_pr,l_pr)

                eltP.setPen(myPen)
                eltP.drawText(l_pp.getX()-l_pr/3,l_pp.getY(),l_pr,l_pr,1,elt.getID())
            else :
                pass
            eltP.end()

    def drawRobot(self, robot, color):
        # Position computing
        relativePoint = self.getRealFromUiCoord(robot.getPosition().x,robot.getPosition().y)
        w_tr = robot.getWidth()/(2*self.scaleFactor)
        l_tr = robot.getLength()/(4*self.scaleFactor)
        x_center = relativePoint.x # w_tr
        y_center = relativePoint.y #- l_tr

        pts_list = QPoint(-w_tr,-l_tr), QPoint(-w_tr,l_tr), QPoint(0,l_tr*1.2), QPoint(w_tr,l_tr),QPoint(w_tr,-l_tr),QPoint(-w_tr,-l_tr)

        polyst = self.rotatePolygon(pts_list,robot.getAngle())
        poly = QPolygon(polyst)
        poly.translate(x_center,y_center)

        # Draw Item
        myPen = QPen()
        myPen.setBrush(QBrush(QColor(color)))
        myPen.setWidth(5)

        robotP = QPainter()
        robotP.begin(self)
        robotP.setPen(myPen)
        robotP.drawPolyline(poly)
        robotP.end()

    def rotatePolygon(self,polygon,teta):
        rotatedPolygon = []
        for corner in polygon :
            Vi = np.array([corner.x(),corner.y(),1])
            Mrot = np.array([ [np.cos(teta), np.sin(teta),0],
                              [-np.sin(teta), np.cos(teta),0],
                              [ 0,0,0] ])
            Vo = np.dot(Mrot,np.transpose(Vi))

            rotatedPolygon.append(QPoint(Vo[0],Vo[1]))
        return rotatedPolygon

    def buildSettingsGroupBox(self, a_widget) :
        self.settingsGroupBox = QGroupBox('Settings')
        l_gridLayout = QGridLayout()

        self.labelRegTitle = QLabel('Position')           # 0
        self.lineEditReg = QLineEdit()                      # 1
        self.lineEditReg.setText("X : 0 - Y : 0 - T : 0")   # 1
        self.pushBtnRegRst = QPushButton('Restart')         # 2
        self.pushBtnRegRst.clicked.connect(self.rstElmtPos) # 2
        self.labelRegTarget = QLabel('Target : not defined')  # 3
        self.selectedRobot = 0

        self.labelSimuTitle = QLabel('Simulation')      # 0
        self.pushBtnStartSimu = QPushButton('Start')    # 1
        self.pushBtnStartSimu.clicked.connect(self.startSimu)
        self.pushBtnStopSimu = QPushButton('Stop')      # 2
        self.pushBtnStopSimu.clicked.connect(self.stopSimu)
        self.labelSimuInfos = QLabel('Durée de simulation : '+repr(self.timeSimu)+' sec')   # 4
        self.hSlider= QSlider()                         # 3
        self.hSlider.setOrientation(Qt.Horizontal)      # 3
        self.hSlider.valueChanged.connect(self.sliderEvolution)
        self.hSlider.setValue(self.timeSimu)
        self.hSlider.setRange(0,120)

        self.labelPfTitle = QLabel('Path Finding')      # 0
        self.comboBoxAlgoPF = QComboBox()               # 1
        self.comboBoxAlgoPF.addItem('A*')               # 1
        self.comboBoxAlgoPF.addItem('Dijtra')           # 1
        self.comboBoxLenghtPF = QComboBox()             # 2
        self.comboBoxLenghtPF.addItem('Manathan')       # 2
        self.comboBoxLenghtPF.addItem('Euclidian')      # 2
        self.pushBtnPF = QPushButton('NOT USED')         # 3
        self.pushBtnPF.clicked.connect(self.rstElmtStat)
        self.labelPfElt = QLabel('')                    # 4

        self.labelStratTitle = QLabel('Stratégie')      # 0
        self.labelStratRbtG = QLabel('GuiGuiBot')       # 0
        self.comboBoxStratRbtG = QComboBox()            # 1
        for l_act in self.brain.getActionKeys() :
            self.comboBoxStratRbtG.addItem(l_act)
        self.comboBoxStratRbtG.currentIndexChanged.connect(self.updateStrategies)
        self.labelStratRbtM = QLabel('MarioBot')        # 2
        self.comboBoxStratRbtM = QComboBox()            # 3
        for l_act in self.brain.getActionKeys() :
            self.comboBoxStratRbtM.addItem(l_act)
        self.comboBoxStratRbtM.currentIndexChanged.connect(self.updateStrategies)

        l_gridLayout.addWidget(self.labelRegTitle,0,0)
        l_gridLayout.addWidget(self.lineEditReg,1,0)
        l_gridLayout.addWidget(self.pushBtnRegRst,2,0)
        l_gridLayout.addWidget(self.labelRegTarget,3,0)

        l_gridLayout.addWidget(self.labelSimuTitle,0,1)
        l_gridLayout.addWidget(self.pushBtnStartSimu,1,1)
        l_gridLayout.addWidget(self.pushBtnStopSimu,2,1)
        l_gridLayout.addWidget(self.hSlider,3,1)
        l_gridLayout.addWidget(self.labelSimuInfos,4,1)

        l_gridLayout.addWidget(self.labelStratTitle,0,2)
        l_gridLayout.addWidget(self.labelStratRbtG,1,2)
        l_gridLayout.addWidget(self.comboBoxStratRbtG,2,2)
        l_gridLayout.addWidget(self.labelStratRbtM,3,2)
        l_gridLayout.addWidget(self.comboBoxStratRbtM,4,2)

        l_gridLayout.addWidget(self.labelPfTitle,0,3)
        l_gridLayout.addWidget(self.comboBoxAlgoPF,1,3)
        l_gridLayout.addWidget(self.comboBoxLenghtPF,2,3)
        l_gridLayout.addWidget(self.pushBtnPF,3,3)
        l_gridLayout.addWidget(self.labelPfElt,4,3)

        l_gridLayout.setColumnStretch(0, a_widget.width()/4)
        l_gridLayout.setColumnStretch(1, a_widget.width()/4)
        l_gridLayout.setColumnStretch(2, a_widget.width()/4)
        l_gridLayout.setColumnStretch(3, a_widget.width()/4)

        self.settingsGroupBox.setLayout(l_gridLayout)
        vbox = QVBoxLayout()
        vbox.addWidget(self.settingsGroupBox)

        a_widget.setLayout(vbox)

    def startSimu(self):
        self.time = 0
        self.rythmSim.start(100)

    def stopSimu(self):
        self.rythmSim.stop()

    def updateStrategies(self):
        self.brain.assignAction(self.comboBoxStratRbtG.currentText(),self.robotG.getID())
        self.brain.assignAction(self.comboBoxStratRbtM.currentText(),self.robotM.getID())

    def simulationStep(self):
        if self.time < self.timeSimu :
            # Appel de la stratégie
            self.brain.beat()

            # Simulation des robots
            for rbt in self.robots :
                rbt.updateState(self.rythmSim.interval())               # Refresh position
                rbt.updateSensors(self.brain.getElements().values())    # Refresh sensors data

            # Mise à jour de l'interface graphique
            self.time = self.time + (self.rythmSim.interval()/1000)
            self.labelSimuInfos.setText('Simulation : '+repr(round(self.time,2))+'\t/ '+repr(self.timeSimu)+' sec')
            self.robotM_traget.setXY(self.robotM.getTarget().getPosition().getX(),self.robotM.getTarget().getPosition().getY())
            self.robotG_traget.setXY(self.robotG.getTarget().getPosition().getX(),self.robotG.getTarget().getPosition().getY())
            self.repaint()
        else :
            pass

    def fitToWindow(self):
        self.settingsWidget.setGeometry(0,0,self.width(),self.height()/4)
        self.centralGP = QPoint((self.width()-self.mapPx.width())/2, self.settingsWidget.height()+20)
        self.repaint()

    def getUiFromRealCoord(self,x,y):
        ty = -self.centralGP.x()
        tx = -self.centralGP.y()
        s = self.scaleFactor

        Vre = np.array([x,y,s])
        Mtr = np.array([ [ 0,s,tx],
                         [ s,0,ty],
                         [ 0,0,0] ])
        Vui = np.dot(Mtr,np.transpose(Vre))

        l_x = Vui[0]
        l_y = Vui[1]
        return Point(round(l_x),round(l_y))

    def getRealFromUiCoord(self,x,y):
        tx = (y/self.scaleFactor)
        ty = (x/self.scaleFactor)
        Vui = np.array([self.centralGP.x(),self.centralGP.y(),1])
        Mtr = np.array([ [ 1,0,tx],
                         [ 0,1,ty],
                         [ 0,0,1] ])
        Vre = np.dot(Mtr,np.transpose(Vui))

        l_x = Vre[0]
        l_y = Vre[1]
        return Point(round(l_x),round(l_y))

    def mousePressEvent(self, it):
        rel_pt = self.getUiFromRealCoord(it.x(),it.y())
        if it.button()== Qt.MouseButton.RightButton and self.selectedRobot != 0:
            self.labelRegTarget.setText('Manual target of '+self.selectedRobot.getID()+' X: '+repr(rel_pt.x)+' Y:'+repr(rel_pt.y))
            if 'M' in self.selectedRobot.getID():
                self.brain.modifyAction('ManuelM',State(rel_pt.x,rel_pt.y,np.pi))
            if 'G' in self.selectedRobot.getID():
                self.brain.modifyAction('ManuelG',State(rel_pt.x,rel_pt.y,np.pi))

        if it.button()== Qt.MouseButton.LeftButton :
            for rbt in self.robots :
                if rbt.getPosition().distanceFrom(rel_pt)<10 :
                    self.selectedRobot = rbt
                    self.labelRegTarget.setText(self.selectedRobot.getID()+ ' selected...')

    def refreshEltLabel(self):
        l_str = ''
        for i in self.brain.getElementsKeys():
            l_str = i+' '+l_str
        self.labelPfElt.setText(l_str)

    def sliderEvolution(self,it):
        self.timeSimu = self.hSlider.value()
        self.labelSimuInfos.setText('Durée de simulation :'+repr(self.timeSimu)+' sec')

    def wheelEvent(self,event):
        angle_delta = 10.0*(event.delta()/120)
        rel_pt = self.getUiFromRealCoord(event.x(),event.y())
        
        for rbt in self.robots :
            if rbt.getPosition().distanceFrom(rel_pt)<10 :
                rbt.setAngle(rbt.getAngle() + np.deg2rad(angle_delta))
                self.lineEditReg.setText(rbt.__str__()+' '+rbt.getPosition().__str__())
                self.repaint()

    def mouseMoveEvent(self,it):
        rel_pt = self.getUiFromRealCoord(it.x(),it.y())

        table = Rect(100,150,200,300)

        for rbt in self.robots:
            if rbt.getPosition().distanceFrom(rel_pt)<10 :
                rbt.setPosition(rel_pt.x,rel_pt.y)
                self.lineEditReg.setText(rbt.__str__()+' '+rbt.getPosition().__str__())
                self.repaint()

        for elt in self.staticElts:
            if elt.getPosition().distanceFrom(rel_pt)<10 :
                elt.setPosition(rel_pt.x,rel_pt.y)

                if table.contains(elt.getPosition()):
                    if not self.brain.containsElement(elt.getID()):
                        self.brain.addElement(elt.getID(),elt)
                        self.refreshEltLabel()
                    else :
                        pass
                else :
                    if self.brain.containsElement(elt.getID()):
                        self.brain.removeElement(elt.getID())
                        self.refreshEltLabel()
                    else:
                        pass
                self.lineEditReg.setText(elt.__str__())
            self.repaint()

    def resizeEvent(self, it):
        self.fitToWindow()
Beispiel #30
0
    def redoIt(self):
        maya_cmds.undoInfo(stateWithoutFlush=False)
        try:
            image = QImage(self.image)
            if image.format() != QImage.Format_RGBA8888:
                image = image.convertToFormat(QImage.Format_RGBA8888)

            imageBits = image.bits()
            imageWidth = image.width()
            imageHeight = image.height()
            imageWidthM = imageWidth - 1
            imageHeightM = imageHeight - 1

            mFnMesh = OpenMaya.MFnMesh(
                OpenMaya.MGlobal.getSelectionListByName(
                    self.shape).getDagPath(0))
            mPoints = mFnMesh.getPoints(OpenMaya.MSpace.kWorld)
            self.mPoints = OpenMaya.MPointArray(mPoints)

            tmp1, uvIdsFace = mFnMesh.getAssignedUVs(self.uvName)
            tmp2, vertexIdsFace = mFnMesh.getVertices()
            u, v = mFnMesh.getUVs(self.uvName)
            uvs = [0] * len(u)
            for i in xrange(len(uvIdsFace)):
                uvIdFace = uvIdsFace[i]
                uvs[vertexIdsFace[i]] = [u[uvIdFace], v[uvIdFace]]

            if self.matrixIs.X:
                diffX = self.matrixMax.X - self.matrixMin.X
                for i in xrange(len(mPoints)):
                    u = int((uvs[i][0] % 1.0) * imageWidthM)
                    v = int((uvs[i][1] % 1.0) * imageHeightM)
                    mPoints[i].x += ((ord(imageBits[
                        (u + v * imageWidth) * 4 + self.matrixCha.X]) * diffX)
                                     / 255.0) + self.matrixMin.X
            if self.matrixIs.Y:
                diffY = self.matrixMax.Y - self.matrixMin.Y
                for i in xrange(len(mPoints)):
                    u = int((uvs[i][0] % 1.0) * imageWidthM)
                    v = int((uvs[i][1] % 1.0) * imageHeightM)
                    mPoints[i].y += ((ord(imageBits[
                        (u + v * imageWidth) * 4 + self.matrixCha.Y]) * diffY)
                                     / 255.0) + self.matrixMin.Y
            if self.matrixIs.Z:
                diffZ = self.matrixMax.Z - self.matrixMin.Z
                for i in xrange(len(mPoints)):
                    u = int((uvs[i][0] % 1.0) * imageWidthM)
                    v = int((uvs[i][1] % 1.0) * imageHeightM)
                    mPoints[i].z += ((ord(imageBits[
                        (u + v * imageWidth) * 4 + self.matrixCha.Z]) * diffZ)
                                     / 255.0) + self.matrixMin.Z
            if self.matrixIs.N:
                diffN = self.matrixMax.N - self.matrixMin.N
                mNormals = mFnMesh.getVertexNormals(True,
                                                    OpenMaya.MSpace.kWorld)
                for i in xrange(len(mPoints)):
                    u = int((uvs[i][0] % 1.0) * imageWidthM)
                    v = int((uvs[i][1] % 1.0) * imageHeightM)
                    mPoints[i].x += mNormals[i].x * ((
                        (ord(imageBits[
                            (u + v * imageWidth) * 4 + self.matrixCha.N]) *
                         diffN) / 255.0) + self.matrixMin.N)
                    mPoints[i].y += mNormals[i].y * ((
                        (ord(imageBits[
                            (u + v * imageWidth) * 4 + self.matrixCha.N]) *
                         diffN) / 255.0) + self.matrixMin.N)
                    mPoints[i].z += mNormals[i].z * ((
                        (ord(imageBits[
                            (u + v * imageWidth) * 4 + self.matrixCha.N]) *
                         diffN) / 255.0) + self.matrixMin.N)
            mFnMesh.setPoints(mPoints, OpenMaya.MSpace.kWorld)
            mFnMesh.updateSurface()
        except Exception as e:
            print >> stderr, str(e)
        maya_cmds.undoInfo(stateWithoutFlush=True)
Beispiel #31
0
def _test_pipedimagerpq():
    # vertices of a pentagon (roughly) centered in a 1000 x 1000 square
    pentagonpts = (
        (504.5, 100.0),
        (100.0, 393.9),
        (254.5, 869.4),
        (754.5, 869.4),
        (909.0, 393.9),
    )
    linepts = ((350, 50), (200, 150), (400, 250), (300, 350), (150, 250),
               (100, 450))
    # start PyQt
    testapp = QApplication(["PipedImagerPQ"])
    # create the list of commands to submit
    drawcmnds = []
    drawcmnds.append({"action": "setTitle", "title": "Tester"})
    drawcmnds.append({"action": "show"})
    drawcmnds.append({"action": "clear", "color": "black"})
    drawcmnds.append({"action": "screenInfo"})
    # create the image to be displayed
    testimage = QImage(500, 500, QImage.Format_ARGB32_Premultiplied)
    # initialize a black background
    testimage.fill(0xFF000000)
    # draw some things in the image
    testpainter = QPainter(testimage)
    testpainter.setBrush(QBrush(QColor(0, 255, 0, 128), Qt.SolidPattern))
    testpainter.setPen(
        QPen(QBrush(QColor(255, 0, 0, 255), Qt.SolidPattern), 5.0,
             Qt.SolidLine, Qt.SquareCap, Qt.MiterJoin))
    testpainter.drawRect(QRectF(5.0, 255.0, 240.0, 240.0))
    testpainter.setBrush(QBrush(QColor(0, 0, 255, 255), Qt.SolidPattern))
    testpainter.setPen(
        QPen(QBrush(QColor(0, 0, 0, 255), Qt.SolidPattern), 5.0, Qt.DashLine,
             Qt.RoundCap, Qt.RoundJoin))
    testpainter.drawPolygon(
        QPolygonF([
            QPointF(.25 * ptx, .25 * pty + 250) for (ptx, pty) in pentagonpts
        ]))
    testpainter.setBrush(Qt.NoBrush)
    testpainter.setPen(
        QPen(QBrush(QColor(255, 255, 255, 255), Qt.SolidPattern), 3.0,
             Qt.DashLine, Qt.RoundCap, Qt.RoundJoin))
    testpainter.drawPolyline(
        QPolygonF([QPointF(pts, pty) for (pts, pty) in linepts]))
    testpainter.end()
    # add the image command
    testimgwidth = testimage.width()
    testimgheight = testimage.height()
    testimgstride = testimage.bytesPerLine()
    # not a good way to get the pixel data
    testimgdata = bytearray(testimgheight * testimgstride)
    k = 0
    for pty in range(testimgheight):
        for ptx in range(testimgwidth):
            pixval = testimage.pixel(ptx, pty)
            (aval, rgbval) = divmod(pixval, 256 * 256 * 256)
            (rval, gbval) = divmod(rgbval, 256 * 256)
            (gval, bval) = divmod(gbval, 256)
            testimgdata[k] = bval
            k += 1
            testimgdata[k] = gval
            k += 1
            testimgdata[k] = rval
            k += 1
            testimgdata[k] = aval
            k += 1
    testblocksize = 4000
    testnumblocks = (testimgheight * testimgstride + testblocksize -
                     1) // testblocksize
    drawcmnds.append({
        "action": "newImage",
        "width": testimgwidth,
        "height": testimgheight,
        "stride": testimgstride
    })
    for k in range(testnumblocks):
        if k < (testnumblocks - 1):
            blkdata = testimgdata[k * testblocksize:(k + 1) * testblocksize]
        else:
            blkdata = testimgdata[k * testblocksize:]
        drawcmnds.append({
            "action": "newImage",
            "blocknum": k + 1,
            "numblocks": testnumblocks,
            "startindex": k * testblocksize,
            "blockdata": blkdata
        })
    # finish the command list
    drawcmnds.append({"action": "show"})
    drawcmnds.append({"action": "exit"})
    # create a PipedImagerPQ in this process
    (cmndrecvpipe, cmndsendpipe) = multiprocessing.Pipe(False)
    (rspdrecvpipe, rspdsendpipe) = multiprocessing.Pipe(False)
    testviewer = PipedImagerPQ(cmndrecvpipe, rspdsendpipe)
    # create a command submitter dialog
    tester = _CommandSubmitterPQ(testviewer, cmndsendpipe, rspdrecvpipe,
                                 drawcmnds)
    tester.show()
    # let it all run
    testresult = testapp.exec_()
    if testresult != 0:
        sys.exit(testresult)