opencv basic threshold to achieve image threshold output · basic explanation (including gif effect picture)

Article directory

                         QQ: 302089729 Xiao Cai

Explanation purpose display


(the code shown above is the integration of the following examples -- simply put the color / gray image in different arrays, and then traverse it.)
In image processing, image features are often processed, and threshold is also the characteristic attribute of image - each pixel corresponds to a certain amount of data - gray image is 8-bit intensity data, color image is 32-bit BGR data.
In our life, we often use threshold processing when dealing with problems - for example, multiple judges' scores remove the lowest score and the highest score, and then calculate the actual data. For example, in the initial stage of a company, a part of technical personnel is needed - only those who exceed the expected ability will be selected, otherwise they will be excluded - of course, my metaphor may not be right, but I just want to let you know that opencv works in this way. As for some special threshold comparison methods, opencv is applied to solve problems It's designed.

Threshold function: cv.threshold application image threshold operation

Introduction to function parameters

The input parameters are as follows:

def threshold(src, thresh, maxval, type, dst=None): # real signature unknown; restored from __doc__
  • Input image - affected by the type behind - gray image is always applicable, and color image is not necessarily
  • threshold
  • Maximum output that meets the threshold
  • Threshold type - or select a threshold determination method
  • The last is the output - the default is to return to accept without setting

Output parameters:

  • The first parameter is the set threshold
  • The second parameter is the image after threshold processing

I think it is necessary to mention the threshold type——

Basic introduction to threshold type

These types are all related to the actual needs - free choice (the first five types are generally selected, and the two types supported at the end can be used as adding conditions to supplement threshold operations).

What we need to know is that the first five kinds meet the requirements of color image as well as gray image, while the last two kinds are only binary operation, so they only apply to 8-bit gray image, that is, threshold operation for intensity data.
The following types of interpretation - the expression shall prevail, and the text shall only be used as a reference and to promote understanding.


  • This threshold type refers to that when the input image is larger than the threshold value we set, the corresponding pixel data is set to the maximum value, otherwise it is 0.


  • This threshold type is the opposite of the previous one - when the input image is larger than the threshold value we set, set the corresponding pixel data to 0, otherwise it is the maximum value.


  • This threshold type means that when the input image is larger than the threshold value we set, the corresponding pixel data is set to the value we set (maxvalue), otherwise it is the value of the image itself.


  • This threshold type means that when the input image is larger than the threshold value we set, the corresponding pixel data is reserved, otherwise it is 0.


  • This threshold type means that when the input image is larger than the threshold value we set, the corresponding pixel data is set to 0, otherwise it is the original data.

  • Python: cv.thresh ﹣ mask -- not supported -- this doesn't explain much, because I don't know much, and I have a chance to correct it later.

  • Python: cv.THRESH_OTSU -- does not support 32-bit color images, only 8-bit gray-scale images

  • Python: cv.thresh'triangle -- does not support 32-bit color images, only 8-bit gray-scale images

Code instance

Gray image example

import cv2 as cv

img = cv.imread('../imag_in_save/images.png')
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)  # In this way, gray image can be obtained
# It can also be obtained directly with img = cv. Imread ('.. / image in save / images. PNG', 0)
# I'm preparing for the last example to compare the gray level change with the color change -- that is, the program keeps the data of the color image

ret1, thresh1 = cv.threshold(img_gray, 127, 255, cv.THRESH_BINARY)  # SRC (x, y) > 127 = > DST (output) (x,y) = 255
cv.imshow('imag', img)
cv.imshow('imag3', thresh1)  # Output threshold processed image

cv.waitKey(0)  # Wait for key input
cv.destroyAllWindows()

Effect:

Original graph

Traverse (grayscale) all cases - all threshold type effects display (and code)

import cv2 as cv


if __name__ == "__main__":
    img = cv.imread('../imag_in_save/images.png')
    img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    # Iterate through the transformation one by one -- you can use list directly, but I wrote it independently for demonstration
    ret1, thresh1 = cv.threshold(img_gray, 127, 255, cv.THRESH_BINARY)  # Meet the threshold setting of 255 (the maximum value we set) and vice versa
    ret2, thresh2 = cv.threshold(img_gray, 127, 255, cv.THRESH_BINARY_INV)  # Meet threshold setting 0, otherwise 255
    ret3, thresh3 = cv.threshold(img_gray, 127, 255, cv.THRESH_MASK)  # By the way, I'll show you where to use it. I'll come back to fix it later
    ret4, thresh4 = cv.threshold(img_gray, 127, 255, cv.THRESH_OTSU)  # Use otus algorithm to get the optimal threshold value ﹐ only suitable for gray-scale image (the end of the article, the length)
    ret5, thresh5 = cv.threshold(img_gray, 127, 255, cv.THRESH_TOZERO)  # It can keep the original data. Otherwise, it is 0, independent of the maximum value of 255
    ret6, thresh6 = cv.threshold(img_gray, 127, 255, cv.THRESH_TOZERO_INV)  # Opposite to thresh? Zero
    ret7, thresh7 = cv.threshold(img_gray, 127, 255, cv.THRESH_TRIANGLE)  # Use trigonometric algorithm to get the optimal threshold ﹐ only suitable for gray-scale image (note at the end of the article, length)
    ret8, thresh8 = cv.threshold(img_gray, 127, 255, cv.THRESH_TRUNC)  # Meet the threshold setting of 255, otherwise retain the original data
    title = ['THRESH_BINARY', 'THRESH_BINARY_INV', 'THRESH_MASK', 'THRESH_OTSU', 'THRESH_TOZERO', 'THRESH_TOZERO_INV',
             'THRESH_TRIANGLE', 'THRESH_TRUNC']
    img_list = [thresh1, thresh2, thresh3, thresh4, thresh5, thresh6, thresh7, thresh8]

    # Font color passes in the corresponding data type according to the image itself -- color is a ternary group
    # Gray image - just transfer in intensity
    for i in range(0, 8):  # Write text to picture - the type of threshold used
        cv.putText(img_list[i], title[i], (25, 60), cv.FONT_HERSHEY_COMPLEX_SMALL, 1, 220, 2, cv.LINE_AA)
    i = 0
    while True:  # Traversal display
        cv.imshow('imag', img_list[i])
        k = cv.waitKey(1000) & 0xFF
        if k == 27:
            break
        i += 1
        if i == 8:
            i = 0
    cv.destroyAllWindows()

Examples of color images (similar to grayscale, but with two less threshold types)

The implementation is the same as the threshold operation of the previous gray-scale image.

import cv2 as cv


if __name__ == "__main__":
    img = cv.imread('../imag_in_save/images.png')
    ret1, thresh1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)  # Meet the threshold setting of 255 (the maximum value we set) and vice versa
    cv.imshow('imag', img)
    cv.imshow('imag_THRESH_BINARY', thresh1)
    cv.waitKey(0)
    cv.destroyAllWindows()

Effect: it will be more direct to realize the parameter change in the effect.

Original graph

Traverse (grayscale) all cases - all threshold type effects display (and code)

import cv2 as cv


if __name__ == "__main__":
    img = cv.imread('../imag_in_save/images.png')
    ret1, thresh1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)  # Meet the threshold setting of 255 (the maximum value we set) and vice versa
    ret2, thresh2 = cv.threshold(img, 127, 255, cv.THRESH_BINARY_INV)  
    ret3, thresh3 = cv.threshold(img, 127, 255, cv.THRESH_MASK)  # By the way
    ret4, thresh4 = cv.threshold(img, 127, 255, cv.THRESH_TOZERO) 
    ret5, thresh5 = cv.threshold(img, 127, 255, cv.THRESH_TOZERO_INV)  # Opposite to thresh? Zero
    ret6, thresh6 = cv.threshold(img, 127, 255, cv.THRESH_TRUNC)  
    title = ['THRESH_BINARY', 'THRESH_BINARY_INV', 'THRESH_MASK', 'THRESH_TOZERO', 'THRESH_TOZERO_INV', 'THRESH_TRUNC']
    img_list = [thresh1, thresh2, thresh3, thresh4, thresh5, thresh6]

    # Font color passes in the corresponding data type according to the image itself -- color is a ternary group
    # Gray image - just transfer in intensity
    for i in range(0, 6):  # Write text to picture - the type of threshold used
        cv.putText(img_list[i], title[i], (25, 60), cv.FONT_HERSHEY_COMPLEX_SMALL, 1, (40, 180, 80), 2, cv.LINE_AA)
    i = 0
    while True:  # Traversal display
        cv.imshow('imag', img_list[i])
        k = cv.waitKey(1200) & 0xFF
        if k == 27:
            break
        i += 1
        if i == 6:
            i = 0
    cv.destroyAllWindows()

Effect:

Supplement: brief introduction to the process of OTSU algorithm


This is the end of the lecture - I hope it can help you even a little. Later, there will be applications. I will supplement the practical operation part of this chapter. (I will also slowly accumulate the previous articles, and then revise them.)

116 original articles published, 125 praised, 10000 visitors+
Private letter follow

Tags: Python less OpenCV Attribute

Posted on Fri, 13 Mar 2020 09:18:45 -0700 by silviuchingaru