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?

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
CyberMathIdiot
  • 193
  • 1
  • 2
  • 12

3 Answers3

2

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.

Baffer
  • 96
  • 11
  • 2
    note that the `img/img.max()` operation results in a temporary float array. you can just say `img /= img.max()` which will cause an in-place integer division (if `img` is of integer type) – Christoph Rackwitz Aug 17 '22 at 21:51
0

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)
Ahmet
  • 7,527
  • 3
  • 23
  • 47
  • this doesn't use numpy at all, other than numpy arrays as containers of numbers. the explicit looping makes this extremely slow. not recommended. – Christoph Rackwitz Aug 17 '22 at 21:49
0

Simply divide whole image with 255 as treat as float,

img = img / 255.

DomagojM
  • 101
  • 1
  • 3