对图像应用对数函数时出现负无穷(-inf)的Python问题
问题:对数函数处理图像时出现-inf的不一致问题
我有一张图片,想要对其应用对数函数f(x)=(1/a)*log(x+1)(其中a=0.01)。以下是我的Python代码:
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 # 原始图片中白色像素值为0,黑色像素值为255 carLog = fnLog(car) # 应用对数函数fnLog print(car[0][0][-1]) print(carLog[0][0][-1]) print(fnLog(car[0][0][-1]))
运行输出如下:
255 -inf 554.5177444479563
相关数组信息:
carLog = [[[277.2 277.2 277.2 -inf] [289. 289. 289. -inf] ... [437. 450. 440.5 -inf]] [[434.5 434.5 434.5 -inf] [433.2 433.2 433.2 -inf] ... [433.2 444.2 438.2 -inf]]] car = [[[ 15 15 15 255] [ 17 17 17 255] ... [148 134 151 255]] [[ 10 10 10 255] [ 14 14 14 255] ...]]
问题原因
图像数组car的 dtype 是无符号8位整数(uint8),取值范围为0-255。对整个数组执行x + 1时,255 + 1会触发溢出,结果变为0;而np.log(0)会返回-inf。但单独取car[0][0][-1]计算时,该值会被自动转换为更高精度的数值类型(int/float),255+1=256不会溢出,因此能得到正确结果。
解决方法
在执行对数运算前,将图像数组转换为浮点类型,避免溢出:
import numpy as np import matplotlib.pyplot as plt import skimage.io as io car = io.imread('HI00008918.png') # 将数组转换为浮点类型,避免整数溢出 car_float = car.astype(np.float64) a = 0.01 fnLog = lambda x : (1/a)*np.log(x + 1) carLog = fnLog(car_float) print(car[0][0][-1]) print(carLog[0][0][-1]) print(fnLog(car[0][0][-1]))
转换为浮点类型后,所有元素的运算都不会触发溢出,255+1=256可以正常参与对数计算,返回正确结果。
内容的提问来源于stack exchange,提问作者Gustavo Henrique
相关产品推荐
相关产品推荐

