Search code examples
pythonpython-3.xopencvgraphicsopencv3.0

Why does this OpenCV threshold call return a blank image?


I am following this tutorial on OpenCV, where the tutorial uses the following code:

import argparse
import imutils
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to input image")
args = vars(ap.parse_args())

image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

thresh = cv2.threshold(gray, 255, 255, cv2.THRESH_BINARY_INV)[1]
cv2.imshow("Thresh", thresh)
cv2.waitKey()

Yet the image thresh displays as a blank window with a light grey background, where the tutorial is supposed to shoe a monochrome profile of an image that came with the tutorial source code.

I'm using the same code, and the same input image, yet the tutorial tells me to expect a monochrome image showing object outlines, while I only get a blank, grey image. What could be wrong here?


Solution

  • Your thresh parameter value should be different than maxval value.

    thresh = cv2.threshold(src=gray,
                           thresh=127,
                           maxval=255,
                           type=cv2.THRESH_BINARY_INV)[1]
    

    From the documentation

    • gray is your source image.
    • thresh is the threshold value
    • maxval is maximum value
    • typeis thresholding type

    When you set both thresh and maxval the same value, you are saying:

    I want to display my pixels above 255 values, but none of the pixels should exceed 255.

    Therefore the result is a blank image.

    One possible way is setting thresh to 127.

    For instance:

          Original Image                                                     Thresholded Image

    enter image description here enter image description here

    import cv2
    
    image = cv2.imread("fgtc7_256_256.jpg")
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(src=gray,
                           thresh=127,
                           maxval=255,
                           type=cv2.THRESH_BINARY_INV)[1]
    cv2.imshow("Thresh", thresh)
    cv2.waitKey(0)