Home > Back-end >  Converting grayscale images to binary and storing in a numpy array in python
Converting grayscale images to binary and storing in a numpy array in python

Time:11-09

I am working on a binary image segmentation problem using Tensorflow Keras. The masks are in grayscale and images are in RGB. I need to convert the grayscale masks to binary and store them in a Numpy array. The following is the code:

 from tensorflow.keras.preprocessing.image import load_img,ImageDataGenerator
    from skimage.transform import resize
    import os
    from tqdm import tqdm
    im_height,im_width = 256,256
    threshold = 150
    ids_test = next(os.walk("data/test/image"))[2] # list of names all images in the given path
    print("No. of images = ", len(ids_test))
    
    X_ts = np.zeros((len(ids_test), im_height, im_width, 3), dtype=np.float32)
    Y_ts = np.zeros((len(ids_test), im_height, im_width, 1), dtype=np.float32)
    for n, id_ in tqdm(enumerate(ids_test), total=len(ids_test)):
        img = load_img("data/test/image/" id_, 
                        color_mode = "rgb")
        x_img = img_to_array(img)
        x_img = resize(x_img, (im_height, im_width,3), 
                        mode = 'constant', preserve_range = True)
        # Load masks
        mask = img_to_array(load_img("data/test/label/" id_, 
                                      color_mode = "grayscale")) #grayscale   
        binarized = 1.0 * (mask > threshold)            
    
        mask = resize(binarized, (im_height,im_width,1), 
                      mode = 'constant', preserve_range = True)
        # Save images
        X_ts[n] = x_img/255.0
        Y_ts[n] = mask

CodePudding user response:

Found the solution to my problem. I am setting a global threshold after empirical evaluations and then thresholding the images to binarize them. Edits made to the posted code.

CodePudding user response:

You can easily convert a numeric array inot a boolean one using comparison operation in numpy (pandas ...).

array = np.random.random(5)
binary_array = array < 0.5
print(array)
print(binary_array)

which leads to :

[0.57145399 0.20060058 0.13103848 0.89899815 0.45459504]
[False  True  True False  True]

And you can easily check the numpy type of your array :

print(binary_array.dtype)
bool

If general if your threshold is th, array > th will convert all values of array to true if > th and to false if <= th with a boolean dtype.

  • Related