简体   繁体   中英

What is the proper procedure for using MATLAB's poly2mask() with a shapefile?

I have a shapefile (example here ) which I would like to convert to a binary region of interest (ROI) mask using MATLAB's poly2mask() .

MATLAB's description is as follows:

BW = poly2mask(x, y, m, n)

BW = poly2mask(x, y, m, n) computes a binary region of interest (ROI) mask, BW, from an ROI polygon, represented by the vectors x and y. The size of BW is m-by-n. poly2mask sets pixels in BW that are inside the polygon (X,Y) to 1 and sets pixels outside the polygon to 0.

poly2mask closes the polygon automatically if it isn't already closed.

This is the script I am using to convert my shapefile:

s = 'D:\path\to\studyArea.shp'

shp = shaperead(s)
x = [shp.X];
y = [shp.Y];

% use bounding box to define m and n
m = shp.BoundingBox(2) - shp.BoundingBox(1)
n = shp.BoundingBox(3) - shp.BoundingBox(1) 

mask = poly2mask(x,y, m, n)

Results in the following error:

Error using poly2mask Expected input number 1, X, to be finite.

Error in poly2mask (line 49) validateattributes(x,{'double'},{'real','vector','finite'},mfilename,'X',1);

Error in createMask (line 11) mask = poly2mask(x,y, m, n)

I suspect there may be an issue with UTM coordinates rather than Lat/Long, however, I could use some input from someone who has experience in this. Where am I going wrong here?

your x and y values have NaN's as the last coordinate. poly2mask won't work if there are NaN's in the coordinates. (hence the error 'values must be finite').

If this is the case you can use a quick fix..

x = length(x)-1;
y = length(y)-1;

more info

http://www.mathworks.com/help/map/understanding-vector-geodata.html

-James

See the changes here -

s = 'studyArea.shp' %// Copy this file to working directory

shp = shaperead(s)
x = [shp.X];
y = [shp.Y];

%// Threw error before because there were NaNs there in x or y or both. So one assumption could be that you want to remove all x and y where any x or y is a NaN.  
cond1 = isnan(x) | isnan(y); 
x(cond1)=[];
y(cond1)=[];

% use bounding box to define m and n
m = shp.BoundingBox(2) - shp.BoundingBox(1)
n = shp.BoundingBox(3) - shp.BoundingBox(1) 

%mask = poly2mask(x,y, m, n); %// Threw error
mask = poly2mask(x,y, round(m/20), round(n/20)); %//Worked fine for smaller 3rd and 4th arguments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM