Plotting Rectangles Within For Loops

14 views (last 30 days)
Hello,
I am trying to run a color detection algorithm. To do this, I used the regionprops command and detected the center of N number of flowers within an image. I then used the impixel command to detect the RGB values on this centroid. The program works by detecting the boundaries of all flowers found within the image. This number is denoted N.
What I wish to do is generate a square around this centroid point of the square (circle will also work) where I can take the average of all the RGB values. Once I have this average, I can compute what color the square is. Here is where I am having trouble:
Although I have detected the flowers and their centroid, I am unable to generate a square around each individual flower. Here is the code I am using: range_x = range(boundary_matrix(:,1)); range_y = range(boundary_matrix(:,2));
range_boundary_x = range_x/4;
range_boundary_y = range_y/4;
for N = 1:N
%FOR X
outer_range_x = round(range_boundary_x + centroid_matrix(N,1));
inner_range_x = round(-range_boundary_x + centroid_matrix(N,1));
%FOR Y
outer_range_y = round(range_boundary_y + centroid_matrix(N,2));
inner_range_y = round(-range_boundary_y + centroid_matrix(N,2));
centroid_point = impixel(cam_image_rgb,centroid_matrix(N,1),...
centroid_matrix(N,2));
Red = centroid_point(1);
Green = centroid_point(2);
Blue = centroid_point(3);
color_matrix(N,:) = [Red, Green, Blue];
hold on;
rectangle('Position', [inner_range_x,inner_range_y,...
outer_range_x - inner_range_x,...
outer_range_y - inner_range_y])
hold on;
end
end
Currently, what is happening is that the code is plotting the individual rectangles around each flower; however, since each flower is a different size - I want to make it so that each flower has its own rectangle. What is happening right now is that each flower is getting N rectangles (with each rectangle being a different size).
  3 Comments
Walter Roberson
Walter Roberson on 14 Oct 2011
If you have a nested "for" loop then we are going to need to see all relevant code.
You should not use
for N=1:N
as that is plain confusing. Notice you are using the same name on the left side as you are using as the boundary condition on the right side. Inside the loop, it becomes ambiguous to readers as to whether N should refer to the current iteration or should refer to the number of items.

Sign in to comment.

Accepted Answer

Jake Bolanski
Jake Bolanski on 20 Oct 2011
Thanks Walter, it turns out that the nested for loop, indeed, was causing the triple printing of the rectangles. Having removed it, the code seems to work flawlessly in this regard :)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!