Пример #1
0
    def initialze_mask(self):

        if self.input_video.shape[1] >= self.input_video.shape[2]:

            self.mask_qimage = QtGui.QImage(
                QtCore.QSize(self.input_video.shape[2],
                             self.input_video.shape[1]),
                QtGui.QImage.Format_ARGB32)

            self.mask_qimage.fill(QtGui.QColor(250, 240, 0, 0))
            self.mask_qimage_view = np.frombuffer(
                self.mask_qimage.bits(),
                dtype=np.uint8).reshape(self.input_video.shape[1],
                                        self.input_video.shape[2], 4)
        else:
            self.mask_qimage = QtGui.QImage(
                QtCore.QSize(self.input_video.shape[2],
                             self.input_video.shape[1]),
                QtGui.QImage.Format_ARGB32)

            self.mask_qimage.fill(QtGui.QColor(250, 240, 0, 0))
            self.mask_qimage_view = np.frombuffer(
                self.mask_qimage.bits(),
                dtype=np.uint8).reshape(self.input_video.shape[1],
                                        self.input_video.shape[2], 4)
Пример #2
0
def convert_pt_to_heatmap(np_pixels):
    """
    Converts the grayscale of the pixel array associated with the PET images
    to a RGB image with a colormap/heat map applied to it.

    Returns:
        qimage [Qimage]: The converted heatmap
    """
    # Conversion of the array to UINT8, color spaces do not like int8.
    arr8 = np_pixels.astype(np.uint8)

    # Apply a colormap to the imageset (np array)
    heatmap = cv2.applyColorMap(arr8, cv2.COLORMAP_HOT)

    # Convert the BGR colorspace to RGB, this is needed as cv2 works in BGR 
    # colorspace as opposed to RGB colorspace.
    heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB)

    # Fix as colored images have 3*8 bits = 3 bytes instead of one
    bytes_per_line = np_pixels.shape[1] * 3

    qimage = QtGui.QImage(
        heatmap,
        heatmap.shape[1],
        heatmap.shape[0],
        bytes_per_line,
        QtGui.QImage.Format_RGB888)

    return qimage
Пример #3
0
def scaled_pixmap(np_pixels, window, level, width, height,
                  fusion=False, color=None):
    """
    Rescale the numpy pixels of image and convert to QPixmap for display.

    :param np_pixels: A list of converted pixel arrays
    :param window: Window width of windowing function
    :param level: Level value of windowing function
    :param width: Pixel width of the window
    :param height: Pixel height of the window
    :param fusion: Boolean to set scaling for overlayed images
    :param color: String for conversion of pixels to specified color map
    :return: pixmap, a QPixmap of the slice
    """

    # Rescale pixel arrays
    np_pixels = np_pixels.astype(np.int16)
    if window != 0 and level != 0:
        # Transformation applied to each individual pixel to unique
        # contrast level
        np_pixels = (np_pixels - level) / window * 255
    else:
        max_val = np.amax(np_pixels)
        min_val = np.amin(np_pixels)
        np_pixels = (np_pixels - min_val) / (max_val - min_val) * 255

    np_pixels[np_pixels < 0] = 0
    np_pixels[np_pixels > 255] = 255
    np_pixels = np_pixels.astype(np.int8)

    # Process heatmap for conversion of the np_pixels to rgb for the purpose
    # of displaying the PT/CT view in RGB colorspace.

    # Convert numpy array data to QImage for PySide6
    if color == "Heat":

        pixmap = QtGui.QPixmap(convert_pt_to_heatmap(np_pixels))

    else:
        # Generate a grayscale image and set pixmap to the image
        bytes_per_line = np_pixels.shape[1]

        qimage = QtGui.QImage(
            np_pixels,
            np_pixels.shape[1],
            np_pixels.shape[0],
            bytes_per_line,
            QtGui.QImage.Format_Indexed8)

        pixmap = QtGui.QPixmap(qimage)

    if fusion:
        width = constant.DEFAULT_WINDOW_SIZE
        height = constant.DEFAULT_WINDOW_SIZE

    # Rescale the image accordingly
    pixmap = pixmap.scaled(width, height, QtCore.Qt.IgnoreAspectRatio,
                           QtCore.Qt.SmoothTransformation)
    return pixmap
Пример #4
0
 def DrawCover(self, Painter, Options):
     self._style.subElementRect(self._style.SE_ItemViewItemDecoration, Options, Options.widget)
     Rect = Options.rect
     TempRec = QRect(Rect.x() + 4, Rect.y() + 4, 56, 56)
     if False:
         pass
     else:
         Painter.drawImage(TempRec, QtGui.QImage(':/icon_pack/png/64/music_icon-02.png'))
Пример #5
0
def pil2pixmap(image: Image) -> QtGui.QPixmap:
    bytes_img = io.BytesIO()
    image.save(bytes_img, format='TIFF')

    qimg = QtGui.QImage()
    qimg.loadFromData(bytes_img.getvalue())

    return QtGui.QPixmap.fromImage(qimg)
Пример #6
0
    def _lookupImage(self, imageName):
        if imageName == "":
            return None

        if imageName not in MyWidget.s_images:
            MyWidget.s_images[imageName] = QtGui.QImage(imageName)

        return MyWidget.s_images[imageName]
Пример #7
0
    def _create_fade_images(self) -> tuple[QtGui.QImage, QtGui.QImage]:
        """Return a fade-in image and a fade-out image of `self.fade_width` width."""
        fade_in_image = QtGui.QImage(
            self.fade_width,
            self._text_size.height(),
            QtGui.QImage.Format_ARGB32_Premultiplied,
        )
        if fade_in_image.is_null():
            raise MemoryError("Unable to allocate QImage.")
        fade_out_image = QtGui.QImage(
            self.fade_width,
            self._text_size.height(),
            QtGui.QImage.Format_ARGB32_Premultiplied,
        )
        if fade_out_image.is_null():
            raise MemoryError("Unable to allocate QImage.")

        # FIXME: use actual transparency instead of using the background color
        background_color = self.palette.window().color().get_rgb()[:-1]
        opaque_color = QtGui.QColor(*background_color, 255)

        fade_in_image.fill(QtCore.Qt.transparent)
        fade_out_image.fill(QtCore.Qt.transparent)

        gradient = QtGui.QLinearGradient(QtCore.QPointF(0, 0),
                                         QtCore.QPointF(self.fade_width, 0))

        painter = QtGui.QPainter(fade_in_image)
        painter.set_pen(QtCore.Qt.NoPen)

        gradient.set_color_at(0, opaque_color)
        gradient.set_color_at(1, QtCore.Qt.transparent)

        painter.fill_rect(fade_in_image.rect(), gradient)
        painter.end()

        painter.begin(fade_out_image)
        painter.set_pen(QtCore.Qt.NoPen)

        gradient.set_color_at(0, QtCore.Qt.transparent)
        gradient.set_color_at(1, opaque_color)

        painter.fill_rect(fade_out_image.rect(), gradient)

        return fade_in_image, fade_out_image
Пример #8
0
def grab_full_desktop() -> QtGui.QImage:
    """Capture rect of screen on gnome systems using wayland."""
    logger.debug("Use capture method: DBUS portal")

    image = QtGui.QImage()

    _, temp_name = tempfile.mkstemp(prefix="normcap")
    try:
        connection = open_dbus_connection(bus="SESSION")

        token = f"normcap_{secrets.token_hex(8)}"
        sender_name = connection.unique_name[1:].replace(".", "_")
        handle = f"/org/freedesktop/portal/desktop/request/{sender_name}/{token}"

        response_rule = MatchRule(type="signal",
                                  interface="org.freedesktop.portal.Request",
                                  path=handle)
        Proxy(message_bus, connection).AddMatch(response_rule)

        with connection.filter(response_rule) as responses:
            msg = FreedesktopPortalScreenshot().grab("", {
                "handle_token": ("s", token),
                "interactive": ("b", False)
            })
            connection.send_and_get_reply(msg)
            response = connection.recv_until_filtered(responses)

        response_code, response_body = response.body
        assert response_code == 0 and "uri" in response_body

        image = QtGui.QImage(urlparse(response_body["uri"][1]).path)

    except AssertionError as e:
        logger.warning("Couldn't take screenshot with DBUS. Got cancelled?")
        raise e from e
    except DBusErrorResponse as e:
        if "invalid params" in [d.lower() for d in e.data]:
            logger.info("ScreenShot with DBUS failed with 'invalid params'")
        else:
            logger.exception("ScreenShot with DBUS through exception")
    finally:
        Path(temp_name).unlink()

    return image
Пример #9
0
def ocr_result() -> OcrResult:
    """Create argparser and provide its default values."""
    return OcrResult(
        tess_args=TessArgs(path=Path(),
                           lang="eng",
                           oem=2,
                           psm=2,
                           version=version.parse("5.0.0")),
        image=QtGui.QImage(),
        magic_scores={},
        transformed="",
        words=[
            {
                "level": 1,
                "page_num": 1,
                "block_num": 1,
                "par_num": 1,
                "line_num": 1,
                "word_num": 1,
                "left": 5,
                "top": 0,
                "width": 55,
                "height": 36,
                "conf": 20,
                "text": "one",
            },
            {
                "level": 1,
                "page_num": 1,
                "block_num": 1,
                "par_num": 2,
                "line_num": 1,
                "word_num": 2,
                "left": 5,
                "top": 0,
                "width": 55,
                "height": 36,
                "conf": 40,
                "text": "two",
            },
            {
                "level": 1,
                "page_num": 1,
                "block_num": 2,
                "par_num": 3,
                "line_num": 3,
                "word_num": 3,
                "left": 5,
                "top": 0,
                "width": 55,
                "height": 36,
                "conf": 30,
                "text": "three",
            },
        ],
    )
Пример #10
0
 def _render_splashscreen(self, pngpath: str) -> None:
     # Render SVG to PNG (qt's svg renderer has issues with blurred elements)
     iconpath = os.path.join(str(vxpy.__path__[0]), 'vxpy_icon.svg')
     renderer = QtSvg.QSvgRenderer(iconpath)
     image = QtGui.QImage(512, 512, QtGui.QImage.Format.Format_RGBA64)
     painter = QtGui.QPainter(image)
     image.fill(QtGui.QColor(0, 0, 0, 0))
     renderer.render(painter)
     image.save(pngpath)
     painter.end()
Пример #11
0
    def create_pixmap(self, input_file):
        if isinstance(input_file, str):
            self.input_file = input_file

        else:
            input_file = Normalization(
                video=input_file).normalized_image_specific()
            if self.parent().parent().alpha is None:
                input_file = self.con_adj.auto_pixelTransforms(input_file)
                self.input_file = input_file
            else:

                alpha = self.parent().parent().alpha
                beta = self.parent().parent().beta
                min_intensity = self.parent().parent().min_intensity
                max_intensity = self.parent().parent().max_intensity
                input_file = self.con_adj.pixel_transforms(
                    input_file, alpha, beta, min_intensity, max_intensity)
                self.input_file = input_file

        if self.medianFilterFlag:
            input_file = median_filter(input_file, 3)

        if self.parent().parent().title != "PNG":
            if input_file.shape[0] >= input_file.shape[1]:
                widthStep = input_file.shape[1]
                img = QtGui.QImage(input_file, input_file.shape[1],
                                   input_file.shape[0], widthStep,
                                   QtGui.QImage.Format_Indexed8)
                img.scaledToWidth(input_file.shape[0])
            else:
                widthStep = input_file.shape[1]
                img = QtGui.QImage(input_file, input_file.shape[1],
                                   input_file.shape[0], widthStep,
                                   QtGui.QImage.Format_Indexed8)

            newimg = img.convertToFormat(QtGui.QImage.Format.Format_RGB888)
            self.current_pixmap = QtGui.QPixmap(newimg)
            self.update_slice(self.current_pixmap)
        elif self.parent().parent().title == "PNG":
            self.current_pixmap = QtGui.QPixmap(input_file)

        return self.current_pixmap
Пример #12
0
def test_save_image_in_tempfolder():
    logger = logging.getLogger(__name__).root
    logger.setLevel("DEBUG")

    image = QtGui.QImage(20, 20, QtGui.QImage.Format.Format_RGB32)

    utils.save_image_in_tempfolder(image, postfix="unittest")

    png_files = (Path(tempfile.gettempdir()) / "normcap").glob("*.png")
    png_files = sorted(png_files, key=os.path.getmtime, reverse=True)
    assert "unittest" in str(list(png_files)[0])
Пример #13
0
 def __create_texture(self, image):
     texture = QtOpenGL.QOpenGLTexture(QtOpenGL.QOpenGLTexture.Target2D)
     texture.setMinMagFilters(QtOpenGL.QOpenGLTexture.Filter.Nearest,
                              QtOpenGL.QOpenGLTexture.Filter.Linear)
     texture.setBorderColor(0, 0, 0, 1)
     texture.setWrapMode(QtOpenGL.QOpenGLTexture.ClampToBorder)
     texture.setAutoMipMapGenerationEnabled(False)
     texture.DontGenerateMipMaps = True
     texture.setData(
         QtGui.QImage(image, image.shape[1], image.shape[0],
                      QtGui.QImage.Format_RGBA8888).mirrored())
     return texture
Пример #14
0
def capture() -> Generator[Capture, None, None]:
    """Create argparser and provide its default values."""
    image = QtGui.QImage(200, 300, QtGui.QImage.Format.Format_RGB32)
    image.fill(QtGui.QColor("#ff0000"))

    yield Capture(
        mode=CaptureMode.PARSE,
        rect=Rect(20, 30, 220, 330),
        ocr_text="one two three",
        ocr_applied_magic="",
        image=image,
    )
Пример #15
0
def qimage_argb32_from_png_decoding(img_data):
    '''Effectue le décodage d'un 'buffer' de données correspondant à une 
       image PNG. 

       En entrée se trouve le 'buffer' conforme d'une image de format PNG.

       En sortie on obtient une QImage du format QImage.Format_ARGB32.'''
    image = QtGui.QImage()
    if image.load_from_data(QtCore.QByteArray(bytearray(img_data)), 'png'):
        return image.convert_to_format(QtGui.QImage.Format_ARGB32)

    print("Erreur de décodage d'une image avec la fonction _png_decoding.")
    return image
Пример #16
0
 def _save_to_file(self):
     filenames = QtWidgets.QFileDialog.getSaveFileName(
         self, "Select export file")
     if not filenames[0]:
         return
     rect_size = self._scene.sceneRect().size()
     img_size = QtCore.QSize(int(rect_size.width()),
                             int(rect_size.height()))
     img = QtGui.QImage(img_size, QtGui.QImage.Format_ARGB32_Premultiplied)
     painter = QtGui.QPainter(img)
     self._scene.render(painter)
     img.save(filenames[0])
     painter.end()
Пример #17
0
def grab_screens() -> list[QtGui.QImage]:
    """Capture screenshots for all screens using org.gnome.Shell.Screenshot.

    This methods works gnome-shell < v41 and wayland.
    """
    logger.debug("Use capture method: DBUS Shell")

    _, temp_file = tempfile.mkstemp(prefix="normcap")
    try:
        fullscreen_to_file(temp_file)
        image = QtGui.QImage(temp_file)
    finally:
        Path(temp_file).unlink()

    return split_full_desktop_to_screens(image)
Пример #18
0
def pil2pixmap(im):
    if im.mode == "RGB":
        r, g, b = im.split()
        im = Image.merge("RGB", (b, g, r))
    elif im.mode == "RGBA":
        r, g, b, a = im.split()
        im = Image.merge("RGBA", (b, g, r, a))
    elif im.mode == "L":
        im = im.convert("RGBA")
    # Bild in RGBA konvertieren, falls nicht bereits passiert
    im2 = im.convert("RGBA")
    data = im2.tobytes("raw", "RGBA")
    qim = QtGui.QImage(data, im.size[0], im.size[1], QtGui.QImage.Format_ARGB32)
    pixmap = QtGui.QPixmap.fromImage(qim)
    return pixmap
Пример #19
0
    def select_area(self, area: Optional[Area]):
        self.area = area
        if area is None:
            return

        if "total_boundings" in area.extra:
            min_x, max_x, min_y, max_y = [
                area.extra["total_boundings"][k]
                for k in ["x1", "x2", "y1", "y2"]
            ]
        else:
            min_x, min_y = math.inf, math.inf
            max_x, max_y = -math.inf, -math.inf
            for node in area.nodes:
                if node.location is None:
                    continue
                min_x = min(min_x, node.location.x)
                min_y = min(min_y, node.location.y)
                max_x = max(max_x, node.location.x)
                max_y = max(max_y, node.location.y)

        image_path = self.game.data_path.joinpath(
            "assets", "maps",
            f"{area.map_name}.png") if self.game is not None else None
        if image_path is not None and image_path.exists():
            self._background_image = QtGui.QImage(os.fspath(image_path))
            min_x = area.extra.get("map_min_x", 0)
            min_y = area.extra.get("map_min_y", 0)
            max_x = self._background_image.width() - area.extra.get(
                "map_max_x", 0)
            max_y = self._background_image.height() - area.extra.get(
                "map_max_y", 0)
            self.image_bounds = BoundsInt(min_x, min_y, max_x, max_y)
            self.world_bounds = BoundsFloat(min_x, min_y, max_x, max_y)
        else:
            self.update_world_bounds()

        self.area_bounds = BoundsFloat(
            min_x=min_x,
            min_y=min_y,
            max_x=max_x,
            max_y=max_y,
        )
        self.area_size = QSizeF(
            max(max_x - min_x, 1),
            max(max_y - min_y, 1),
        )
        self.update()
Пример #20
0
    def load_icon(self, app_name, repo):
        self.IconSignal.connect(self.ui.HomebrewIconLabel.setPixmap)
        # Gets raw image data from server
        # Check if still relevant
        if self.ui.FileNameLineEdit.text().replace('.zip', '') == app_name:
            data = metadata.icon(app_name=app_name, repo=repo)

            # Loads image
            image = QtGui.QImage()
            image.loadFromData(data)

            # Adds image to label
            # Once again check if still relevant
            if self.ui.FileNameLineEdit.text().replace('.zip', '') == app_name:
                lbl = self.ui.HomebrewIconLabel
                self.IconSignal.emit(QPixmap(image))
                lbl.show()
Пример #21
0
class Capture:
    """Store all information like screenshot and selected region."""

    mode: CaptureMode = CaptureMode.PARSE

    # Image of selected region
    image: QtGui.QImage = QtGui.QImage()
    screen: Optional[Screen] = None
    scale_factor: float = 1
    rect: Rect = Rect()

    ocr_text: Optional[str] = None
    ocr_applied_magic: Optional[str] = None

    @property
    def image_area(self) -> int:
        """Provide area of cropped image in px²."""
        return self.rect.width * self.rect.height if self.image else 0
Пример #22
0
 def __init__(self):
     super().__init__()
     self.icon = QtGui.QIcon(umn_config.PATH_ICON)
     self.setWindowIcon(self.icon)
     self.setWindowTitle("uumail notification について")
     self.setFixedSize(600, 370)
     self.setWindowFlags(QtCore.Qt.Dialog | QtCore.Qt.WindowStaysOnTopHint)
     self.label = QtWidgets.QLabel(self)
     self.label_style = """QLabel {
         font-size: 43px;               /* 文字サイズ */
         padding: 0px 40px;
     }"""
     self.font = QtGui.QFont()
     self.font.setPointSize(13)
     self.label.setStyleSheet(self.label_style)
     self.label.setText("uumail notification")
     self.label.setGeometry(QtCore.QRect(120, 0, 480, 120))
     self.umnlogo_image = QtGui.QImage('icon\\uumail.png')
     self.umnlogo_pixmap = QtGui.QPixmap.fromImage(
         self.umnlogo_image.scaledToHeight(120))
     self.umnlogo_label = QtWidgets.QLabel(self)
     self.umnlogo_label.setPixmap(self.umnlogo_pixmap)
     self.umnlogo_label.setGeometry(QtCore.QRect(0, 0, 120, 120))
     self.varsion_txt = QtWidgets.QLabel(self)
     self.varsion_txt.setText("Version  :  2.0")
     self.varsion_txt.setFont(self.font)
     self.varsion_txt.setGeometry(QtCore.QRect(40, 150, 500, 30))
     self.github_txt = QtWidgets.QLabel(self)
     self.github_txt.setText(
         "Github : https://github.com/ikepggthb/uumail_notification")
     self.github_txt.setFont(self.font)
     self.github_txt.setGeometry(QtCore.QRect(40, 190, 500, 30))
     self.licence_txt = QtWidgets.QLabel(self)
     self.licence_txt.setText(
         "オープンソースソフトウェア(OSS)であり、GPLv3の条件で許諾されます。\nこのソフトウェアを使用、複製、配布、ソースコードを修正することができます。"
     )
     self.licence_txt.setFont(self.font)
     self.licence_txt.setGeometry(QtCore.QRect(40, 230, 500, 45))
     self.cpn_txt = QtWidgets.QLabel(self)
     self.cpn_txt.setText(
         "© 2020 ikkei Yamada All Rights Reserved.\n	Twitter : @idkaeti , Email : [email protected]"
     )
     self.cpn_txt.setFont(self.font)
     self.cpn_txt.setGeometry(QtCore.QRect(40, 290, 500, 45))
Пример #23
0
    def select_world(self, world: World):
        self.world = world
        image_path = self.game.data_path.joinpath(
            "assets", "maps",
            f"{world.name}.png") if self.game is not None else None
        if image_path is not None and image_path.exists():
            self._background_image = QtGui.QImage(os.fspath(image_path))
            self.image_bounds = BoundsInt(
                min_x=world.extra.get("map_min_x", 0),
                min_y=world.extra.get("map_min_y", 0),
                max_x=self._background_image.width() -
                world.extra.get("map_max_x", 0),
                max_y=self._background_image.height() -
                world.extra.get("map_max_y", 0),
            )
        else:
            self._background_image = None

        self.update_world_bounds()
        self.update()
Пример #24
0
    def mouseMoveEvent(self, event):
        if QtCore.QLineF(
                QtCore.QPointF(event.screenPos()),
                QtCore.QPointF(event.buttonDownScreenPos(QtCore.Qt.LeftButton))
        ).length() < QtWidgets.QApplication.startDragDistance():
            return

        drag = QtGui.QDrag(event.widget())
        mime = QtCore.QMimeData()
        drag.setMimeData(mime)

        ColorItem.n += 1
        if ColorItem.n > 2 and random(3) == 0:
            image = QtGui.QImage(':/images/head.png')
            mime.setImageData(image)
            drag.setPixmap(QtGui.QPixmap.fromImage(image).scaled(30, 40))
            drag.setHotSpot(QtCore.QPoint(15, 30))
        else:
            mime.setColorData(self.color)
            mime.setText(
                "#%02x%02x%02x" %
                (self.color.red(), self.color.green(), self.color.blue()))

            pixmap = QtGui.QPixmap(34, 34)
            pixmap.fill(QtCore.Qt.white)

            painter = QtGui.QPainter(pixmap)
            painter.translate(15, 15)
            painter.setRenderHint(QtGui.QPainter.Antialiasing)
            self.paint(painter, None, None)
            painter.end()

            pixmap.setMask(pixmap.createHeuristicMask())

            drag.setPixmap(pixmap)
            drag.setHotSpot(QtCore.QPoint(15, 20))

        drag.exec_()
        self.setCursor(QtCore.Qt.OpenHandCursor)
Пример #25
0
        with open(resource_path(f"assets/themes/{theme}"), "r") as fh:
            self.setStyleSheet(fh.read())

    def forwarder_generator(self):
        selected_app = self.ui.listAppsWidget.currentItem().data(Qt.UserRole)
        self.forwarder_gen_window = forwardergen.ForwarderWizard(self, selected_app=selected_app)
        self.forwarder_gen_window.show()


if __name__ == "__main__":
    global app
    app = QApplication()

    # set windows style for macOS users
    if platform.system() == "Darwin":
        app.setStyle('Fusion')

    global splash
    global splash_color

    # Splash
    image = QtGui.QImage(resource_path("assets/gui/splash.png"))
    splash_color = QColor("White")
    splash = QSplashScreen(QtGui.QPixmap(image))
    splash.show()

    window = MainWindow()
    window.show()
    splash.hide()
    app.exec()
Пример #26
0
    def show_stats(self):
        sending_source = self.sender()
        val = ''
        # QComboBox has the attribute 'currentText' while QPushButton does not
        # use hasattr to check if a object has a attribute
        if hasattr(sending_source, 'currentText'):
            index = self.dropdown.currentIndex()
            val = self.names[index]
        elif str(sending_source.text()) == "Search":
            searchbar_txt = self.searchbar.text()
            _, val = searchbar_txt.split(' ', 1)
        elif str(sending_source.text()) == "Random":
            single = self.df.sample()
            val = single['Name'].values[0]
        cond = self.df['Name'] == val
        # Image
        base = 'https://img.pokemondb.net/artwork/'
        index_value = self.df[cond].index.values[0]
        img_addition = ''
        if val == "Nidoran\u2640":
            img_addition = "nidoran-f" + '.jpg'
        elif val == "Nidoran\u2642":
            img_addition = "nidoran-m" + '.jpg'
        elif val == 'Farfetch\'d':
            img_addition = 'farfetchd.jpg'
        elif val == "Type: Null":
            img_addition = 'type-null.jpg'
        elif val == "Mime Jr." or val == "Mr. Mime" or val == "Mr. Rime":
            name = val.replace('. ', '-').lower()
            img_addition = name + '.jpg'
        elif val == "Mr. Mime (Galarian Mr. Mime)":
            img_addition = 'mr-mime-galarian.jpg'
        elif '(' in val and ')' in val:
            form = val[val.find("(") + 1:val.find(")")].lower()
            name = val.split(' ', 1)[0].lower()
            if 'partner' in form:
                img_addition = name + '-lets-go.jpg'
            elif name == 'greninja':
                img_addition = 'greninja-ash.jpg'
            elif form == "pa'u style":
                img_addition = 'oricorio-pau.jpg'
            elif form == "galarian farfetch'd":
                img_addition = 'farfetchd-galarian.jpg'
            elif name == 'pumpkaboo' or name == 'pumpkaboo' or name == 'rockruff':
                img_addition = name + '.jpg'
            elif name == 'hoopa':
                img_addition = form.replace(' ', '-') + '.jpg'
            elif name == 'zacian' or name == 'zamazenta':
                form_des = form.split(' ')[0]
                img_addition = name + '-' + form_des + '.jpg'
            elif name == 'calyrex':
                img_addition = name + '-' + form.replace(' ', '-') + '.jpg'
            elif name == "zygarde" and 'complete' not in form:
                img_addition = name + '-' + form[0:2] + '.jpg'
            elif name == "eternatus":
                # TODO right now using an external picture
                pass
            elif 'mega' in form:
                words = form.split()
                if len(words) == 3 and words[2] == 'x':
                    img_addition = name + '-mega-x' + '.jpg'
                elif len(words) == 3 and words[2] == 'y':
                    img_addition = name + '-mega-y' + '.jpg'
                else:
                    img_addition = name + '-mega' + '.jpg'
            else:
                fin_des = ''
                if ' ' in form:
                    form_des = form.split()
                    form_des.pop()
                    fin_des = '-'.join(form_des)
                else:
                    fin_des = form
                if name == "castform":
                    img_addition = 'vector/' + name + '-' + fin_des + '.png'
                else:
                    img_addition = name + '-' + fin_des + '.jpg'
        else:
            img_addition = val.lower() + '.jpg'
        img_url = base + img_addition
        if val == "Eternatus (Eternamax)":
            img_url = "https://static.wikia.nocookie.net/villains/images/7/76/HOME890E.png"
        # print(img_url)
        req = Request(img_url, headers={'User-Agent': "Mozilla/5.0"})
        data = urlopen(req).read()
        image = QtGui.QImage()
        image.loadFromData(data)
        self.img_label.setPixmap(QtGui.QPixmap(image))

        # Set values
        name = 'Name:\t\t\t' + val + '\n\n'
        ty = 'Type:\t\t\t' + \
            ', '.join(self.df[cond]['Type'].values[0]) + '\n\n'
        hp = 'HP:\t\t\t' + str(self.df[cond]['HP'].values[0]) + '\n\n'
        atk = 'Attack:\t\t\t' + str(self.df[cond]['Attack'].values[0]) + '\n\n'
        satk = 'Sp. Attack:\t\t' + \
            str(self.df[cond]['Sp. Atk'].values[0]) + '\n\n'
        deff = 'Defense:\t\t\t' + \
            str(self.df[cond]['Defense'].values[0]) + '\n\n'
        sdef = 'Sp. Defense:\t\t' + \
            str(self.df[cond]['Sp. Def'].values[0]) + '\n\n'
        speed = 'Speed:\t\t\t' + str(self.df[cond]['Speed'].values[0]) + '\n\n'
        total = 'Total:\t\t\t' + str(self.df[cond]['Total'].values[0]) + '\n\n'

        # Add text
        final = name + ty + hp + atk + satk + deff + sdef + speed + total
        self.label.setText(final)

        # Clean searchbar
        self.searchbar.clear()

        # Set dropdown to current
        self.dropdown.setCurrentIndex(index_value)
Пример #27
0
 def __init__(self, parent=None):
     super().__init__(":/assets/base.png",
                      ":/assets/KDAB_bubble_fulcolor.png", parent)
     self.m_triangle = QtGui.QImage(":/assets/tri.png")
Пример #28
0
def test_capture_image_area(capture: Capture):
    capture.image = QtGui.QImage(200, 300, QtGui.QImage.Format.Format_RGB32)
    assert capture.image_area == 60_000

    capture.image = QtGui.QImage()
    assert capture.image_area == 0
Пример #29
0
    def initUI(self):
        """
        initial UI
        """
        # Grid Layout
        self.grid = QtWidgets.QGridLayout()
        self.setLayout(self.grid)

        # Parse JSON for dataframe
        self.df = pd.read_json('PokemonData.json')
        self.df = self.df.sort_values('#')
        self.df['#'] = self.df['#'].apply(int_to_str)
        self.df['Index'] = self.df['#'] + ' ' + self.df['Name']
        # self.df = self.df.set_index(['#'])

        # Drop Down
        self.dropdown = QtWidgets.QComboBox(self)
        self.names = self.df['Name'].values
        self.index = self.df['Index'].values
        self.dropdown.addItems(self.index)
        self.dropdown.currentIndexChanged.connect(self.show_stats)
        self.grid.addWidget(self.dropdown, 0, 0, 1, 1)

        # Search bar
        self.completer = QtWidgets.QCompleter(self.index)
        self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.completer.setFilterMode(QtCore.Qt.MatchContains)
        self.searchbar = QtWidgets.QLineEdit(self)
        self.searchbar.setCompleter(self.completer)
        self.grid.addWidget(self.searchbar, 0, 1, 1, 1)
        self.searchbtn = QtWidgets.QPushButton('Search', self)
        self.grid.addWidget(self.searchbtn, 0, 2, 1, 1)
        self.searchbtn.clicked.connect(self.show_stats)

        # Random one
        self.randombtn = QtWidgets.QPushButton('Random', self)
        self.grid.addWidget(self.randombtn, 0, 3, 1, 1)
        self.randombtn.clicked.connect(self.show_stats)

        # Image
        self.img_label = QtWidgets.QLabel()
        img_url = 'https://img.pokemondb.net/artwork/bulbasaur.jpg'
        req = Request(img_url, headers={'User-Agent': "Mozilla/5.0"})
        data = urlopen(req).read()
        image = QtGui.QImage()
        image.loadFromData(data)
        self.img_label.setPixmap(QtGui.QPixmap(image))
        self.grid.addWidget(self.img_label, 1, 1, 1, 3)

        # Data
        self.label = QtWidgets.QLabel()
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setText(
            '\nName:\n\nType:\n\nHP:\n\nAttack\n\nSp. Attack\n\nDefense:\n\nSp. Defense:\n\nSpeed:\n\nTotal:'
        )
        self.label.setAlignment(QtCore.Qt.AlignLeft)
        self.grid.addWidget(self.label, 1, 0, 1, 1)

        # Set values
        name = 'Name:\t\t\t' + 'Bulbasaur' + '\n\n'
        ty = 'Type:\t\t\t' + 'Grass, Poison' + '\n\n'
        hp = 'HP:\t\t\t' + '45' + '\n\n'
        atk = 'Attack:\t\t\t' + '49' + '\n\n'
        satk = 'Sp. Attack:\t\t' + '65' + '\n\n'
        deff = 'Defense:\t\t\t' + '49' + '\n\n'
        sdef = 'Sp. Defense:\t\t' + '65' + '\n\n'
        speed = 'Speed:\t\t\t' + '45' + '\n\n'
        total = 'Total:\t\t\t' + '318' + '\n\n'

        # Add text
        final = name + ty + hp + atk + satk + deff + sdef + speed + total
        self.label.setText(final)
        self.label.setAlignment(QtCore.Qt.AlignLeft)
        self.grid.addWidget(self.label, 1, 0, 1, 1)
Пример #30
0
def get_fused_pixmap(orig_image,
                     fused_image,
                     aspect,
                     slice_num,
                     view,
                     windowing=(-250, 500)):
    """
    Generates a colored pixmap of the array from the inputted view.
    Args:
        orig_image(ndarray): N dimension array containing signed int8 values
        fused_image(ndarray): N dimension array containing signed int8 values
        aspect(Any): currently not used
        slice_num(int): slice number of the array
        view(String): specified flag that can be sagittal, coronal or axial
        windowing: upper and lower bound for windowing
    windowing: target level and window of the fused image
    Returns:
        pixmap (QtGui.QPixmap): returns the pixmap of co-registered fixed and 
        moving images.
    """
    # Get dimension /could also input dimensions as parameters
    image_array = sitk.GetArrayFromImage(orig_image)
    if view == "sagittal":
        image_slice = return_slice("x", slice_num)

        pixel_array_color = \
            np.array(generate_comparison_colormix(
                [orig_image, fused_image],
                arr_slice=image_slice, window=windowing))

        # resize dimensions to stop image stretch
        pixel_array_color = np.resize(pixel_array_color, (512, 345, 3))

        # first adjusts rgb (0,1) scale to greyscale (0,255)
        # then converts type and formats it to color.
        qimage2 = \
            QtGui.QImage(((255 * pixel_array_color).astype(np.uint8)),
                         image_array.shape[1], image_array.shape[0],
                         QtGui.QImage.Format_RGB888)

        # Then continues to convert to pixmap just like in onko
        pixmap = QtGui.QPixmap(qimage2)

        pixmap = pixmap.scaled(512, 512, QtCore.Qt.IgnoreAspectRatio,
                               QtCore.Qt.SmoothTransformation)
    elif view == "coronal":
        image_slice = return_slice("y", slice_num)

        pixel_array_color = np.array(
            generate_comparison_colormix([orig_image, fused_image],
                                         arr_slice=image_slice,
                                         window=windowing))

        # resize dimensions to stop image stretch
        pixel_array_color = np.resize(pixel_array_color, (512, 345, 3))

        # first adjusts rgb (0,1) scale to greyscale (0,255)
        # then converts type and formats it to color.
        qimage2 = QtGui.QImage(((255 * pixel_array_color).astype(np.uint8)),
                               image_array.shape[1], image_array.shape[0],
                               QtGui.QImage.Format_RGB888)

        # Then continues to convert to pixmap just like in onko
        pixmap = QtGui.QPixmap(qimage2)
        pixmap = pixmap.scaled(512, 512, QtCore.Qt.IgnoreAspectRatio,
                               QtCore.Qt.SmoothTransformation)
    else:
        image_slice = return_slice("z", slice_num)

        pixel_array_color = np.array(
            generate_comparison_colormix([orig_image, fused_image],
                                         arr_slice=image_slice,
                                         window=windowing))

        # first adjusts rgb (0,1) scale to greyscale (0,255)
        # then converts type and formats it to color.
        qimage = QtGui.QImage(((255 * pixel_array_color).astype(np.uint8)),
                              image_array.shape[1], image_array.shape[1],
                              QtGui.QImage.Format_RGB888)

        # Then continues to convert to pixmap just like in onko
        pixmap = QtGui.QPixmap(qimage)
        pixmap = pixmap.scaled(512, 512, QtCore.Qt.IgnoreAspectRatio,
                               QtCore.Qt.SmoothTransformation)

    # Generates an rgb color overlaid image,
    # convert to contiguous array,
    # and also flip the array if it is a coronal (y) or sagittal (x)
    return pixmap