pythonopencvimage-processingadaptive-threshold

adaptive thresholding ---ValueError: too many values to unpack


I'm pretty amateur at image processing. I could successfully do normal thresholding but however I'm facing an error in Adaptive Thresholding. Here is my code:

import cv2

import numpy as np

img = cv2.imread("vehicle004.jpg")

img = cv2.medianBlur(img,5)

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

_,th2=cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)

cv2.imshow("window2",th2)

cv2.waitKey(0)

cv2.destroyAllWindows()

Error Message:

line 7, in <module>
    _,th2 = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
ValueError: too many values to unpack

Any help is appreciated.


Solution

  • As per the documentation, the cv2.adaptiveThreshold() returns only 1 value that is the threshold image and in this case you are trying to receive 2 values from that method, that is why ValueError: too many values to unpack error is raised.

    After fixing the issue the code may look like:

    import cv2
    
    import numpy as np
    
    img = cv2.imread("vehicle004.jpg")
    
    img = cv2.medianBlur(img,5)
    
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    
    th2=cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
    
    cv2.imshow("window2",th2)
    
    cv2.waitKey(0)
    
    cv2.destroyAllWindows()