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