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

时间:2021-02-25 08:54:34

标签: r matlab image-processing r-raster

我正在尝试计算包含 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) 的输出是不同的。

1 个答案:

答案 0 :(得分:1)

我不知道 R,但我可以看到,在您的 Matlab 代码中,您正在计算 String my_variable_string= my_enum.name(); 的平均值,这不是去除 Inf 值后 ~isinf(Hue_index) 的平均值。< /p>

实际上,计算 Hue_index,这与您从 R 获得的值非常接近。

现在,您是要计算 mean(Hue_index(~isinf(Hue_index)), 'all', 'omitnan') = -1.5165759 的均值(这是一个只有 1 和 0 的矩阵,取决于 ~isinf(Hue_index) 是否为 Inf)或 Hue_index 的均值取决于你。

编辑:

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

Hue_index(~isinf(Hue_index))