Skip to content
Related Articles

Related Articles

Image Analysis Tool using PyQtGraph
  • Last Updated : 01 Nov, 2020

In this article we will see how we can perform common image analysis using PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).

In order to install the PyQtGraph we use the command given below.

pip install pyqtgraph

Image analysis is the extraction of meaningful information from images; mainly from digital images by means of digital image processing techniques. Image analysis tasks can be as simple as reading bar coded tags or as sophisticated as identifying a person from their face.

In order to do this we have to do the following.

  1. Import the required libraries like pyqtgraph, pyqt5 and numpy.
  2. Create a main window class using pyqt5. 
  3. Create a graphic window to add the widgets required to show the image analysis. 
  4. Create two plot area and add a image item to it with the roi object to first plot area.
  5. Create an isocurve object and add it to the image item.
  6. Create a data for image and add it to the image item.
  7. Connect a update method to the roi object when the region is changed, inside the update method get the region and set it to the second plot area. 
  8. Create a mouse move event and set the positon, pixel value to the title according to the mouse position.
  9. Add this graph window to the main window layout with any additional widgets. 

Below is the implementation 






# importing Qt widgets
from PyQt5.QtWidgets import *
# importing system
import sys
# importing numpy as np
import numpy as np
# importing pyqtgraph as pg
import pyqtgraph as pg
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Window(QMainWindow):
    def __init__(self):
        # setting title
        # setting geometry
        self.setGeometry(100, 100, 900, 550)
        # icon
        icon = QIcon("skin.png")
        # setting icon to the window
        # calling method
        # showing all the widgets
    # method for components
    def UiComponents(self):
        # creating a widget object
        widget = QWidget()
        # text
        text = "Image Analysis"
        # creating a label
        label = QLabel(text)
        # setting minimum width
        # making label do word wrap
        # creating a graphic layout widget
        win = pg.GraphicsLayoutWidget()
        # plot area (ViewBox + axes) for displaying the image
        p1 = win.addPlot(title="")
        # item for displaying image data
        img = pg.ImageItem()
        # adding image to the plot area
        # Custom ROI for selecting an image region
        roi = pg.ROI([-10, 14], [5, 5])
        roi.addScaleHandle([0.5, 1], [0.5, 0.5])
        roi.addScaleHandle([0, 0.5], [0.5, 0.5])
        # adding roi to the plot area
        # setting z value to roi
        # making sure ROI is drawn above image
        # creating a Isocurve drawing on the image
        iso = pg.IsocurveItem(level=1.2, pen='r')
        # setting parent as image
        # setting z axis value of isocurve
        # Contrast/color control
        hist = pg.HistogramLUTItem()
        # setting image to the control
        # adding control widget to the plot window
        # creating draggable line for setting isocurve level
        isoLine = pg.InfiniteLine(angle=0, movable=True, pen='r')
        # making user interaction a little easier
        # bring iso line above contrast controls
        # going to next row of grpahic window
        # another plot area for displaying ROI data
        p2 = win.addPlot(colspan=2)
        # setting maximum height of plot area
        # generating image data
        data = np.random.normal(size=(200, 100))
        data[20:80, 20:80] += 2.
        # setting gaussian filter to the data
        data = pg.gaussianFilter(data, (3, 3))
        data += np.random.normal(size=(200, 100)) * 0.1
        # setting data to the image
        # setting level
        hist.setLevels(data.min(), data.max())
        # build isocurves from smoothed data
        iso.setData(pg.gaussianFilter(data, (2, 2)))
        # set position and scale of image
        img.scale(0.2, 0.2)
        img.translate(-50, 0)
        # zoom to fit image
        # method for updating the plot
        def updatePlot():
            # getting the selected region by the roi
            selected = roi.getArrayRegion(data, img)
            # plot the selected region
            p2.plot(selected.mean(axis=0), clear=True)
        # connecting the update plot method
        # it get called when the region is changed
        # call the update plot method
        # method for updating the isocurve
        def updateIsocurve():
            # setting iso level
        # method for image hover event
        def imageHoverEvent(event):
            # showing the position, pixel, and value under the mouse cursor
            # if cursor is not on the plot area
            if event.isExit():
                # set title as blank
            # getting cursor positon
            pos = event.pos()
            i, j = pos.y(), pos.x()
            # pixel values
            i = int(np.clip(i, 0, data.shape[0] - 1))
            j = int(np.clip(j, 0, data.shape[1] - 1))
            # value of point
            val = data[i, j]
            ppos = img.mapToParent(pos)
            x, y = ppos.x(), ppos.y()
            # setting plot title data
                "pos: (%0.1f, %0.1f)  pixel: (%d, %d)  value: %g" % (x, y, i, j, val))
        # Monkey-patch the image to use our custom hover function.
        img.hoverEvent = imageHoverEvent
        # Creating a grid layout
        layout = QGridLayout()
        # minimum width value of the label
        # setting this layout to the widget
        # adding label in the layout
        layout.addWidget(label, 1, 0)
        # plot window goes on right side, spanning 3 rows
        layout.addWidget(win, 0, 1, 3, 1)
        # setting this widget as central widget of the main widow
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :