Hong-Phuc Bui
2024-09-27 45c96fe258657363ef4ad1a2ae93513ca4139e26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import sys
 
from PySide6.QtGui import QPixmap, QImage
#from PIL.ImageQt import QPixmap, QImage
 
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog
import numpy as np
from PIL import Image
 
from imgdemo.ui_mainwindow import Ui_MainWindow
 
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.saved_file = ('', '')
        self.chosen_file = ('', '')
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.actionChoose_Image.triggered.connect(self.choose_image)
        self.ui.actionSave_Image.triggered.connect(self.save_image)
 
    def choose_image(self):
        self.chosen_file = ('', '') # reset (for safe)
        self.chosen_file = QFileDialog.getOpenFileName(None, "Choose Image", "",
                                                       "Images (*.png *.xpm *.jpg *.tiff) ;; All Filetypes (*.*)")
        print(self.chosen_file)
        if self.chosen_file[0] != '':  # user has chosen a file
            self.display_image()
 
 
    def save_image(self):
        self.saved_file = ('', '') # reset for safe
        self.saved_file = QFileDialog.getSaveFileName(None, "Choose Image", "",
                                                       "All (*.*)")
        print(self.saved_file)
 
 
    def display_image(self):
        pixmap = QPixmap(self.chosen_file[0])
        self.ui.origin_img.setPixmap(pixmap)
        # now read the image and show it via Image in other container
        with Image.open(self.chosen_file[0]) as img:
            image = np.asarray(img, dtype=np.uint8)
            self.display_numpy_image(image)
 
 
    def display_numpy_image(self, image):
        height, width, channel = image.shape
        print(height, width, channel)
 
        bytes_per_line = channel * width  # color
        img_format = QImage.Format.Format_RGBX8888
        if channel == 4:
            img_format =  QImage.Format.Format_ARGB32
        elif channel == 3:
            img_format = QImage.Format.Format_RGB888
        qImg = QImage(image.data, width, height, bytes_per_line, img_format).rgbSwapped()
        pixmap = QPixmap(qImg)
        self.ui.result_img.setPixmap(pixmap)
 
 
 
 
def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
 
    sys.exit(app.exec())
    pass
 
 
if __name__ == "__main__":
    main()