【问题标题】:Discrepancy between Matlab and R image processing outputMatlab 和 R 图像处理输出之间的差异
【发布时间】: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


    【解决方案1】:

    我不知道 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)或 Hue_index(~isinf(Hue_index)) 的平均值取决于您。

    编辑:

    这里是完整的代码,唯一的变化是对 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');
    

    【讨论】:

    • Running mean(Hue_index(~isinf(Hue_index)), 'all', 'omitnan'); 返回以下错误 Error using sum The dimension input to SUM must be numeric. Error in mean (line 82) y = sum(x,dim,flag)/size(x,dim); 我想在删除 inf 后计算均值。
    • 如果能提供完整代码就好了。
    • 如果还是有错误,那就奇怪了。尝试重塑你的 Hue_index,mean_HI = mean(reshape(Hue_index(~isinf(Hue_index)), [], 1), 'omitnan');
    • 其实我在 Windows 10 上使用 MATLAB R2014b。
    • 那么我猜'all'标志还没有实现,并且Matlab正在尝试将标志'all'读取为仅接受数值的字段'dim'。然后像我之前的评论中那样在平均调用中重塑数组应该可以工作。
    猜你喜欢
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 2012-10-19
    • 1970-01-01
    • 2019-09-25
    相关资源
    最近更新 更多