【发布时间】:2021-05-27 14:52:02
【问题描述】:
我正在尝试计算包含 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 image-processing r-raster