Search code examples
pythonopencvcomputer-vision

binarization an image grayscale


i am new in python , my probleme it's about edit some changes in an image grayscale , i wanna make a binarization for this image , the values of pixels bigger then 100 take the value 1 (white), and the values low than 100 takes the value 0 (black) so any suggestion plz (sorry for my bad english)

my code :

`import numpy as np import cv2

image = cv2.imread('Image3.png', 0)




dimension = image.shape
height = dimension[0]
width = dimension[1]

#finalimage = np.zeros((height, width))
for i in  range(height) :
    for j in  range(width):
        
        if (image[i, j] > 100):
            image[i][j] = [1]  
        else:
            image[i][j] = [0]

cv2.imshow('binarizedImage',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Solution

  • You can try use OpenCV function cv2.threshold for binarize.

    import cv2
    img = cv2.imread('Image3.png', cv2.IMREAD_GRAYSCALE)
    thresh = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY)[1]
    cv2.imshow('binarizedImage',thresh)
    cv2.waitKey(0)
    cv2.destroyAllWindows()