DEV Community

Cover image for Image threshold with Python
petercour
petercour

Posted on

Image threshold with Python

You can threshold images with the cv2 method threshold(). What is thresholding? What is cv2?

The module cv2 is the computer vision module for Python. This lets you make computer vision software, which goes far beyond image processing. The technique uses Machine Learning.

Start with an input image. This can be any input image, jpg, png or whatever you want.

Input image:

If pixel value is greater than a threshold value, it is assigned one value (may be white), else it is assigned another value (may be black). The function used is cv2.threshold.

There are different types of thresholding, which the program below demonstrates:

Different types are:

  • cv2.THRESH_BINARY
  • cv2.THRESH_BINARY_INV
  • cv2.THRESH_TRUNC
  • cv2.THRESH_TOZERO
  • cv2.THRESH_TOZERO_INV

OpenCV code

So how does it work in code? Start with an input image (image.jpg). Then use cv2 to show different variations.

#!/usr/bin/python3                                                                                                                                                  

import cv2
import numpy as np
from matplotlib import pyplot as plt

img=cv2.imread('image.jpg')
GrayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh1=cv2.threshold(GrayImage,127,255,cv2.THRESH_BINARY)
ret,thresh2=cv2.threshold(GrayImage,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3=cv2.threshold(GrayImage,127,255,cv2.THRESH_TRUNC)
ret,thresh4=cv2.threshold(GrayImage,127,255,cv2.THRESH_TOZERO)
ret,thresh5=cv2.threshold(GrayImage,127,255,cv2.THRESH_TOZERO_INV)
titles = ['Gray Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [GrayImage, thresh1, thresh2, thresh3, thresh4, thresh5]
for i in xrange(6):
   plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
   plt.title(titles[i])
   plt.xticks([]),plt.yticks([])
plt.show()
Enter fullscreen mode Exit fullscreen mode

Output for this example:

These lines show all the images in one plot:

#/usr/bin/python3

for i in xrange(6):
   plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
   plt.title(titles[i])
   plt.xticks([]),plt.yticks([])
plt.show()
Enter fullscreen mode Exit fullscreen mode

These are the different variations of thresholding. You can set the threshold parameters. The parameters include threshold and maxval.

Related links:

Top comments (0)