Life2Coding
Apply Mean and Gaussian Adaptive Thresholding on Images using Trackbar in OpenCV Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply them in various aspects using some great examples. Then the output will be visualized along with the comparisons.

We will also discuss the basic of image processing and provide the detail explanation related to the OpenCV functions.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV with Python 3

Goals:

The goal is to make you understand how to apply adaptive thresholding on images in Python with OpenCV library

Documentation:

getTrackbarPos()

retval=cv.getTrackbarPos(trackbarname, winname)

Returns the trackbar position.

Parameters
trackbarname Name of the trackbar.
winname Name of the window that is the parent of the trackbar.

adaptiveThreshold()

dst=cv.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst])

Applies an adaptive threshold to an array.

Parameters
src Source 8-bit single-channel image.
dst Destination image of the same size and the same type as src.
maxValue Non-zero value assigned to the pixels for which the condition is satisfied
adaptiveMethod Adaptive thresholding algorithm to use, see AdaptiveThresholdTypes. The BORDER_REPLICATE | BORDER_ISOLATED is used to process boundaries.
thresholdType Thresholding type that must be either THRESH_BINARY or THRESH_BINARY_INV, see ThresholdTypes.
blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.
C Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well.

imshow()

None=cv.imshow(winname, mat)

Displays an image in the specified window.

Parameters
winname Name of the window.
mat Image to be shown.

namedWindow()

None=cv.namedWindow(winname[, flags])

Creates a window.

Parameters
winname Name of the window in the window caption that may be used as a window identifier.
flags Flags of the window. The supported flags are: (cv::WindowFlags)

imread()

retval=cv.imread(filename[, flags])

Loads an image from a file.

Parameters
filename Name of file to be loaded.
flags Flag that can take values of cv::ImreadModes

cvtColor()

dst=cv.cvtColor(src, code[, dst[, dstCn]])

Converts an image from one color space to another.

Parameters
src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC… ), or single-precision floating-point.
dst output image of the same size and depth as src.
code color space conversion code (see ColorConversionCodes).
dstCn number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code.

waitKey()

retval=cv.waitKey([, delay])

Waits for a pressed key.

Parameters
delay Delay in milliseconds. 0 is the special value that means “forever”.

destroyAllWindows()

None=cv.destroyAllWindows()

Destroys all of the HighGUI windows.

Steps:

  • Read the image using cv2.imread()
  • Create the trackbars for adjusting the Adaptive thresholding block size value and type of adaptive thresholding using cv2.createTrackbar()
  • Get the trackerbars’ value at the callback function using cv2.getTrackbarPos()
  • Apply the different types of adaptive thresholding with the cv2.adaptiveThreshold()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2

def UpdateAdaptive(num):
    blockSize = cv2.getTrackbarPos('Thresh', 'Threshold')
    type = cv2.getTrackbarPos('1:Mean 2:Gaussian', 'Threshold')
    if type==0:
        tval=cv2.ADAPTIVE_THRESH_MEAN_C
    else:
        tval = cv2.ADAPTIVE_THRESH_GAUSSIAN_C

    if blockSize<=0:
        blockSize=1
    blockSize=blockSize*2+1

    outImage = cv2.adaptiveThreshold(img, 255, tval, cv2.THRESH_BINARY,
                                     blockSize, 2)
    cv2.imshow('Threshold', outImage)


if __name__ == '__main__':
    cv2.namedWindow('Threshold',1)
    cv2.createTrackbar('Thresh', 'Threshold', 1, 255, UpdateAdaptive)
    cv2.createTrackbar('1:Mean 2:Gaussian', 'Threshold', 0, 1, UpdateAdaptive)

    img = cv2.imread('./hanif.jpg')
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    UpdateAdaptive(0)
    cv2.waitKey(0)


cv2.destroyAllWindows()

Output:

5cc03d9448308 Apply Mean and Gaussian Adaptive Thresholding on Images using Trackbar in OpenCV Python
life2coding_icon [] Apply Mean and Gaussian Adaptive Thresholding on Images using Trackbar in OpenCV Python

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.