How to apply a function to every element of a matrix
8 次查看(过去 30 天)
显示 更早的评论
Hi, I have a RGB image which in MATLAB is in the form of a 3D matrix. The code:
angle_dimension = linspace(0,180,3);
cashew_RGB = imread('White Wholes 180.jpg');
cashew_BW = img_BW(cashew_RGB);
cashew_stats = regionprops(cashew_BW,'BoundingBox');
for i = 1:numel(cashew_stats)
cashew_single = imcrop(cashew_RGB,cashew_stats(i).BoundingBox);
cashew_single_BW = img_BW(cashew_single);
dim = imFeretDiameter(cashew_single_BW,angle_dimension);
end
The functions used are not really important. I want to know how I can eliminate the for loop. It is possible in my project that
numel(cashew_stats)
may return a large number and the for loop then would take a lot of time to execute. It would be immensely helpful if you could give me a technique to eliminate the for loop used. I have attached the image that I have used in the code. Thank You!
0 个评论
采纳的回答
Image Analyst
2015-12-13
You don't have a loop over the number of elements (which is 3 times the number of pixels) in the image! You have a loop over the regions you found. And you can't use Bounding Box because other cashews could poke into the bounding box. Actually you don't even use regionprops() at all! You need to use ismember() and then bwboundaries(). Then there is no feret diameter function in MATLAB so you have to use my attached program to get the two farthest points.
[labeledImage, numRegions] = bwlabel(cashew_BW);
cashew_stats = regionprops(labeledImage,'BoundingBox');
for k = 1 : numRegions
% Get binary image of just this one cashew.
thisCashew = ismember(labeledImage, k) > 0;
% Get its boundaries
boundaries = bwboundaries(thisCashew);
x = boundaries(:, 2);
y = boundaries(:, 1);
feretDiameters(k) = GetFeretDiameters(x, y); % See my attached demo for this.
end
3 个评论
Image Analyst
2015-12-13
Yes, but for loops are no problem when the number of iterations is less than a few million, and I doubt you'll have that many cashews in your image. Even when the number of iterations is hundreds of millions, it's usually the memory access on a huge array that is causing the slow down since I can have a hundred million iterations where I don't access any other variables and the time to complete the loop is only 0.3 seconds (I actually just tried it now). Now, if inside that loop I was accessing the (i,j) element of an array with hundreds of millions of elements, then that would be slower, but the for loop itself is not the problem.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!