How to apply a function to every element of a matrix
조회 수: 6 (최근 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!