Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Image can't Show in Page2
QtWS25 Last Chance

Image can't Show in Page2

Scheduled Pinned Locked Moved Solved General and Desktop
pyqt6software
9 Posts 4 Posters 849 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    AlbertRicky
    wrote on last edited by AlbertRicky
    #1

    I can't find any error in my code, but why image in SecondPage is not shown in a label2 as I have defined below.

    ############ LIBRARY WAJAH ##############
    import cv2
    import math
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    import numpy as np
    from PIL import Image
    import os
    
    from keras import backend as K
    from keras.models import load_model
    from keras.preprocessing import image
    from mtcnn import MTCNN
    ########################################
    
    from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QFileDialog, QStackedWidget, QMessageBox, QComboBox
    from PyQt6.QtGui import QPixmap, QImage
    from PyQt6 import uic
    
    class MainWindow(QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            uic.loadUi("D:/Thesis Final/Apps/Gender_and_Age.ui", self)
            
            self.button1 = self.findChild(QPushButton, "pushButton")
            self.button1.setEnabled(True)  # Menonaktifkan tombol saat pertama kali aplikasi dijalankan
            self.button1.clicked.connect(self.Load_Image)
            self.label = self.findChild(QLabel, "label")
            
            self.button2 = self.findChild(QPushButton, "pushButton_2")
            self.button2.clicked.connect(self.gotoSecondPage)
            
        def Load_Image(self):
            fname = QFileDialog.getOpenFileName(self, "Open File")
            
            if fname[0]:
                # Open the image
                self.pixmap = QPixmap(fname[0])
                self.label.setPixmap(self.pixmap)
                self.fname = fname
            
        def gotoSecondPage(self):
            if hasattr(self, 'fname'):  # Memeriksa apakah gambar telah dipilih sebelum pindah ke halaman kedua
                secondpage = SecondPage(self.fname[0])
                widget.addWidget(secondpage)
                widget.setCurrentIndex(widget.currentIndex()+1)
            else:
                # Menampilkan pesan kesalahan jika gambar belum dipilih
                QMessageBox.warning(self, 'Warning', 'Please select an image first!')
    
    class SecondPage(QMainWindow) :
        def __init__(self, fname) :  # Tambahkan parameter fname
            super(SecondPage, self).__init__()
    
            uic.loadUi("D:/Thesis Final/Apps/Second_Page.ui", self)
    
            self.button = self.findChild(QPushButton, "backButton")
            self.button.clicked.connect(self.gotoFirstPage)
            
            #self.label2 = self.findChild(QLabel, "labelilustrasi")
            
            self.fname = fname # simpan nilai atribut fname
            print(self.fname)
            print(type(self.fname))
            
            if self.fname :
                self.label2 = self.findChild(QLabel, "labelilustrasi")
                self.display_image()
                
                self.show()
                
            else :
                print("File Not Found")
    
        def display_image(self):
            face_detector = MTCNN()
            img = cv2.imread(self.fname)
            img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #mtcnn expects RGB but OpenCV read BGR
            detections = face_detector.detect_faces(img_rgb)
            print(detections)
            
            # call function to process image and get numpy ndarray
            img2 = self.draw_facebox(self.fname, [detections[0]])
    
            # convert numpy ndarray to QImage
            height, width, channel = img2.shape
            bytesPerLine = 3 * width
            qImg = QImage(img2.data, width, height, bytesPerLine, QImage.Format.Format_RGB888)
    
            # set QPixmap from QImage
            pixmap2 = QPixmap.fromImage(qImg)
    
            # set label with pixmap
            self.label2.setPixmap(pixmap2)
    
        def draw_facebox(self, filename, result_list):
            # load the image
            img = cv2.imread(filename)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            # plot each box
            for result in result_list:
                # get coordinates
                x, y, width, height = result['box']
                # draw the box
                cv2.rectangle(img, (x, y), (x + width, y + height), (255, 255, 255), 2)
                # draw the dots
                # create and draw dot
                array = result['keypoints']['left_eye'], result['keypoints']['right_eye']
                for value in array:
                    cv2.circle(img, (int(value[0]), int(value[1])), 4, (255, 255, 255), -1)
            
            return img
                
            # Create combo box with options based on the number of detections
            #self.comboBox = self.findChild(QComboBox, "comboBox")
            #for i in range(len(detections)):
            #    self.comboBox.addItem(str(i))
            #self.comboBox.clicked.connect(self.Load_Image)
            
        def gotoFirstPage(self) :
            mainwindow = MainWindow()
            widget.addWidget(mainwindow)
            widget.setCurrentIndex(widget.currentIndex()-1)
            
    if __name__ == '__main__':
        app = QApplication([])
        widget = QStackedWidget()
        mainwindow = MainWindow()
        secondpage = SecondPage("")
        widget.addWidget(mainwindow)
        widget.addWidget(secondpage)
        widget.setFixedHeight(600)
        widget.setFixedWidth(820)
        widget.setWindowTitle("Gender and Age")
        widget.show()
        app.exec()
    
    

    If you net the UI File :

    • First UI : https://drive.google.com/file/d/1u__UmEOg2xiHX5qwuT4f7QkMqqkUmQ3H/view?usp=sharing
    • Second UI : https://drive.google.com/file/d/1nCoTN5oHaQwVhYXhFQCM0yYi48hF3nXO/view?usp=sharing

    Your help means a lot to me, thank you.

    Pl45m4P 1 Reply Last reply
    0
    • A AlbertRicky

      I can't find any error in my code, but why image in SecondPage is not shown in a label2 as I have defined below.

      ############ LIBRARY WAJAH ##############
      import cv2
      import math
      import matplotlib.pyplot as plt
      import matplotlib.image as mpimg
      import numpy as np
      from PIL import Image
      import os
      
      from keras import backend as K
      from keras.models import load_model
      from keras.preprocessing import image
      from mtcnn import MTCNN
      ########################################
      
      from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QFileDialog, QStackedWidget, QMessageBox, QComboBox
      from PyQt6.QtGui import QPixmap, QImage
      from PyQt6 import uic
      
      class MainWindow(QMainWindow):
          def __init__(self):
              super(MainWindow, self).__init__()
              uic.loadUi("D:/Thesis Final/Apps/Gender_and_Age.ui", self)
              
              self.button1 = self.findChild(QPushButton, "pushButton")
              self.button1.setEnabled(True)  # Menonaktifkan tombol saat pertama kali aplikasi dijalankan
              self.button1.clicked.connect(self.Load_Image)
              self.label = self.findChild(QLabel, "label")
              
              self.button2 = self.findChild(QPushButton, "pushButton_2")
              self.button2.clicked.connect(self.gotoSecondPage)
              
          def Load_Image(self):
              fname = QFileDialog.getOpenFileName(self, "Open File")
              
              if fname[0]:
                  # Open the image
                  self.pixmap = QPixmap(fname[0])
                  self.label.setPixmap(self.pixmap)
                  self.fname = fname
              
          def gotoSecondPage(self):
              if hasattr(self, 'fname'):  # Memeriksa apakah gambar telah dipilih sebelum pindah ke halaman kedua
                  secondpage = SecondPage(self.fname[0])
                  widget.addWidget(secondpage)
                  widget.setCurrentIndex(widget.currentIndex()+1)
              else:
                  # Menampilkan pesan kesalahan jika gambar belum dipilih
                  QMessageBox.warning(self, 'Warning', 'Please select an image first!')
      
      class SecondPage(QMainWindow) :
          def __init__(self, fname) :  # Tambahkan parameter fname
              super(SecondPage, self).__init__()
      
              uic.loadUi("D:/Thesis Final/Apps/Second_Page.ui", self)
      
              self.button = self.findChild(QPushButton, "backButton")
              self.button.clicked.connect(self.gotoFirstPage)
              
              #self.label2 = self.findChild(QLabel, "labelilustrasi")
              
              self.fname = fname # simpan nilai atribut fname
              print(self.fname)
              print(type(self.fname))
              
              if self.fname :
                  self.label2 = self.findChild(QLabel, "labelilustrasi")
                  self.display_image()
                  
                  self.show()
                  
              else :
                  print("File Not Found")
      
          def display_image(self):
              face_detector = MTCNN()
              img = cv2.imread(self.fname)
              img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #mtcnn expects RGB but OpenCV read BGR
              detections = face_detector.detect_faces(img_rgb)
              print(detections)
              
              # call function to process image and get numpy ndarray
              img2 = self.draw_facebox(self.fname, [detections[0]])
      
              # convert numpy ndarray to QImage
              height, width, channel = img2.shape
              bytesPerLine = 3 * width
              qImg = QImage(img2.data, width, height, bytesPerLine, QImage.Format.Format_RGB888)
      
              # set QPixmap from QImage
              pixmap2 = QPixmap.fromImage(qImg)
      
              # set label with pixmap
              self.label2.setPixmap(pixmap2)
      
          def draw_facebox(self, filename, result_list):
              # load the image
              img = cv2.imread(filename)
              img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
              # plot each box
              for result in result_list:
                  # get coordinates
                  x, y, width, height = result['box']
                  # draw the box
                  cv2.rectangle(img, (x, y), (x + width, y + height), (255, 255, 255), 2)
                  # draw the dots
                  # create and draw dot
                  array = result['keypoints']['left_eye'], result['keypoints']['right_eye']
                  for value in array:
                      cv2.circle(img, (int(value[0]), int(value[1])), 4, (255, 255, 255), -1)
              
              return img
                  
              # Create combo box with options based on the number of detections
              #self.comboBox = self.findChild(QComboBox, "comboBox")
              #for i in range(len(detections)):
              #    self.comboBox.addItem(str(i))
              #self.comboBox.clicked.connect(self.Load_Image)
              
          def gotoFirstPage(self) :
              mainwindow = MainWindow()
              widget.addWidget(mainwindow)
              widget.setCurrentIndex(widget.currentIndex()-1)
              
      if __name__ == '__main__':
          app = QApplication([])
          widget = QStackedWidget()
          mainwindow = MainWindow()
          secondpage = SecondPage("")
          widget.addWidget(mainwindow)
          widget.addWidget(secondpage)
          widget.setFixedHeight(600)
          widget.setFixedWidth(820)
          widget.setWindowTitle("Gender and Age")
          widget.show()
          app.exec()
      
      

      If you net the UI File :

      • First UI : https://drive.google.com/file/d/1u__UmEOg2xiHX5qwuT4f7QkMqqkUmQ3H/view?usp=sharing
      • Second UI : https://drive.google.com/file/d/1nCoTN5oHaQwVhYXhFQCM0yYi48hF3nXO/view?usp=sharing

      Your help means a lot to me, thank you.

      Pl45m4P Offline
      Pl45m4P Offline
      Pl45m4
      wrote on last edited by
      #2

      @AlbertRicky

      What do you get? Does the QStackedWidget page switch correctly and only the image is missing? Is the OCV image valid?


      If debugging is the process of removing software bugs, then programming must be the process of putting them in.

      ~E. W. Dijkstra

      A 1 Reply Last reply
      0
      • SGaistS Offline
        SGaistS Offline
        SGaist
        Lifetime Qt Champion
        wrote on last edited by
        #3

        Hi and welcome to devnet,

        The code you posted can't work for several reasons.

        First, you put a QMainWindow in a QStackedWidget, while not forbidden, it's really not the usual way to use them.
        Next, in your gotoFirstPage function, you don't go anywhere, you crate a new MainWindow and add it to the widget variable which does not exist there.
        Finally, using findChildren like that is a sign of architectural issue. You don't that when dealing with designer based widget.

        You really should redesign your widget handling logic and also use uic to generate the Python code from your ui files rather than use the uic module.

        Can you post a picture of what you want your widgets to look like ?

        Interested in AI ? www.idiap.ch
        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

        A 1 Reply Last reply
        1
        • SGaistS SGaist

          Hi and welcome to devnet,

          The code you posted can't work for several reasons.

          First, you put a QMainWindow in a QStackedWidget, while not forbidden, it's really not the usual way to use them.
          Next, in your gotoFirstPage function, you don't go anywhere, you crate a new MainWindow and add it to the widget variable which does not exist there.
          Finally, using findChildren like that is a sign of architectural issue. You don't that when dealing with designer based widget.

          You really should redesign your widget handling logic and also use uic to generate the Python code from your ui files rather than use the uic module.

          Can you post a picture of what you want your widgets to look like ?

          A Offline
          A Offline
          AlbertRicky
          wrote on last edited by AlbertRicky
          #4

          @SGaist Hi thank you for your response.

          Tampilan Forum_compressed.jpg

          This is the form of the application I want. Photo results from the function does not appear on the second page and i don't know why. No error shown

          JonBJ 1 Reply Last reply
          0
          • A AlbertRicky

            @SGaist Hi thank you for your response.

            Tampilan Forum_compressed.jpg

            This is the form of the application I want. Photo results from the function does not appear on the second page and i don't know why. No error shown

            JonBJ Offline
            JonBJ Offline
            JonB
            wrote on last edited by
            #5

            @AlbertRicky
            QStackedWidget is for showing just one of a number of widgets at any one time. I do not see a need for this on either page (assuming second page is intended to be a quite separate window from first page).

            A 1 Reply Last reply
            1
            • Pl45m4P Pl45m4

              @AlbertRicky

              What do you get? Does the QStackedWidget page switch correctly and only the image is missing? Is the OCV image valid?

              A Offline
              A Offline
              AlbertRicky
              wrote on last edited by
              #6

              @Pl45m4 Yes it's valid, i tested it on jupyter notebook before include to class PyQT6

              1 Reply Last reply
              0
              • JonBJ JonB

                @AlbertRicky
                QStackedWidget is for showing just one of a number of widgets at any one time. I do not see a need for this on either page (assuming second page is intended to be a quite separate window from first page).

                A Offline
                A Offline
                AlbertRicky
                wrote on last edited by
                #7

                @JonB Sorry so what should I use to make two pages. It's very difficult to find it on the internet, especially if I use it directly from the .ui file without converting it

                JonBJ Pl45m4P 2 Replies Last reply
                0
                • A AlbertRicky

                  @JonB Sorry so what should I use to make two pages. It's very difficult to find it on the internet, especially if I use it directly from the .ui file without converting it

                  JonBJ Offline
                  JonBJ Offline
                  JonB
                  wrote on last edited by JonB
                  #8

                  @AlbertRicky
                  I did say

                  assuming second page is intended to be a quite separate window from first page

                  Looking again, I see the button on these two screenshots is the same in the same place. So maybe you do not intend the "second page" to be an independent window after all? If you are replacing a rectangular area of one window with different widgets (is that what you want?) then a QStackedWidget is indeed the right thing to use.

                  1 Reply Last reply
                  0
                  • A AlbertRicky

                    @JonB Sorry so what should I use to make two pages. It's very difficult to find it on the internet, especially if I use it directly from the .ui file without converting it

                    Pl45m4P Offline
                    Pl45m4P Offline
                    Pl45m4
                    wrote on last edited by
                    #9

                    @AlbertRicky said in Image can't Show in Page2:

                    so what should I use to make two pages

                    Change the secondWindow type to QWidget (using QMainWindow there is weird) and make it a page of QStackedWidget.
                    You can design that widget with your QtDesigner and setup the layout with the label that should hold your image later.
                    Assign your result image with your detections to the label, when you have processed the source image and flip the pages with your buttons.

                    This can also be done in-place. Then you dont need a QStackedWidget. If you don't need to switch back and forth multiple times, but swtich one time to show the result, you could also "replace" the image on your current label, when clicking the button. But I dont know, what else you what to do on that second page widget.


                    If debugging is the process of removing software bugs, then programming must be the process of putting them in.

                    ~E. W. Dijkstra

                    1 Reply Last reply
                    0
                    • A AlbertRicky has marked this topic as solved on

                    • Login

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • Users
                    • Groups
                    • Search
                    • Get Qt Extensions
                    • Unsolved