MATLAB: Extract a non-rectangular region from an image

polyroi

I have an image whose size is m x n. I also have a vector whose size is m x 1. The elements of the vector are the column numbers in the image where there is a border. I want to extract the image data only to the right of the border. For example, if my image intensity values matrix is
I = [ 0.8308 0.5678 0.4694 0.6020 0.9133 0.9619 0.8001
0.5853 0.0759 0.0119 0.2630 0.1524 0.0046 0.4314
0.5497 0.0540 0.3371 0.6541 0.8258 0.7749 0.9106
0.9172 0.5308 0.1622 0.6892 0.5383 0.8173 0.1818
0.2858 0.7792 0.7943 0.7482 0.9961 0.8687 0.2638
0.7572 0.9340 0.3112 0.4505 0.0782 0.0844 0.1455
0.7537 0.1299 0.5285 0.0838 0.4427 0.3998 0.1361
0.3804 0.5688 0.1656 0.2290 0.1067 0.2599 0.8693 ]
and the vector is:
v = [2; 2; 2; 3; 3; 4; 5; 4];
then I want to create a new image whose values to the right of the border are extracted from the image and to the left of the border are zeros.
I2 = [ 0.0000 0.5678 0.4694 0.6020 0.9133 0.9619 0.8001
0.0000 0.0759 0.0119 0.2630 0.1524 0.0046 0.4314
0.0000 0.0540 0.3371 0.6541 0.8258 0.7749 0.9106
0.0000 0.0000 0.1622 0.6892 0.5383 0.8173 0.1818
0.0000 0.0000 0.7943 0.7482 0.9961 0.8687 0.2638
0.0000 0.0000 0.0000 0.4505 0.0782 0.0844 0.1455
0.0000 0.0000 0.0000 0.0000 0.4427 0.3998 0.1361
0.0000 0.0000 0.0000 0.2290 0.1067 0.2599 0.8693 ]
To develop my algorithm I used a double loop, but now, that I need to do this several thousands of times, I am looking for an efficient way to extract this non-rectangular region from the image.
Any help will be greatly appreciated.

Best Answer

I would create a mask using bsxfun that I'd then multiply with the original image:
mask = bsxfun(@ge, 1:size(I, 2), v); %compare row vector 1:size(I, 2) to each element of v and return 1 when it is greater or equal (ge)
I2 = I .* mask
or just on one line:
I2 = I .* bsxfun(@ge, 1:size(I, 2), v)