how to iterate through all the pixels within a bbox returned by vision.BlobAnalysis

4 views (last 30 days)
Hi I want to iterate through all the pixels within a bbox returned by vision.BlobAnalysis to sum their values, tried following code assuming (x,y) are the coordinates for first pixel, width is number of columns moving right and height is number of rows moving down (seems like I was wrong get an error indicating negative values as k,j coordinates). Can someone kindly explain a bit.
sum=0;
for k=track.bbox(1,1):track.bbox(1,1)+tracks.bbox(1,3)
for j=tracks.bbox(1,2):tracks.bbox(1,2)+tracks.bbox(1,4)
sum=sum+img(k,j);
end
end

Answers (1)

Walter Roberson
Walter Roberson on 14 Oct 2015
%remember, bounding box is _x_ first and _x_ is column not row!
fr = track.bbox(1,2);
fc = track.bbox(1,1);
lr = fr + track.bbox(1,4) - 1; %height includes first pixel
lc = fc + track.bbox(1,3) - 1; %width includes first pixel
pixtotal = sum( sum( img(fr:lr, fc:lc) ) );
and never use "sum" as the name of a variable: it interferes with using sum() as the important MATLAB routine
Note: if you are adding the pixel values only in order to find the mean pixel value, then do not bother adding them:
pixmean = mean2( img(fr:lr, fc:lc) );
  3 Comments
Walter Roberson
Walter Roberson on 14 Oct 2015
What does track.bbox show up as?
Please show your code for creating track.bbox as there are a number of different bounding box detectors.
Maria Kanwal
Maria Kanwal on 15 Oct 2015
bbox shows up as a struct with 4 fields x,y,width and height.
I am using matlab's multiObjectTracking which is using vision.BlobAnalysis for getting bboxes after foreground detection. The problem is that some of the x and y coordinates have negative values so can not index pixels in the image which cause the error, can't understand what coordinate system is working here, I guess it may be axes so tried to use axes2pix but its not working. Also there is some strange behaviour the example 2 outputs +ve values for negative inputs but example 1 outputs -ve values for negative inputs.

Sign in to comment.

Categories

Find more on Entering Commands in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!