0
votes

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()
2
You might want to use 255 instead of 1, but is there something about this code that isn't working?Mark Ransom
yes , when i execute the program , it shows a black imageNặśř' Eddíŋě

2 Answers

1
votes

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()
0
votes

I think you just want to use np.where():

import numpy as np
image = np.array([[200, 50, 200],[50, 50 ,50],[10, 255, 10]]) #this will be your image instead
In [11]: image
Out[11]: 
array([[200,  50, 200],
       [ 50,  50,  50],
       [ 10, 255,  10]])

In [12]: np.where(image > 100, 1, 0)
Out[12]: 
array([[1, 0, 1],
       [0, 0, 0],
       [0, 1, 0]])