Adaptive threshold error using python opencv library

1.2k views Asked by At

I am in a situation where cv2.THRESH_TRUNC suits me well and I want to apply as adaptive threshold but I am facing an unknown error. Here is my basic code:

from PIL import Image
import pytesseract
import cv2

image = cv2.imread("/home/anees/Desktop/passport.png",0)
thresh =cv2.adaptiveThreshold(image,170,
cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_TRUNC, 3, 5)

ERROR that I am getting is below:

openCV(4.5.2) /tmp/pip-req-build-yw7uvgqm/opencv/modules/imgproc/src/thresh.cpp:1723: error: (-206:Bad flag (parameter or structure field)) Unknown/unsupported threshold type in function 'adaptiveThreshold'
1

There are 1 answers

0
Red On

Here is the documentation of the cv2.adaptiveThreshold() method, accessible by calling the built-in help() method:

>>> import cv2
>>> help(cv2.adaptiveThreshold)
Help on built-in function adaptiveThreshold:

adaptiveThreshold(...)
    adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst]) -> dst
    .   @brief Applies an adaptive threshold to an array.
    .   
    .   The function transforms a grayscale image to a binary image according to the formulae:
    .   -   **THRESH_BINARY**
    .       \f[dst(x,y) =  \fork{\texttt{maxValue}}{if \(src(x,y) > T(x,y)\)}{0}{otherwise}\f]
    .   -   **THRESH_BINARY_INV**
    .       \f[dst(x,y) =  \fork{0}{if \(src(x,y) > T(x,y)\)}{\texttt{maxValue}}{otherwise}\f]
    .   where \f$T(x,y)\f$ is a threshold calculated individually for each pixel (see adaptiveMethod parameter).
    .   
    .   The function can process the image in-place.
    .   
    .   @param src Source 8-bit single-channel image.
    .   @param dst Destination image of the same size and the same type as src.
    .   @param maxValue Non-zero value assigned to the pixels for which the condition is satisfied
    .   @param adaptiveMethod Adaptive thresholding algorithm to use, see #AdaptiveThresholdTypes.
    .   The #BORDER_REPLICATE | #BORDER_ISOLATED is used to process boundaries.
    .   @param thresholdType Thresholding type that must be either #THRESH_BINARY or #THRESH_BINARY_INV,
    .   see #ThresholdTypes.
    .   @param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the
    .   pixel: 3, 5, 7, and so on.
    .   @param 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.
    .   
    .   @sa  threshold, blur, GaussianBlur

>>> 

Focusing on this part:

@param thresholdType Thresholding type that must be either #THRESH_BINARY or #THRESH_BINARY_INV

So you'll simply have to change your cv2.THRESH_TRUNC to one of cv2.THRESH_BINARY or cv2.THRESH_BINARY_INV.

The help() method to is great tool to get the more information on methods without having to go online!