コード例 #1
0
 def set_blurs_thumbnails(self, event):
     """Устанавливает миниатюры для виджетов во вкладке Размытие
     Вызывается после изменения размеров одного из виджетов, так как изначально
     виджеты имеют неправильные размеры"""
     img = TransposeHandler.resize(self.default_image,
                                   self.default_blur_label.width(),
                                   self.default_blur_label.height())
     self.default_blur_label.setPixmap(ImageQt.toqpixmap(img))
     self.horizontal_blur_label.setPixmap(
         ImageQt.toqpixmap(BlurHandler.horizontal_blur(img)))
     self.vertical_blur_label.setPixmap(
         ImageQt.toqpixmap(BlurHandler.vertical_blur(img)))
     self.blurs_loaded = True
コード例 #2
0
    def Set_Filter_Label(self):

        self.filter_img_data = self.imgData.resize((300,300))
        self.Template_Label_1.setPixmap(ImageQt.toqpixmap(self.filter_img_data.filter(ImageFilter.BLUR)))
        self.Template_Label_1.setScaledContents(True)

        self.Template_Label_2.setPixmap(ImageQt.toqpixmap(self.filter_img_data.filter(ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 9, -1, -1, -1, -1), 1, 0))))
        self.Template_Label_2.setScaledContents(True)

        self.Template_Label_3.setPixmap(ImageQt.toqpixmap(self.filter_img_data.filter(ImageFilter.EMBOSS)))
        self.Template_Label_3.setScaledContents(True)

        self.Template_Label_4.setPixmap(ImageQt.toqpixmap(self.filter_img_data.filter(ImageFilter.MaxFilter)))
        self.Template_Label_4.setScaledContents(True)

        self.Template_Label_5.setPixmap(ImageQt.toqpixmap(self.filter_img_data.filter(ImageFilter.CONTOUR)))
        self.Template_Label_5.setScaledContents(True)

        self.Template_Label_6.setPixmap(ImageQt.toqpixmap(ImageEnhance.Color(self.filter_img_data).enhance(1)))
        self.Template_Label_6.setScaledContents(True)
        
        self.Template_Label_7.setPixmap(ImageQt.toqpixmap(ImageEnhance.Color(self.filter_img_data).enhance(0)))
        self.Template_Label_7.setScaledContents(True)

        self.filter_img_data = ImageEnhance.Color(self.filter_img_data).enhance(1.5)
        self.Template_Label_8.setPixmap(ImageQt.toqpixmap(ImageEnhance.Brightness(self.filter_img_data).enhance(1.5)))
        self.Template_Label_8.setScaledContents(True)
コード例 #3
0
 def open_image(self):
     """Открывает изображение, выбранное пользователем, вызывает функции для отображения миниатюр"""
     if not self.saved:
         flag = QMessageBox.question(
             self, '',
             'Есть несохраненные изменения\nВы точно хотите продолжить?',
             QMessageBox.Yes, QMessageBox.No)
         if flag == QMessageBox.No:
             return
     self.filename = QFileDialog.getOpenFileName(self,
                                                 'Выберите изображение', '',
                                                 'Image (*.jpg *.png)')[0]
     if self.filename != '':
         self.menu_tab.setVisible(True)
         image = ImageQt.toqpixmap(
             self.normalize_image(Image.open(self.filename)))
         self.image_label.setText('')
         self.image_label.setPixmap(image)
         self.default_image = ImageQt.fromqpixmap(image)
         self.image = self.default_image.copy()
         self.set_default_values()
         self.set_filters_thumbnails(None)
         self.set_blurs_thumbnails(None)
         self.history_manager = HistoryHandler(self, self.filename)
         self.update_image()
コード例 #4
0
 def del_channel(self, arr):
     pixmap = self.img_label.pixmap
     image = ImageQt.fromqpixmap(pixmap)
     data = pic.to_arr(image)
     modifided_image = pic.to_img(pic.del_channels(data, arr))
     pixmap = ImageQt.toqpixmap(modifided_image)
     self.img_label.paint(pixmap)
コード例 #5
0
ファイル: main.py プロジェクト: godnative/pythonProject
    def set_para(self):
        mydate_set = str(self.date_Edit.text())
        myda_set = str(self.DA_text.text())
        mydate2_set = str(self.Date2_text.text())
        myoms_set = str(self.lineEdit_3.text())
        mydate = self.str2pic(mydate_set, 'date')
        myda = self.str2pic(myda_set, 'da')
        mydate2 = self.str2pic(mydate2_set, 'date2')
        myoms = self.str2pic(myoms_set, 'oms')
        # output_pic=Image.new('RGB', (700, 400), color=(255, 255, 255))
        # output_pic.paste(mydate, (0, 0))
        # output_pic.paste(myda, (0, 100))
        # output_pic.paste(mydate2, (0, 200))
        # output_pic.paste(myoms, (0, 300))
        # output_pic.save('output.jpg')

        self.fapian.paste(mydate, (313, 612))
        self.fapian.paste(myda, (301, 1139))
        self.fapian.paste(mydate2, (920, 1137))
        self.fapian.paste(myoms, (315, 1354))
        width = int(self.fapian.size[0] * scale)
        height = int(self.fapian.size[1] * scale)
        figure_resize = self.fapian.resize((width, height))
        self.Show_pic_label.setPixmap(ImageQt.toqpixmap(figure_resize))
        self.fapian.save(pic_save_path)
        self.data_ini_save[0] = self.DA_text.text()
        self.data_ini_save[1] = self.Date2_text.text()
        self.data_ini_save[2] = self.lineEdit_3.text()
        s = str(self.data_ini_save[0]) + '\n' + str(
            self.data_ini_save[1]) + '\n' + str(self.data_ini_save[2]) + '\n'
        self.file_ini_write(self.file_path, s)
コード例 #6
0
 def slot_btn_dectv2(self):
     if not self.image:
         QMessageBox.critical(self, '错误', '没有加载图片', QMessageBox.Yes)
         return
     from detect_yolov2 import detectv2
     detected_image = detectv2(self.image.copy())
     self.disPicture.setPixmap(ImageQt.toqpixmap(detected_image))
コード例 #7
0
ファイル: main.py プロジェクト: godnative/pythonProject
 def set_moban(self):
     self.fapian = Image.open("picsrc/模板/" +
                              self.moban_select.currentText())
     width = int(self.fapian.size[0] * scale)
     height = int(self.fapian.size[1] * scale)
     figure_resize = self.fapian.resize((width, height))
     self.Show_pic_label.setPixmap(ImageQt.toqpixmap(figure_resize))
コード例 #8
0
ファイル: main.py プロジェクト: godnative/pythonProject
    def __init__(self, parent=None):
        super(PYQT5mainclass, self).__init__(parent)
        self.setupUi(self)
        a = os.listdir("picsrc/门店")
        self.mendian_select.addItems(a)
        self.mendian = Image.open("picsrc/门店/" +
                                  self.mendian_select.currentText())

        a = os.listdir("picsrc/模板")
        self.moban_select.addItems(a)
        self.fapian = Image.open("picsrc/模板/" +
                                 self.moban_select.currentText())

        self.date_Edit.setDateTime(QDateTime.currentDateTime())
        self.moban_select.currentIndexChanged.connect(self.set_moban)
        self.mendian_select.currentIndexChanged.connect(self.set_mendian)
        self.Set_para_Button.clicked.connect(self.set_para)

        width = int(self.fapian.size[0] * scale)
        height = int(self.fapian.size[1] * scale)
        figure_resize = self.fapian.resize((width, height))
        self.Show_pic_label.setPixmap(ImageQt.toqpixmap(figure_resize))

        self.file_path = 'cfg.dat'
        self.data_ini_save = self.file_ini_read(self.file_path)

        self.DA_text.setText(self.data_ini_save[0])
        self.Date2_text.setText(self.data_ini_save[1])
        self.lineEdit_3.setText(self.data_ini_save[2])
コード例 #9
0
ファイル: main.py プロジェクト: InfiniteYinux/Python
 def previewPhoto(self):
     pix = ImageQt.toqpixmap(self.img)
     self.label2.move((self.swinWidth - pix.width()) / 2, (self.swinHeight - pix.height()) / 2)
     self.label2.setPixmap(QtGui.QPixmap())
     self.label2.setPixmap(pix)
     self.label2.resize(pix.width(), pix.height())
     self.label2.setScaledContents(True)  # 图片自适应
コード例 #10
0
 def apply_effect(self, func):
     pixmap = self.img_label.pixmap
     image = ImageQt.fromqpixmap(pixmap)
     data = pic.to_arr(image)
     modifided_image = pic.to_img(func(data))
     pixmap = ImageQt.toqpixmap(modifided_image)
     self.img_label.paint(pixmap)
コード例 #11
0
 def add_filter(self):
     """Добавление фильтра"""
     QMessageBox.warning(
         self, 'Предупреждение',
         'Для правильной работы программы импортируйте файл .py,'
         'содержащий функции, предназначенные только для обработки'
         'изображений.\n'
         'Функции должны принимать на вход объекты класса PIL.Image.Image'
         'и возвращать так же объекты класса PIL.Image.Image.\n'
         'Файл, содержащий функции должен находиться в одной директории '
         'с main.py.', QMessageBox.Ok)
     name = QFileDialog.getOpenFileName(self, 'Открыть файл с фильтрами',
                                        '', "Python file (*.py)")[0]
     if name:
         file = importlib.import_module(name.split('/')[-1].split('.')[0])
         for func in inspect.getmembers(file, inspect.isfunction):
             label = self.add_filter_label(func[1])
             label.flag = False
             label.name = func[0]
             label.func = func[1]
             self.filter_labels_list.append(label)
             label.clicked.connect(self.activate_filter)
             if self.filters_loaded:
                 img = TransposeHandler.resize(
                     self.default_image, self.default_fliter_label.width(),
                     self.default_fliter_label.height())
                 label.setPixmap(ImageQt.toqpixmap(label.func(img)))
コード例 #12
0
ファイル: pedi_image.py プロジェクト: traumgedanken/pedi
    def __display_one(self, thumb, pedi_image):
        image_filtered = pedi_image.clone()
        self.__filterer.execute(image_filtered, thumb.name)

        preview_pixmap = ImageQt.toqpixmap(image_filtered.qimage)
        thumb.setPixmap(preview_pixmap)

        logging.debug('%s thumb updated' % thumb.name)
コード例 #13
0
ファイル: main.py プロジェクト: alexionby/segmentation_tool
    def read_pad_show(self, path, mask=None):
        image = Image.open(path)
        image = pad_to_square(image, self.main_label_size)
        image = ImageQt.toqpixmap(image)

        mask_path = path.replace(f'{self.imageDirLine.text()}/',
                                 f'{self.maskDirLine.text()}/')
        print(self.imageDirLine.text(), self.maskDirLine.text(), path,
              mask_path)

        if mask_path in self.masks_list:
            print('mask OK')
            mask = Image.open(mask_path)
            mask = pad_to_square(mask, self.main_label_size)
            mask = ImageQt.toqpixmap(mask)

        self.label.load_pixmap(image, mask)
コード例 #14
0
 def set_filters_thumbnails(self, event):
     """Устанавливает миниатюры для виджетов во вкладке Фильтры
     Вызывается после изменения размеров одного из виджетов, так как изначально
     виджеты имеют неправильные размеры"""
     img = TransposeHandler.resize(self.default_image,
                                   self.default_fliter_label.width(),
                                   self.default_fliter_label.height())
     self.default_fliter_label.setPixmap(ImageQt.toqpixmap(img))
     self.black_white_filter_label.setPixmap(
         ImageQt.toqpixmap(FilterHandler.black_white(img)))
     self.sepia_filter_label.setPixmap(
         ImageQt.toqpixmap(FilterHandler.sepia(img)))
     self.negative_filter_label.setPixmap(
         ImageQt.toqpixmap(FilterHandler.negative(img)))
     for label in self.filter_labels_list:
         label.setPixmap(ImageQt.toqpixmap(label.func(img)))
     self.filters_loaded = True
コード例 #15
0
    def bnr_load_dialog(self) -> bool:
        supportedFormats = {
            "*.bmp": "Windows Bitmap",
            "*.bnr": "Nintendo Banner",
            "*.ico": "Windows Icon",
            "*.jpg|*.jpeg": "JPEG Image",
            "*.png": "Portable Network Graphics",
            "*.ppm": "Portable Pixmap",
            "*.tga": "BMP Image",
            "*.tif": "Tagged Image",
            "*.webp": "WEBP Image"
        }

        _allsupported = " ".join(
            [" ".join(k.split("|")) for k in supportedFormats])
        _filter = f"All supported formats ({_allsupported});;" + ";;".join([
            f"{supportedFormats[k]} ({' '.join(k.split('|'))})"
            for k in supportedFormats
        ]) + ";;All files (*)"

        dialog = QFileDialog(parent=self,
                             caption="Open Image",
                             directory=str(self.bnrImagePath.parent if self.
                                           bnrImagePath else Path.home()),
                             filter=_filter)

        dialog.setFileMode(QFileDialog.ExistingFile)

        if dialog.exec_() != QFileDialog.Accepted:
            return False, ""

        self.bnrImagePath = Path(dialog.selectedFiles()[0]).resolve()

        if self.bnrImagePath.is_file():
            if self.bnrImagePath.suffix == ".bnr":
                self.bnrMap.rawImage = BytesIO(
                    self.bnrImagePath.read_bytes()[0x20:0x1820])
                self.bnr_update_info()
            else:
                with Image.open(self.bnrImagePath) as image:
                    if image.size != (96, 32):
                        dialog = JobWarningDialog(
                            f"Resizing image of size {image.size} to match BNR size (96, 32)",
                            self)
                        dialog.exec_()
                    self.bnrMap.rawImage = image
                pixmap = ImageQt.toqpixmap(self.bnrMap.getImage())
                pixmap = pixmap.scaled(
                    self.ui.bannerImageView.geometry().width() - 1,
                    self.ui.bannerImageView.geometry().height() - 1,
                    Qt.KeepAspectRatio)
                self.ui.bannerImageView.setPixmap(pixmap)

            return True, ""
        else:
            return False, "The file does not exist!"
コード例 #16
0
    def test_sanity(self):
        for mode in ('1', 'RGB', 'RGBA', 'L', 'P'):
            data = ImageQt.toqpixmap(hopper(mode))

            self.assertIsInstance(data, QPixmap)
            self.assertFalse(data.isNull())

            # Test saving the file
            tempfile = self.tempfile('temp_{}.png'.format(mode))
            data.save(tempfile)
コード例 #17
0
    def test_sanity(self, tmp_path):
        for mode in ("1", "RGB", "RGBA", "L", "P"):
            data = ImageQt.toqpixmap(hopper(mode))

            assert isinstance(data, QPixmap)
            assert not data.isNull()

            # Test saving the file
            tempfile = str(tmp_path / f"temp_{mode}.png")
            data.save(tempfile)
コード例 #18
0
    def test_sanity(self):
        for mode in ("1", "RGB", "RGBA", "L", "P"):
            data = ImageQt.toqpixmap(hopper(mode))

            self.assertIsInstance(data, QPixmap)
            self.assertFalse(data.isNull())

            # Test saving the file
            tempfile = self.tempfile("temp_{}.png".format(mode))
            data.save(tempfile)
コード例 #19
0
    def test_sanity(self):
        for mode in ('1', 'RGB', 'RGBA', 'L', 'P'):
            data = ImageQt.toqpixmap(hopper(mode))

            self.assertIsInstance(data, QPixmap)
            self.assertFalse(data.isNull())

            # Test saving the file
            tempfile = self.tempfile('temp_{}.png'.format(mode))
            data.save(tempfile)
コード例 #20
0
ファイル: filter.py プロジェクト: bluec0re/pascal-utils
    def load_pixmap(self, path, bb=None):
        im = Image.open(str(path)).convert('RGBA')

        if bb is not None:
            overlay = Image.new('L', im.size, color=255/2)
            overlaydraw = ImageDraw.Draw(overlay)
            overlaydraw.rectangle(bb, fill=0)
            black = Image.new('RGBA', im.size, color=0xFF000000)
            black.putalpha(overlay)
            im = Image.alpha_composite(im, black)
        return ImageQt.toqpixmap(im)
コード例 #21
0
ファイル: main.py プロジェクト: alexionby/segmentation_tool
    def mouseReleaseEvent(self, eventQMouseEvent):
        self.currentQRubberBand.hide()
        currentQRect = self.currentQRubberBand.geometry()
        self.currentQRubberBand.deleteLater()
        cropQPixmap = self.pixmap().copy(currentQRect)
        # cropQPixmap.save('output.png')

        crop_PIL = ImageQt.fromqpixmap(cropQPixmap)
        crop_PIL = pad_to_square(crop_PIL, self.target_size)
        cropQPixmap = ImageQt.toqpixmap(crop_PIL)
        self.setPixmap(cropQPixmap)
コード例 #22
0
ファイル: photo_editor.py プロジェクト: Rufoots/image-editor-
    def on_capture(self):
        
        cam = VideoCapture(0)   # 0 -> index of camera
        s, img = cam.read()
        if s:    # frame captured without any errors
             namedWindow("camcapture")
             imshow("camcapture",img)
             waitKey(0)
             destroyWindow("camcapture")
             imwrite("capture.jpg",img) #save image
             logger.debug("capture")
             img_path = 'capture.jpg'

        if img_path:
            logger.debug(f"open file {img_path}")

            self.file_name = ntpath.basename(img_path)

            pix = QPixmap(img_path)
            self.img_lbl.setPixmap(pix)
            self.img_lbl.setScaledContents(False)
            self.action_tabs.setVisible(True)
            self.action_tabs.adjustment_tab.reset_sliders()

            global _img_original
            _img_original = ImageQt.fromqpixmap(pix)

            self.update_img_size_lbl()

            if _img_original.width < _img_original.height:
                w = THUMB_SIZE
                h = _get_ratio_height(_img_original.width, _img_original.height, w)
            else:
                h = THUMB_SIZE
                w = _get_ratio_width(_img_original.width, _img_original.height, h)

            img_filter_thumb = img_helper.resize(_img_original, w, h)

            global _img_preview
            _img_preview = _img_original.copy()

            for thumb in self.action_tabs.filters_tab.findChildren(QLabel):
                if thumb.name != "none":
                    img_filter_preview = img_helper.color_filter(img_filter_thumb, thumb.name)
                else:
                    img_filter_preview = img_filter_thumb

                preview_pix = ImageQt.toqpixmap(img_filter_preview)
                thumb.setPixmap(preview_pix)

            self.reset_btn.setEnabled(True)
            self.save_btn.setEnabled(True)
            self.action_tabs.modification_tab.set_boxes()
コード例 #23
0
    def test_sanity(self):
        PillowQtTestCase.setUp(self)

        for mode in ('1', 'RGB', 'RGBA', 'L', 'P'):
            data = ImageQt.toqpixmap(hopper(mode))

            self.assertTrue(isinstance(data, QPixmap))
            self.assertFalse(data.isNull())

            # Test saving the file
            tempfile = self.tempfile('temp_{0}.png'.format(mode))
            data.save(tempfile)
コード例 #24
0
    def test_sanity(self):
        PillowQtTestCase.setUp(self)

        for mode in ("1", "RGB", "RGBA", "L", "P"):
            data = ImageQt.toqpixmap(hopper(mode))

            self.assertTrue(isinstance(data, QPixmap))
            self.assertFalse(data.isNull())

            # Test saving the file
            tempfile = self.tempfile("temp_{0}.png".format(mode))
            data.save(tempfile)
コード例 #25
0
 def get_qrcode(self, url):
     qr = qrcode.QRCode(
         version=None,
         error_correction=qrcode.constants.ERROR_CORRECT_L,
         box_size=10,
         border=1,
     )
     qr.add_data(str(url))
     qr.make(fit=True)
     img = qr.make_image(fill_color="black", back_color="white")
     pix = ImageQt.toqpixmap(img)
     self.qrcode_label.setPixmap(pix.scaled(self.qrcode_label.width(), self.qrcode_label.height()))
コード例 #26
0
    def on_upload(self, img_path):
        logger.debug("upload")
        if img_path:
            logger.debug("open file " + img_path)

            imageUri = QtCore.QUrl(
                QtCore.QString("file://{0}".format(img_path)))

            self.file_name = ntpath.basename(str(img_path))

            pix = QPixmap(str(img_path))
            self.img_lbl.setPixmap(pix)
            self.img_lbl.setScaledContents(True)
            self.action_tabs.setVisible(True)
            self.action_tabs.adjustment_tab.reset_sliders()

            global _img_original
            _img_original = ImageQt.fromqpixmap(pix)

            self.update_img_size_lbl()

            logger.debug("_img_original.width " + str(_img_original.width))
            logger.debug("_img_original.height " + str(_img_original.height))
            h = THUMB_SIZE
            w = THUMB_SIZE
            if _img_original.width < _img_original.height:
                w = THUMB_SIZE
                h = _get_ratio_height(_img_original.width,
                                      _img_original.height, w)
            elif _img_original.width > _img_original.height:
                h = THUMB_SIZE
                w = _get_ratio_width(_img_original.width, _img_original.height,
                                     h)

            img_filter_thumb = img_helper.resize(_img_original, w, h)

            global _img_preview
            _img_preview = _img_original.copy()

            for thumb in self.action_tabs.filters_tab.findChildren(QLabel):
                if thumb.name != "none":
                    img_filter_preview = img_helper.color_filter(
                        img_filter_thumb, thumb.name)
                else:
                    img_filter_preview = img_filter_thumb

                preview_pix = ImageQt.toqpixmap(img_filter_preview)
                thumb.setPixmap(preview_pix)

            self.reset_btn.setEnabled(True)
            self.save_btn.setEnabled(True)
            self.action_tabs.modification_tab.set_boxes()
コード例 #27
0
    def bnr_update_info(self, *args):
        if len(self.bnrMap) == 0:
            return

        self.ui.bannerGroupBox.setEnabled(True)

        bnrComboBox = self.ui.bannerComboBox
        bnrLangComboBox = self.ui.bannerLanguageComboBox

        bnrComboBox.blockSignals(True)
        bnrLangComboBox.blockSignals(True)

        bnrLangComboBox.setItemText(0, "English")

        curBnrName = bnrComboBox.currentText()
        if not curBnrName in self.bnrMap:
            curBnrName = list(self.bnrMap.keys())[0]
            bnrComboBox.setCurrentText(curBnrName)

        bnr = self.bnrMap[curBnrName]

        pixmap = ImageQt.toqpixmap(bnr.get_image())
        pixmap = pixmap.scaled(self.ui.bannerImageView.geometry().width() - 1,
                               self.ui.bannerImageView.geometry().height() - 1,
                               Qt.KeepAspectRatio)
        self.ui.bannerImageView.setPixmap(pixmap)
        self.ui.bannerImageView.setFrameShape(QFrame.NoFrame)

        self.ui.bannerVersionTextBox.setPlainText(bnr.magic)
        if bnr.magic == "BNR2":
            bnr.index = bnrLangComboBox.currentIndex()
            bnrLangComboBox.setEnabled(True)
        else:
            bnr.index = 0
            bnrLangComboBox.setCurrentIndex(0)
            bnrLangComboBox.setEnabled(False)

        if bnr.region == "NTSC-J":
            bnrLangComboBox.setItemText(0, "Japanese")
        else:
            bnrLangComboBox.setItemText(0, "English")

        self.ui.bannerVersionTextBox.setEnabled(False)

        self.ui.bannerShortNameTextBox.setPlainText(bnr.gameName)
        self.ui.bannerLongNameTextBox.setPlainText(bnr.gameTitle)
        self.ui.bannerShortMakerTextBox.setPlainText(bnr.developerName)
        self.ui.bannerLongMakerTextBox.setPlainText(bnr.developerTitle)
        self.ui.bannerDescTextBox.setPlainText(bnr.gameDescription)

        bnrComboBox.blockSignals(False)
        bnrLangComboBox.blockSignals(False)
コード例 #28
0
    def on_upload(self):

        global img_path

        logger.debug("upload")
        img_path, _ = QFileDialog.getOpenFileName(self.parent, "Open image",
                                                  "/Users",
                                                  "Images (*.png *jpg)")

        if img_path:
            logger.debug(f"open file {img_path}")

            self.file_name = ntpath.basename(img_path)

            pix = QPixmap(img_path)
            self.img_lbl.setPixmap(pix)
            self.img_lbl.setScaledContents(True)
            self.action_tabs.setVisible(True)
            self.action_tabs.adjustment_tab.reset_sliders()

            global _img_original
            _img_original = ImageQt.fromqpixmap(pix)

            self.update_img_size_lbl()

            if _img_original.width < _img_original.height:
                w = THUMB_SIZE
                h = _get_ratio_height(_img_original.width,
                                      _img_original.height, w)
            else:
                h = THUMB_SIZE
                w = _get_ratio_width(_img_original.width, _img_original.height,
                                     h)

            img_filter_thumb = img_helper.resize(_img_original, w, h)

            global _img_preview
            _img_preview = _img_original.copy()

            for thumb in self.action_tabs.filters_tab.findChildren(QLabel):
                if thumb.name != "none":
                    img_filter_preview = img_helper.color_filter(
                        img_filter_thumb, thumb.name)
                else:
                    img_filter_preview = img_filter_thumb

                preview_pix = ImageQt.toqpixmap(img_filter_preview)
                thumb.setPixmap(preview_pix)

            self.reset_btn.setEnabled(True)
            self.save_btn.setEnabled(True)
            self.action_tabs.modification_tab.set_boxes()
コード例 #29
0
    def place_preview_img(self):

        if not (operations.color_filter == None
                or operations.color_filter == 'none'):
            img = _get_img_with_all_operations()
            img = img_helper.color_filter(img, operations.color_filter)
        else:
            img = _get_img_with_all_operations()

        preview_pix = ImageQt.toqpixmap(img)
        self.img_lbl.setPixmap(preview_pix)

        print("Canvas Updated!!")
コード例 #30
0
 def read_dataset(self):
     self.label_2.setText(" ")
     batch = get_test_data_loader(1)
     image, label = next(iter(batch))
     self.image = image  #将tensor传走
     self.label_3.setText(str(label.numpy()))
     image = image.squeeze(dim=0)
     unloader = transforms.ToPILImage()
     image = unloader(image)
     pixmap = ImageQt.toqpixmap(image)
     jpg = QtGui.QPixmap(pixmap).scaled(self.label.width(),
                                        self.label.height())
     self.label.setPixmap(jpg)
コード例 #31
0
    def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle("PyQt Image Viewer")

        # Open up image in Pillow
        image = Image.open("pink_flower.jpg")
        pixmap = ImageQt.toqpixmap(image)

        self.image_label = QLabel('')
        self.image_label.setPixmap(pixmap)

        self.main_layout = QVBoxLayout()
        self.main_layout.addWidget(self.image_label)
        self.setLayout(self.main_layout)
コード例 #32
0
    def update_image(self):
        """Обновляет отображаемое изображение, применяет необходимые функции
        Вызывается при любом изменении изобраения"""
        self.image = self.default_image.copy()
        for key, value in self.crop.items():
            self.image = TransposeHandler.crop(self.image, key, value)
        self.image = TransposeHandler.rotate(self.image, self.rotation)
        if self.horizontal_flip:
            self.image = TransposeHandler.horizontal_flip(self.image)
        if self.vertical_flip:
            self.image = TransposeHandler.vertical_flip(self.image)
        self.image = self.normalize_image(self.image)

        self.image = AdjustmentHandler.brightness(self.image, self.brightness)
        self.image = AdjustmentHandler.contrast(self.image, self.contrast)
        self.image = AdjustmentHandler.sharpness(self.image, self.sharpness)

        for label in self.filter_labels_list:
            print(f'{label.name}: {label.flag}')

        if any(map(attrgetter('flag'), self.filter_labels_list)):
            for label in self.filter_labels_list:
                if label.flag:
                    self.image = label.func(self.image)
                    self.current_filter = label.name
                    label.setStyleSheet(ON_SS)
                    break

        for label in self.blurs_labels_list:
            print(f'{label.name}: {label.flag}')

        if self.horizontal_blur_label.flag:
            self.image = self.horizontal_blur_label.func(self.image)
            self.horizontal_blur_label.setStyleSheet(ON_SS)
            self.current_blur = self.horizontal_blur_label.name
        elif self.vertical_blur_label.flag:
            self.image = self.vertical_blur_label.func(self.image)
            self.vertical_blur_label.setStyleSheet(ON_SS)
            self.current_blur = self.vertical_blur_label.name
        else:
            self.default_blur_label.setStyleSheet(ON_SS)
            self.current_blur = 'По_умолчанию'

        self.image_label.setPixmap(ImageQt.toqpixmap(self.image))
        self.saved = False
        if self.write and self.history_manager is not None:
            self.history_manager.write()
        self.write = True
コード例 #33
0
ファイル: main.py プロジェクト: alexionby/segmentation_tool
    def updateLabel(self, value):
        self.rotate_label.setText(str(value))
        self.rotate_slider.setValue(value)

        image = ImageQt.fromqpixmap(self.label.original_image_pixmap)
        image = image.rotate(-1 * value)

        mask = self.label.original_mask_pixmap
        if mask:
            mask = ImageQt.fromqpixmap(mask)
            mask = mask.rotate(-1 * value)
            pixmap = self.label.merge_image_mask(image, mask)
        else:
            pixmap = ImageQt.toqpixmap(image)

        self.label.setPixmap(pixmap)
コード例 #34
0
ファイル: grouper.py プロジェクト: bluec0re/pascal-utils
    def load(self):
        self.leftList.clear()
        self.rightList.clear()
        self.topList.clear()
        self.bottomList.clear()
        self._history = []
        self.img_index = 0
        self.obj_index = 0

        image_lists = [[]] * 4
        for i in range(4):
            with self._outfile(i).open('r') as fp:
                image_lists[i] = [line.strip().rsplit(' ', 1) for line in fp.readlines()]

        for i, image in enumerate(self.pascalClass.images):
            for j, bb in enumerate(self.pascalClass.bounding_boxes[image.stem]):
                empty = True
                for k in range(4):
                    if len(image_lists[k]) > 0:
                        empty = False
                        if image_lists[k][0][0] == image.stem and image_lists[k][0][1] == str(j):
                            image_lists[k].pop(0)
                            im = Image.open(str(image)).convert('RGBA')
                            overlay = Image.new('L', im.size, color=255/2)
                            overlaydraw = ImageDraw.Draw(overlay)
                            overlaydraw.rectangle(bb, fill=0)
                            black = Image.new('RGBA', im.size, color=0xFF000000)
                            black.putalpha(overlay)
                            im = Image.alpha_composite(im, black)
                            pixmap = ImageQt.toqpixmap(im)

                            self._history.append((k, self.lists[k], self.lists[k].addImage(pixmap, image)))
                            break
                if empty:
                    break
            if empty:
                break
        self.img_index = i
        self.obj_index = j
        self.next()
コード例 #35
0
ファイル: main_window.py プロジェクト: CruizeMissile/Shiro
    def update_manga_list(self):
        cursor = Library.db.cursor()
        query = "SELECT title, cover_url FROM manga ORDER BY title"
        cursor.execute(query)
        data_query = cursor.fetchall()
        self.manga_list.clear()

        for data in data_query:
            title = data[0]
            cover_file = os.path.join(Library.directory, ".Cover", title + ".jpg")
            if not os.path.isfile(cover_file):
                continue
            # Needs to be a copy as it will resize the actual image in the library dict
            image = Library.covers[title].copy()
            image = image.resize((self.icon_size.width(), self.icon_size.height()), Image.ANTIALIAS)
            pix_map = ImageQt.toqpixmap(image)
            icon = QtGui.QIcon(pix_map)
            item = QtGui.QListWidgetItem(title, self.manga_list)
            item.setStatusTip(title)
            item.setIcon(icon)
            item.setSizeHint(self.icon_size + self.icon_padding)
            item.setBackgroundColor(QtGui.QColor("#F9F9F9"))
コード例 #36
0
 def roundtrip(self, expected):
     PillowQtTestCase.setUp(self)
     result = ImageQt.fromqpixmap(ImageQt.toqpixmap(expected))
     # Qt saves all pixmaps as rgb
     self.assert_image_equal(result, expected.convert('RGB'))
コード例 #37
0
ファイル: main_window.py プロジェクト: CruizeMissile/Shiro
    def update_info_panel(self):
        cursor = Library.db.cursor()

        # Getting the selected item
        item = self.manga_list.currentItem()
        title = item.text()
        cover = Library.covers[title]
        # cover.thumbnail((235, 350), Image.ANTIALIAS)
        pix_map = ImageQt.toqpixmap(cover)
        pix_map = pix_map.scaledToHeight(350, QtCore.Qt.SmoothTransformation)
        self.cover_label.setPixmap(pix_map)
        self.cover_label.resize(pix_map.size())

        query = (
            "SELECT title, authors, year, genre, publish_status, "
            "scan_status, description FROM manga WHERE title='{}'".format(title)
        )
        cursor.execute(query)
        data = cursor.fetchone()

        if data is None:
            self.show_clean_info_panel()
            return

        # Breaking up the genre string so that it is not so big
        genre_string = data[3].split(",")
        genre = ""
        character_count = 0
        for g in genre_string:
            word_count = len(g)
            if character_count + word_count >= 24:
                genre += "\n{}".format(g)
                character_count = word_count
            else:
                if len(genre) == 0:
                    genre = g
                else:
                    genre += ", {}".format(g)
                character_count += word_count

        author_string = data[1].split(",")
        author = ""
        character_count = 0
        for a in author_string:
            word_count = len(a)
            if character_count + word_count >= 24:
                author += "\n{}".format(a)
                character_count = word_count
            else:
                if len(author) == 0:
                    author = a
                else:
                    author += ", {}".format(a)
                character_count += word_count

        title = ""
        character_count = 0
        for word in data[0].split(" "):
            word_count = len(word)
            if character_count + word_count >= 25:
                title += "\n{}".format(word)
                character_count = word_count
            else:
                if len(title) == 0:
                    title = word
                else:
                    title += " {}".format(word)
                    character_count += word_count

        # Setting all of the label to display the information
        self.label_title.setText(title)
        # self.label_title.setText(data[0])
        self.label_author.setText(author)
        self.label_year.setText(str(data[2]))
        self.label_genre.setText(genre)
        self.label_publish.setText(data[4])
        self.label_scan.setText(data[5])
        self.description_box.setText(data[6])
        self.status_message(title)