フィルターのクリア

How to automate dimensional expansion elegantly(broadcasting mechanism)?

4 ビュー (過去 30 日間)
cui,xingxing
cui,xingxing 2021 年 8 月 2 日
回答済み: Chunru 2021 年 8 月 2 日
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 Center および File ExchangeGeographic Plots についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by