Search code examples
pythonopencvimage-thresholding

What settings in cv2.threshold() to threshold this image?


I would like to convert this image to gray scale in OpenCV and then find the settings to threshold it. I want to threshold the black spaces inside of the skull. Can someone write out a Python script using OpenCV?

I convert to grayscale with: gray = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)

When I do (ret, thresh) = cv2.threshold(gray, 177, 255, cv2.THRESH_BINARY) I get a black image.

When I do (ret, thresh) = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY) the whole head becomes a white blob.


Solution

  • If i has understood your goal correctly, here is my proposal. It uses Otsu's Thresholding as @stateMachine has said.

    import cv2
    
    im = cv2.imread("IScDg.png")
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    
    # Your first method
    (_, thresh1) = cv2.threshold(gray, 177, 255, cv2.THRESH_BINARY)
    
    # Your second method
    (ret, thresh2) = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
    
    # Proposed method
    (_, thresh3) = cv2.threshold(gray, 0, 1, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    

    different thresholds on your image