The minimum element in a numpy array remaining zero even after adding one to every element pointwise

Viewed 108

I am trying to get the log of an image for some further processing, the minimum pixel value in the image is zero and hence i am trying to take log(1+image), but even after adding 1 to every element the minimum value of the array is still showing as 0 and hence np.log is throwing a divide by zero encountered in log and setting the value to -inf which is causing me problems down the line.

import numpy as np
import skimage.io as io

image = io.imread('./PET_image.tif')
image_2 = image + 1
print(np.amin(image))
print(np.amin(image_2))
np.log(image)

both the print np.amin() statements are printing out 0.

0
0
error.py:8: RuntimeWarning: divide by zero encountered in log
  np.log(image_2)

But after adding 1 to the array shouldn't the minimum value be 1? I'm pretty sure I'm missing something extremely stupid, but this is making my head split and any help is greatly appreciated.

2 Answers

Most likely due to image.dtype being unsigned (e.g. uint8), which makes sense since the pixel values are always positive. Due to the data type, pixels with value 255 will overflow when you add one and change to zero.

image = io.imread('./PET_image.tif').astype(np.uint64)

to read into an array of 64-bit integers which won't overflow (so easily).

Instead of adding 1 to the image and then applying log. You can just do

np.log1p(image)

which is essentially doing the same thing that you are trying to achieve with that +1.

The error that you are facing with the +1 is caused by the type of the array dtype=uint8. Adding 1 to all the pixels will turn the pixels that have value 255 to 0.

Or you can add the 1 only to pixels where the value is 0.

image[np.where(image == 0)] = 1
Related