0

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?

CyberMathIdiot
  • 123
  • 1
  • 1
  • 9

2 Answers2

1

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)
Ahx
  • 6,551
  • 3
  • 18
  • 41
0

Simply divide whole image with 255 as treat as float,

img = img / 255.

DomagojM
  • 81
  • 1
  • 3