pythonnumpyimage-processinglogarithminteger-arithmetic

Logarithm of a positive number result in minus infinity python


I have this image: HI00008918.png

I want to apply a logarithmic function (f(x) = (1/a)*log(x + 1), where a = 0.01) on the image...

So this is the code:

import numpy as np
import matplotlib.pyplot as plt
import skimage.io as io


car = io.imread('HI00008918.png')
# plt.imshow(car, cmap='gray', vmin=0, vmax=255)

a = 0.01

fnLog = lambda x : (1/a)*np.log(x + 1) # logarithmic function

# the original image has white pixels (=0) and black pixels (=255)

carLog = fnLog(car) # Applying the function fnLog

print(car[0][0][-1])

print(carLog[0][0][-1])

print(fnLog(car[0][0][-1]))

The output:

255
-inf
554.5177444479563

Look at one moment it results in -inf and at others it results in the correct value :(

Now I will show the arrays:

carLog =
[[[277.2 277.2 277.2  -inf]
  [289.  289.  289.   -inf]
  [304.5 304.5 304.5  -inf]
  ...
  [423.5 431.8 429.   -inf]
  [422.  434.5 427.8  -inf]
  [437.  450.  440.5  -inf]]

 [[434.5 434.5 434.5  -inf]
  [433.2 433.2 433.2  -inf]
  [430.5 430.5 430.5  -inf]
  ...
  [422.  430.5 427.8  -inf]
  [420.2 429.  426.2  -inf]
  [433.2 444.2 438.2  -inf]]]


car =
[[[ 15  15  15 255]
  [ 17  17  17 255]
  [ 20  20  20 255]
  ...
  [148 138 149 255]
  [138 125 142 255]
  [148 134 151 255]]

 [[ 10  10  10 255]
  [ 14  14  14 255]
  [ 19  19  19 255]
  ...

Solution

  • It looks like np.log(x + 1) gives -Inf only where x is 255 in an array.

    Because the array x is uint8, adding 1 to 255 causes overflow, which wraps the result yielding 0. The log of 0 is -Inf.

    You might want to cast the image to a floating-point type before applying the function:

    carLog = fnLog(car.astype(np.float32))
    

    When you apply the function to a value extracted from the image, you are working with a Python int, which doesn’t ever overflow.