问题
I have n
regions generated by regionprops with 'BoundingBox'
and 'Image'
properties. I saved the data ([x, y, Δx, Δy]
) from a specific region (14 for example) to bb1
that I want to work on but first I need to understand the following code:
bb1=floor( Ic(14,1).BoundingBox );
I1bb1=I1( bb1(2):bb1(2)+bb1(4)-1 , bb1(1):bb1(1)+bb1(3)-1 ,:);
After that, also I want to understand the next code that it is from the same example:
I2=I1bb1.*repmat( Ic(BB,1).Image , [1 1 3]);
Where Ic
contains n
regions generated by BoundingBox
回答1:
You have a 3D variable I1
(I guess RGB image) and you wish to crop the boundingbox Ic(14,1).BoundingBox
from it. That is, have a smaller 3D array that corresponds to the pixels inside the bounding box in image I1
. To do this cropping you have these commands:
bb1=floor( Ic(14,1).BoundingBox );
First, you make sure the values [x, y, w, h]
of the bounding box are integers and not sub-pixels so that you can use these values for indexing. Then, you can index into I1
with the bounding box:
I1bb1=I1( bb1(2):bb1(2)+bb1(4)-1 , bb1(1):bb1(1)+bb1(3)-1 ,:);
For the rows of I1bb1
you take the rows from bb1(2)
(y
value) to y+w-1
which is bb1(2)+bb1(4)-1
. Same for the columns from x
to x+h-1
.
For the third line of code, you have the property Ic(14,1).Image
. This property is
Returns a binary image (logical) of the same size as the bounding box of the region. The on pixels correspond to the region, and all other pixels are off.
Now you want I2
to be the same size as the bounding box, but all pixels in the boundingbox not belonging to the object are set to [0 0 0]
(all RGB values zero). Thus you convert Ic(14,1).Image
from 2D binary mask to a 3D mask over three channels:
repmat( Ic(BB,1).Image , [1 1 3])
Finally you element-wise multiply the "inflated" mask with the cropped image I1bb1
:
I2=I1bb1.*repmat( Ic(BB,1).Image , [1 1 3]);
You can achieve the same results with slightly more readable code:
Ibb1 = imcrop( I1, bb1 ); %// crop a bounding box from image
I2 = bsxfun( @times, Ibb1, Ic(14,1).Image ); %// no need for repmat
来源:https://stackoverflow.com/questions/36759827/working-with-an-specific-region-generated-by-boundingbox