You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

scikit-image计算RG_ratio遇除零警告及直方图错误的解决方法

解决红-绿指数计算中的除以0警告及直方图绘制错误

问题现象

计算红-绿指数(RG_ratio = R/G)时出现两个RuntimeWarning:

RuntimeWarning: divide by zero encountered in divide
RuntimeWarning: invalid value encountered in divide

绘制RG_ratio直方图时抛出ValueError:

ValueError: supplied range of [0.0, inf] is not finite

错误原因

  1. 除以0警告:图像的G通道中存在值为0的像素,直接执行R/G时,会出现除以0的情况,生成无穷大(inf)的结果;如果R和G同时为0,会生成无效值(nan)。
  2. 直方图绘制失败:RG_ratio数组中包含inf和nan这类非有限值,numpy在计算直方图范围时无法处理无穷大,导致报错。

解决方案

方案1:避免除以0,替换无效值

通过numpy的divide函数指定条件,或者给G通道添加极小值,避免除以0的情况:

# 方法A:使用np.divide的where参数,G为0时输出0
RG_ratio = np.divide(R, G, out=np.zeros_like(R, dtype=np.float64), where=G != 0)

# 方法B:给G加极小值(1e-8),避免除以0,同时不影响正常计算
RG_ratio = R / (G + 1e-8)

方案2:过滤非有限值后绘制直方图

如果已经生成了包含inf/nan的数组,绘制直方图前先过滤掉这些无效值:

# 提取所有有限值
valid_rg = RG_ratio[np.isfinite(RG_ratio)]
# 绘制直方图
plt.figure()
plt.hist(valid_rg, bins='scott')
plt.show()

方案3:改用更稳定的植被指数

代码中已经实现的**过绿指数(ExG = 2*G - R - B)**是更稳定的选择,它不需要除法运算,完全避免了除以0的问题,同样可以有效定位绿色像素。

修改后的完整代码

# Import modules
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from skimage.color import rgb2gray, label2rgb
from skimage.filters import threshold_otsu

# Read example image
filename = 'wheat.jpg'
RGB = mpimg.imread(filename)

# Display image
plt.axis('off')
plt.imshow(RGB)
plt.show()

# Convert image from float in the range 0-1 to unsigned integer in the range 0-255
RGB = (RGB*255).astype('uint8')

# Separate RGB channels
R = RGB[:, :, 0]
G = RGB[:, :, 1]
B = RGB[:, :, 2]

# Display bands and histograms for each band
plt.figure(figsize=(12,8))
plt.subplot(2, 3, 1)
plt.axis('off')
plt.imshow(R, cmap='gray')
plt.title('Red')
plt.subplot(2, 3, 2)
plt.axis('off')
plt.imshow(G, cmap='gray')
plt.title('Green')
plt.subplot(2, 3, 3)
plt.axis('off')
plt.imshow(B, cmap='gray')
plt.title('Blue')
plt.subplot(2, 3, 4)
plt.hist(R.flatten())
plt.subplot(2, 3, 5)
plt.hist(G.flatten())
plt.subplot(2, 3, 6)
plt.hist(B.flatten())
plt.show()

# Compute Red-Green Ratio(处理除以0情况)
RG_ratio = np.divide(R, G, out=np.zeros_like(R, dtype=np.float64), where=G != 0)

# Compute Excess Green Index
ExG = 2*G - R - B

# Plot histogram of RG_ratio(过滤无效值)
valid_rg = RG_ratio[np.isfinite(RG_ratio)]
plt.figure()
plt.hist(valid_rg, bins='scott')
plt.title('RG_ratio Histogram')
plt.show()

内容的提问来源于stack exchange,提问作者s_o_c_account

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 22:05:20