Qslider не будет передавать параметр в PyQt5 - PullRequest
0 голосов
/ 25 января 2020

моя функция не будет работать, когда значение slider изменилось, я не знаю почему? я впервые использую PyQt5.

from PIL.ImageQt import Image, ImageQt
from PIL import ImageEnhance

from PyQt5.QtWidgets import (QApplication, QDialog, QGridLayout,
                             QLabel, QPushButton, QGroupBox,
                             QSlider, QVBoxLayout, QFileDialog)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QIcon


class MainWindow(QDialog):
    def __init__(self):
        super(MainWindow,self).__init__()

        self.originalPalette = QApplication.palette()
#        self.setAcceptDrops(True)

        self.createTopGroupBox()
        self.createBottomGroupBox()
#        self.color("blue")

        mainLayout = QGridLayout()
        mainLayout.addWidget(self.topGroupBox, 0, 0)
        mainLayout.addWidget(self.bottomGroupBox, 1, 0)        
        #mainLayout.setRowStretch(1, 1)
        #mainLayout.setRowStretch(2, 1)
        #mainLayout.setColumnStretch(0, 1)
        #mainLayout.setColumnStretch(1, 1)
        self.setLayout(mainLayout)

        self.setWindowTitle("Photo Editor")    
        self.resize(800, 800)

    def createTopGroupBox(self):  

        self.topGroupBox = QGroupBox()
        openImgButton = QPushButton("Open Image")
        openImgButton.clicked.connect(self.getImage)
        self.label = QLabel("Your Photo")

        layout = QVBoxLayout()
        layout.addWidget(openImgButton)
        layout.addWidget(self.label)
        layout.addStretch(1)
        self.topGroupBox.setLayout(layout)

    def getImage(self):
        global fname
        fname = QFileDialog.getOpenFileName(self, 'Open file',
               'c:\ ', "Image files (*.jpeg *.jpg *.gif *.bmp *.png))")
        imagePath = fname[0]
        #pixmap = QPixmap(imagePath)
        self.image = Image.open(imagePath)
        self.qimage = ImageQt(self.image)
        self.label.setPixmap(QPixmap.fromImage(self.qimage))
        self.resize(self.qimage.width(), self.qimage.height())

    def createBottomGroupBox(self):

        self.bottomGroupBox = QGroupBox()

        self.sliderBrightness = QSlider(Qt.Horizontal, self)
        brightnessLabel = QLabel("Brightness:")
        brightnessLabel.setBuddy(self.sliderBrightness)
        self.sliderBrightness.setTickPosition(QSlider.TicksBelow)
        self.sliderBrightness.setTickInterval(1)
        self.sliderBrightness.setValue(100)
        self.sliderBrightness.setMinimum(0)
        self.sliderBrightness.setMaximum(200)
        self.brightnessValueLabel = QLabel("1")

        self.sliderContrast = QSlider(Qt.Horizontal, self)
        contrastLabel = QLabel("Contrast:")
        contrastLabel.setBuddy(contrastLabel)
        self.sliderContrast.setValue(1)
        self.sliderContrast.setMinimum(0)
        self.sliderContrast.setMaximum(2)
        self.contrastValueLabel = QLabel("1")

        sliderSharpness = QSlider(Qt.Horizontal, self)
        sharpnessLabel = QLabel("Sharpness:")
        sharpnessLabel.setBuddy(sharpnessLabel)
        sliderSharpness.setValue(1)
        sliderSharpness.setMinimum(0)
        sliderSharpness.setMaximum(2)
        self.sharpnessValueLabel = QLabel("1")

        savePushButton = QPushButton("Save")
        savePushButton.clicked.connect(self.saveImage("image.png", "PNG"))

        self.sliderBrightness.valueChanged.connect(self.valueChangeBrightness)
        self.sliderContrast.valueChanged.connect(self.valueChangeContrast)
        sliderSharpness.valueChanged.connect(self.valueChangeSharpness)

        layout = QVBoxLayout()
        layout.addWidget(brightnessLabel)
        layout.addWidget(self.sliderBrightness, 0)
        layout.addWidget(self.brightnessValueLabel)
        layout.addWidget(contrastLabel)
        layout.addWidget(self.sliderContrast, 1)
        layout.addWidget(sharpnessLabel)
        layout.addWidget(sliderSharpness, 2)
        layout.addWidget(savePushButton, 3)
        self.bottomGroupBox.setLayout(layout)

    def saveImage(self, fileName, fileFormat):
        self.editImage.save(fileName, fileFormat)            

    def valueChangeBrightness(self, sliderValue):

        factor = float(sliderValue)/100
        enhancer_object = ImageEnhance.Brightness(self.image)
        self.editImage = enhancer_object.enhance(factor)
        self.brightnessValueLabel.setText(str(self.sliderBrightness.value()))       

    def valueChangeContrast(self, factor):

        enhancer_object = ImageEnhance.Contrast(self.image)
        enhancer_object.enhance(factor)

    def valueChangeSharpness(self, factor):

        enhancer_object = ImageEnhance.Sharpness(self.image)
        enhancer_object.enhance(factor)


if __name__ == '__main__':

    import sys

    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

1 Ответ

0 голосов
/ 26 января 2020

Основная проблема в коде OP заключается в том, что он не обновил показанное изображение. Например, если документы проверяются, подразумевается, что метод расширения возвращает измененное изображение, но не сохраняется и не отображается.

С другой стороны, применение изменений должно быть каскадным (одно после other).

Существуют также ошибки, такие как не проверка того, что имя файла является пустой строкой, кроме того, что нажатый сигнал связан с завершением работы, а не с возвращаемой оцененной функцией.

Учитывая вышеизложенное, решение:

from PIL.ImageQt import Image, ImageQt
from PIL import ImageEnhance

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (
    QApplication,
    QDialog,
    QGridLayout,
    QLabel,
    QPushButton,
    QGroupBox,
    QSlider,
    QVBoxLayout,
    QFileDialog,
)


class MainWindow(QDialog):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.createTopGroupBox()
        self.createBottomGroupBox()
        mainLayout = QGridLayout(self)
        mainLayout.addWidget(self.topGroupBox, 0, 0)
        mainLayout.addWidget(self.bottomGroupBox, 1, 0)

        self.setWindowTitle("Photo Editor")
        self.resize(800, 800)

        self.input_image = None
        self.output_image = None

    def createTopGroupBox(self):
        self.topGroupBox = QGroupBox()
        openImgButton = QPushButton("Open Image")
        openImgButton.clicked.connect(self.getImage)
        self.label = QLabel("Your Photo")

        layout = QVBoxLayout()
        layout.addWidget(openImgButton)
        layout.addWidget(self.label)
        layout.addStretch(1)
        self.topGroupBox.setLayout(layout)

    def getImage(self):
        fname, _ = QFileDialog.getOpenFileName(
            self, "Open file", "", "Image files (*.jpeg *.jpg *.gif *.bmp *.png)"
        )
        if fname:
            self.input_image = Image.open(fname)
            self.show_image(self.input_image)

    def show_image(self, image):
        qimage = ImageQt(image)
        self.label.setPixmap(QPixmap.fromImage(qimage))

    def createBottomGroupBox(self):
        self.bottomGroupBox = QGroupBox()
        self.sliderBrightness = QSlider(
            Qt.Horizontal,
            tickPosition=QSlider.TicksBelow,
            tickInterval=1,
            value=100,
            minimum=0,
            maximum=200,
        )
        brightnessLabel = QLabel("Brightness:")
        brightnessLabel.setBuddy(self.sliderBrightness)

        self.brightnessValueLabel = QLabel()
        self.brightnessValueLabel.setNum(self.sliderBrightness.value())

        self.sliderContrast = QSlider(Qt.Horizontal, value=1, minimum=0, maximum=2)
        contrastLabel = QLabel("Contrast:")
        contrastLabel.setBuddy(self.sliderContrast)
        self.contrastValueLabel = QLabel()
        self.contrastValueLabel.setNum(self.sliderContrast.value())

        self.sliderSharpness = QSlider(Qt.Horizontal, value=1, minimum=0, maximum=2)
        sharpnessLabel = QLabel("Sharpness:")
        sharpnessLabel.setBuddy(self.sliderSharpness)
        self.sharpnessValueLabel = QLabel()
        self.sharpnessValueLabel.setNum(self.sliderSharpness.value())

        savePushButton = QPushButton("Save")
        savePushButton.clicked.connect(lambda: self.saveImage("image.png", "PNG"))

        self.sliderBrightness.valueChanged.connect(self.update_image)
        self.sliderContrast.valueChanged.connect(self.update_image)
        self.sliderSharpness.valueChanged.connect(self.update_image)

        layout = QVBoxLayout()
        layout.addWidget(brightnessLabel)
        layout.addWidget(self.sliderBrightness)
        layout.addWidget(self.brightnessValueLabel)

        layout.addWidget(contrastLabel)
        layout.addWidget(self.sliderContrast)
        layout.addWidget(self.contrastValueLabel)

        layout.addWidget(sharpnessLabel)
        layout.addWidget(self.sliderSharpness)
        layout.addWidget(self.sharpnessValueLabel)

        layout.addWidget(savePushButton)
        self.bottomGroupBox.setLayout(layout)

    def saveImage(self, fileName, fileFormat):
        if self.output_image is not None:
            self.output_image.save(fileName, fileFormat)

    def update_image(self):
        if self.input_image is not None:
            factor_brightness = self.sliderBrightness.value() / 100.0
            factor_contrast = self.sliderContrast.value()
            factor_sharpness = self.sliderSharpness.value()

            enhancer_object = ImageEnhance.Brightness(self.input_image)
            image = enhancer_object.enhance(factor_brightness)
            enhancer_object = ImageEnhance.Contrast(image)
            image = enhancer_object.enhance(factor_contrast)
            enhancer_object = ImageEnhance.Sharpness(image)
            self.output_image = enhancer_object.enhance(factor_sharpness)
            self.show_image(self.output_image)


if __name__ == "__main__":

    import sys

    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
...