20070224-ROIPOLY – rectangular regions and logical indexing

原文:http://blogs.mathworks.com/steve/2007/02/24/roipoly-rectangular-regions-and-logical-indexing/

Rectangular regions

Users sometimes wonder why poly2mask and roipoly don't return some of the boundary pixels of a rectangular region as part of the mask. Here's an example.

x = [2 4 4 2 2];
y = [2 2 4 4 2];

mask = poly2mask(x, y, 5, 5)
mask =

     0     0     0     0     0
     0     0     0     0     0
     0     0     1     1     0
     0     0     1     1     0
     0     0     0     0     0

Some users expect rows 2 through 4 and columns 2 through 4 to be included in the mask. One reader commented that he uses a different function instead of roipoly because of this behavior.

As I have illustrated in my previous posts, roipoly and poly2mask treat a pixel not as a point, but as a unit square area. The upper-left corner of the (2,2) pixel is (1.5,1.5), and the lower-right corner is (2.5,2.5). So the polygon defined by the x-y vertices in the example above covers only one-fourth of the (2,2) pixel.

I suggest that you get used to defining rectangles that cover complete pixel areas. Such rectangles go along pixel edges, not through pixel centers. Here's a second example to demonstrate:

xp = [1.5 4.5 4.5 1.5 1.5];
yp = [1.5 1.5 4.5 4.5 1.5];

maskp = poly2mask(xp, yp, 5, 5)
maskp =

     0     0     0     0     0
     0     1     1     1     0
     0     1     1     1     0
     0     1     1     1     0
     0     0     0     0     0

Logical indexing

Another reader asked how to get and modify pixels inside a region of interest. One nice way to do that in MATLAB is to use logical indexing. The expression A(B), if B is logical and the same size as A, selects all the elements in A corresponding to the true elements of B.
clear
I = imread('eight.tif');
imshow(I)
c = [222 272 300 270 221 194];
r = [21 21 75 121 121 75];
mask = roipoly(I,c,r);
imshow(mask)
You can use logical indexing on the left-hand side of an assignment as well.
I2 = I;
I2(mask) = 255 - I(mask);  % Or imcomplement(I(mask)).
imshow(I2)
發佈了119 篇原創文章 · 獲贊 16 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章