CyberMathIdiot
CyberMathIdiot

Reputation: 303

How to convert a 0, 255 binary image to a 0, 1 binary image?

I have an image img in the form

array([[  0,   0,   0, ..., 255, 255, 255],
       [  0,   0,   0, ..., 255, 255,   0],
       [  0,   0,   0, ..., 255,   0,   0],
        ...,
       [  0,   0,   0, ...,   0,   0,   0],
       [  0,   0,   0, ...,   0,   0,   0],
       [  0,   0,   0, ...,   0,   0,   0]], dtype=uint8)

Is there any build in python function that convert images like that to 0,1 binarization?

Upvotes: 0

Views: 4572

Answers (3)

Baffer
Baffer

Reputation: 138

Using double for loop is completely inefficient. You can divide all by the max value (in your case 255) like this:

img = np.array(img/img.max(),dtype=np.uint8)

Another way is to define a threshold value and set all image values above this threshold to 1:

threshold = 0
img[img>threshold]=1

I recommend it because it will even assign values 1 in the binary image to values that were different to 255 in the original image.

Upvotes: 2

DomagojM
DomagojM

Reputation: 101

Simply divide whole image with 255 as treat as float,

img = img / 255.

Upvotes: 0

Ahx
Ahx

Reputation: 7985

Your each row is a list, and from each list you want to check whether the value is 255 or not. If it is 255 convert to 1.

To get the index of each row and column , you can enumerate through the list

for i, v1 in enumerate(img):
    for j, v2 in enumerate(v1):
        if v2 == 255:
            img[i, j] = 1

Result:

[[0 0 0 1 1 1]
 [0 0 0 1 1 0]
 [0 0 0 1 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]]

Code:

import numpy as np

img = np.array([[0,   0,   0, 255, 255, 255],
                [0,   0,   0, 255, 255,   0],
                [0,   0,   0, 255,   0,   0],
                [0,   0,   0,   0,   0,   0],
                [0,   0,   0,   0,   0,   0],
                [0,   0,   0,   0,   0,   0]], dtype=np.uint8)

for i, v1 in enumerate(img):
    for j, v2 in enumerate(v1):
        if v2 == 255:
            img[i, j] = 1

print(img)

Upvotes: 0

Related Questions