Converting an OpenCV Image to Black and White

后端 未结 7 1533
逝去的感伤
逝去的感伤 2020-11-29 17:38

How do you convert a grayscale OpenCV image to black and white? I see a similar question has already been asked, but I\'m using OpenCV 2.3, and the proposed solution no long

7条回答
  •  长情又很酷
    2020-11-29 18:04

    Step-by-step answer similar to the one you refer to, using the new cv2 Python bindings:

    1. Read a grayscale image

    import cv2
    im_gray = cv2.imread('grayscale_image.png', cv2.IMREAD_GRAYSCALE)
    

    2. Convert grayscale image to binary

    (thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    

    which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:

    thresh = 127
    im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]
    

    3. Save to disk

    cv2.imwrite('bw_image.png', im_bw)
    

提交回复
热议问题