How to automate dimensional expansion elegantly(broadcasting mechanism)?

5 次查看(过去 30 天)
For example, I have a RGB image and for each channel I need to subtract the mean and divide by the standard deviation, where meanRGB = [0.485, 0.456, 0.406]; stdRGB = [0.229, 0.224, 0.225]; How can I write the code in an elegant and concise way?
The common way to write it is:
meanRGB = [0.485, 0.456, 0.406];
stdRGB = [0.229, 0.224, 0.225];
oriImg = imread('peppers.png'); % RGB,[0,255] range
inferenceSize = size(oriImg,[1,2]);
img = rescale(oriImg,0,1);% 转换到[0,1],h*w*c,RGB顺序
% The usual way of writing, the code is slightly more complicated
Rmean = meanRGB(1)*ones(inferenceSize);
Gmean = meanRGB(2)*ones(inferenceSize);
Bmean = meanRGB(3)*ones(inferenceSize);
Rstd = stdRGB(1)*ones(inferenceSize);
Gstd = stdRGB(2)*ones(inferenceSize);
Bstd = stdRGB(3)*ones(inferenceSize);
RGBmean = cat(3,Rmean,Gmean,Bmean);
RGBstd = cat(3,Rstd,Gstd,Bstd);
img = (img-RGBmean)./RGBstd;
And for the same operation, the python writeup is much more elegant for dimensional expansion, with just the following lines.
meanRGB = (0.485, 0.456, 0.406)
stdRGB = (0.229, 0.224, 0.225)
img = (img - meanRGB)/stdRGB # only one line code! automatic broadcasting mechanism

采纳的回答

Chunru
Chunru 2021-8-2
meanRGB = [0.485, 0.456, 0.406];
stdRGB = [0.229, 0.224, 0.225];
oriImg = imread('peppers.png'); % RGB,[0,255] range
img = rescale(oriImg,0,1);% 转换到[0,1],h*w*c,RGB顺序
% change the mean and std into "compatiable" shape for array expansion
meanRGB = reshape(meanRGB, [1,1,3]);
stdRGB = reshape(stdRGB, [1, 1, 3]);
% Array automatic expansion to 1st and 2nd dims
img = (img-meanRGB)./stdRGB;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Geographic Plots 的更多信息

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by