How to replace for-loop with matrix multiplication?
古いコメントを表示
I'm trying to replace for-loop with matrix multiplication in order for efficiency. In my case, the matrix is 3-dimensional. I'm not sure how to achieve it. I've attached my code. Could someone help optimize my code?
2 件のコメント
Bruno Luong
2023 年 9 月 25 日
why reinvent the wheel and not using MATLAB interpolation functions?
Duen Chian
2023 年 9 月 25 日
回答 (1 件)
Nipun
2023 年 10 月 5 日
Hi Duen,
I understand that you are trying to replace the for loops in the given code with matrix multiplication for imroved time efficiency. I assume that the matrix that you are referring to in the question is a different 3 dimensional matrix, since resizedImage is a 2 dimensional matrix.
Here are few steps that I followed to optimize the code:
- vectorize variables a and b
- generate the weights as a vector
- Use element-wise operations for the matrix elements and reshape the matrix to get the desired image size
Please note that the optimized code below assumes that the img matrix contains grayscale pixel values. If you're working with RGB images, you'll need to modify the code accordingly.
function resizedImage = resizeImage_bilinear_Opt(originalImage, scalingFactor)
% load image
img = imread(originalImage);
% get source row and column
[sr, sc] = size(img);
% get destination row and column
dr = ceil(sr * scalingFactor);
dc = ceil(sc * scalingFactor);
% generate row and column indices for the destination image
a = (1:dr) * ((sr - 1) / (dr - 1));
b = (1:dc) * ((sc - 1) / (dc - 1));
% compute the floor and ceil values for row and column indices
x = floor(a);
y = floor(b);
x1 = min(x + 1, sr);
y1 = min(y + 1, sc);
% compute the weights for bilinear interpolation
wa = a - x;
wb = b - y;
wa1 = 1 - wa;
wb1 = 1 - wb;
% perform bilinear interpolation using matrix multiplication
resizedImage = uint8(wa1 .* wb1 .* double(img(x, y)) + ...
wa1 .* wb .* double(img(x, y1)) + ...
wa .* wb1 .* double(img(x1, y)) + ...
wa .* wb .* double(img(x1, y1)));
% reshape the image to the desired size
resizedImage = reshape(resizedImage, dr, dc);
end
Hope this helps.
Regards,
Nipun
カテゴリ
ヘルプ センター および File Exchange で 2-D and 3-D Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!