正数的对数会导致负无穷大python

问题描述 投票:0回答:1

我有这张图片: HI00008918.png

我想应用对数函数

(f(x) = (1/a)*log(x + 1)
,其中图像上的
a = 0.01)
...

所以这是代码:

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]))

输出:

255
-inf
554.5177444479563

看看某一时刻它会产生 -inf,而在其他时刻它会产生正确的值:(

现在我将展示数组:

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]
  ...
python image numpy image-processing logarithm
1个回答
0
投票

看起来

np.log(x + 1)
仅在数组中
x
为 255 时给出 -Inf。

因为数组

x
uint8
,所以将1加到255会导致溢出,从而将结果包装为0。0的对数是-Inf。

您可能希望在应用该函数之前将图像转换为浮点类型:

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

当您将该函数应用于从图像中提取的值时,您正在使用 Python

int
,它永远不会溢出。

© www.soinside.com 2019 - 2024. All rights reserved.