Matlab 和 R 图像处理输出之间的差异

Discrepancy between Matlab and R image processing output

我正在尝试计算包含 Inf 的图像(单波段)的平均值。我在 R 和 Matlab 中都做过。但是输出是不同的。谁能指导我我做错了什么?代码如下

Matlab代码

I = imread('peppers.png');

% Extract color channels as single data type
R = single(I(:,:,1)); % Red channel
G = single(I(:,:,2)); % Green channel
B = single(I(:,:,3)); % Blue channel

%Index calculation
Hue_index = (2*R-G-B)./(G-B);

%Mean calculation after ignoring inf
mean_HI = mean(reshape(~isinf(Hue_index), [], 1));

% mean_HI = 0.9947

imwrite(I, 'peppers.png'); %Saving the image for using it in R

R码

library(raster)

#Load the image, Use stack function to read in all bands
r <- stack("peppers.png")

#Now read the individual bands from the stack
R=r[[1]]
G=r[[2]]
B=r[[3]]

#Index calculation
Hue_index = (2*R-G-B)/(G-B)
Hue_index
#> class      : RasterLayer 
#> dimensions : 384, 512, 196608  (nrow, ncol, ncell)
#> resolution : 1, 1  (x, y)
#> extent     : 0, 512, 0, 384  (xmin, xmax, ymin, ymax)
#> crs        : NA 
#> source     : memory
#> names      : layer 
#> values     : -Inf, Inf  (min, max)

#Replaces inf or -inf with NA
is.na(Hue_index) <- sapply(Hue_index, is.infinite)

#Raster to dataframe conversion
HI_df  = raster::as.data.frame(Hue_index, xy = TRUE)

#Mean calculation of the dataframe
HI_mean <- raster::mean(HI_df$layer, na.rm=T)
HI_mean 
#> [1] -1.516576

Hue_index可以看出,它包含-Inf和Inf,Matlab(0.9947)和R(-1.516576)的输出是不同的。

我不知道 R,但我可以看到在你的 Matlab 代码中你正在计算 ~isinf(Hue_index) 的平均值,这不是删除 Inf 值后 Hue_index 的平均值.

事实上,计算 mean(Hue_index(~isinf(Hue_index)), 'all', 'omitnan') = -1.5165759,这非常接近你从 R 得到的值。

现在,您是否要计算 ~isinf(Hue_index) 的平均值(这是一个只有 1 和 0 的矩阵,具体取决于 Hue_index 是否为 Inf)或 [=16 的平均值=] 由你决定。

编辑:

这是完整的代码,唯一的变化是对 mean 的调用。代码对我来说运行良好(Windows 10 上的 MATLAB R2019a)。

I = imread('peppers.png');

% Extract color channels as single data type
R = single(I(:,:,1)); % Red channel
G = single(I(:,:,2)); % Green channel
B = single(I(:,:,3)); % Blue channel

%Index calculation
Hue_index = (2*R-G-B)./(G-B);

%Mean calculation after ignoring inf
mean_HI = mean(Hue_index(~isinf(Hue_index)), 'all', 'omitnan');