Saturday, May 11, 2019

Image Histogram with OpenCV and PyQt

To know more about Python GUI, you can visit my book (LEARN FROM SCRATCH SIGNAL AND IMAGE PROCESSING WITH PYTHON GUI) on Amazon or Google Books.



In this tutorial, you will display image histogram with OpenCV and PyQt. Follow these steps below:
  1. Open Qt Designer. Create the form using the Main Window template:


  2. Click the Create button.
  3. Then, place a Push Button widget and a Label widget on the form.
  4. Specify the text property of the Push Button widget to Read Image dan that of Label widget to labelImage in the Property Editor window.
  5. Set the property of the objectName from the Push Button widget in the Property Editor window to pbImage.
  6. Place a Widget from the Containers panel on the form. Set the objectName property to be the widgetDisplay.
  7. Save the form with the name histogram.ui. Now, the form looks like it looks in the following figure:


  8. Next, right-click on the Widget and from  the context menu displayed select Promote to ...:


  9. Name the Promoted class name as Histogram:


  10. Then click the Add button and click the Promote button. In the Object Inspector window, you can see that widgetDisplay (Histogram class) along with the pbImage object (QPushButton class) is now in the centralwidget object (QWidget class).
  11. Define the Histogram class in a Python file with the same name:

  12. from PyQt5.QtWidgets import*
    from matplotlib.backends.backend_qt5agg import FigureCanvas
    from matplotlib.figure import Figure
        
    class Histogram(QWidget):    
        def __init__(self, parent = None):
            QWidget.__init__(self, parent)        
            self.canvas = FigureCanvas(Figure())
           
            vertical_layout = QVBoxLayout()
            vertical_layout.addWidget(self.canvas)
            
            self.canvas.sumbu1 = self.canvas.figure.add_subplot(111)
            self.canvas.figure.set_facecolor("xkcd:wheat")
            self.setLayout(vertical_layout)
    

  13. Define the new Python script with name main_histogram.py that defines the method display_histogram() and connect it with the clicked() event from pbImage widget:

  14. #main_histogram.py
    import cv2
    import numpy as np
    from PyQt5.QtWidgets import*
    from PyQt5.uic import loadUi
    from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar)
    from PyQt5.QtWidgets import QDialog, QFileDialog
    from PyQt5.QtGui import QIcon, QPixmap, QImage
    
    import numpy as np
    fname = ""
         
    class Display_Histogram(QMainWindow):   
        def __init__(self):
            
            QMainWindow.__init__(self)
            loadUi("histogram.ui",self)
    
            self.setWindowTitle("Image Histogram")
            self.pbImage.clicked.connect(self.display_histogram)
            self.addToolBar(NavigationToolbar(self.widgetDisplay.canvas, self))
    
        def display_histogram(self):
            global fname
            fname = QFileDialog.getOpenFileName(self, 'Open file', 
               'd:\\',"Image Files (*.jpg *.gif *.bmp *.png *.tiff)")
            pixmap = QPixmap(fname[0])
            self.labelImage.setPixmap(pixmap)
            self.labelImage.setScaledContents(True);
            
    
            self.widgetDisplay.canvas.sumbu1.clear()
            read_img = cv2.imread(fname[0], cv2.IMREAD_COLOR)
            color = ('b','g','r')
            for i,col in enumerate(color):
                histr = cv2.calcHist([read_img],[i],None,[256],[0,256])
                self.widgetDisplay.canvas.sumbu1.plot(histr,color = col,linewidth=3.0)
                self.widgetDisplay.canvas.sumbu1.set_ylabel('Y', color='blue')
                self.widgetDisplay.canvas.sumbu1.set_xlabel('X', color='blue')
                self.widgetDisplay.canvas.sumbu1.set_title('Histogram')
                self.widgetDisplay.canvas.sumbu1.set_facecolor('xkcd:wheat')
                self.widgetDisplay.canvas.sumbu1.grid()
            self.widgetDisplay.canvas.draw()
                
    if __name__ == '__main__':
        import sys
        app = QApplication(sys.argv)
        ex = Display_Histogram()
        ex.show()
        sys.exit(app.exec_())
    

  15. Click on Read Image button. You now can see the image and its histogram:



  16. Place another Push Button widget and Label widget onto form. 
  17. Set the property of the objectName from the Push Button widget in the Property Editor window to pbFilter.
  18. Set the property of the objectName from the Label widget in the Property Editor window to labelFilter.
  19. Place another Widget from the Containers panel on the form. Set the objectName property to be the widgetDisplay2
  20. Next, right-click on the Widget and from  the context menu displayed select Promoter widgets and select checkbox available:


  21. Modify main_histogram.py that defines the method filter_histogram() and connect it with the clicked() event from pbFilter widget:

  22. #main_histogram.py
    import cv2
    import numpy as np
    from PyQt5.QtWidgets import*
    from PyQt5.uic import loadUi
    from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar)
    from PyQt5.QtWidgets import QDialog, QFileDialog
    from PyQt5.QtGui import QIcon, QPixmap, QImage
    
    import numpy as np
    fname = ""
         
    class Display_Histogram(QMainWindow):   
        def __init__(self):
            
            QMainWindow.__init__(self)
            loadUi("histogram.ui",self)
    
            self.setWindowTitle("Image Histogram")
            self.pbImage.clicked.connect(self.display_histogram)
            self.pbFilter.clicked.connect(self.filter_histogram)
            self.addToolBar(NavigationToolbar(self.widgetDisplay.canvas, self))
    
        def display_histogram(self):
            global fname
            fname = QFileDialog.getOpenFileName(self, 'Open file', 
               'd:\\',"Image Files (*.jpg *.gif *.bmp *.png *.tiff)")
            pixmap = QPixmap(fname[0])
            self.labelImage.setPixmap(pixmap)
            self.labelImage.setScaledContents(True);
            
    
            self.widgetDisplay.canvas.axes1.clear()
            read_img = cv2.imread(fname[0], cv2.IMREAD_COLOR)
            color = ('b','g','r')
            for i,col in enumerate(color):
                histr = cv2.calcHist([read_img],[i],None,[256],[0,256])
                self.widgetDisplay.canvas.axes1.plot(histr,color = col,linewidth=3.0)
                self.widgetDisplay.canvas.axes1.set_ylabel('Y', color='blue')
                self.widgetDisplay.canvas.axes1.set_xlabel('X', color='blue')
                self.widgetDisplay.canvas.axes1.set_title('Histogram')
                self.widgetDisplay.canvas.axes1.set_facecolor('xkcd:wheat')
                self.widgetDisplay.canvas.axes1.grid()
            self.widgetDisplay.canvas.draw()
    
        def filter_histogram(self):
            read_img = cv2.imread(fname[0], cv2.IMREAD_COLOR)
            
            # To filter image using kernel 5x5
            kernel_5x5 = np.ones((5,5), np.float32) / 25.0
            output = cv2.filter2D(read_img, -1, kernel_5x5)
            
            # To convert back from BGR to RGB space color
            cv2.cvtColor(output, cv2.COLOR_BGR2RGB, output)
            
            # To display image in label widget
            height, width, channel = output.shape
            bytesPerLine = 3 * width
            qImg = QImage(output.data, width, height, bytesPerLine, QImage.Format_RGB888)
            pixmap = QPixmap.fromImage(qImg)
            self.labelFilter.setPixmap(pixmap)
            self.labelFilter.setScaledContents(True);        
    
            self.widgetDisplay2.canvas.axes1.clear()
            color = ('b','g','r')
            for i,col in enumerate(color):
                histr = cv2.calcHist([output],[i],None,[256],[0,256])
                self.widgetDisplay2.canvas.axes1.plot(histr,color = col,linewidth=3.0)
                self.widgetDisplay2.canvas.axes1.set_ylabel('Y', color='blue')
                self.widgetDisplay2.canvas.axes1.set_xlabel('X', color='blue')
                self.widgetDisplay2.canvas.axes1.set_title('Histogram of Filtered Image')
                self.widgetDisplay2.canvas.axes1.set_facecolor('xkcd:wheat')
                self.widgetDisplay2.canvas.axes1.grid()
            self.widgetDisplay2.canvas.draw()
                
    if __name__ == '__main__':
        import sys
        app = QApplication(sys.argv)
        ex = Display_Histogram()
        ex.show()
        sys.exit(app.exec_())
    

  23. Click on Read Image and Filter Image buttons. You now can see the image and its each histogram:



1 comment: