Tuesday, May 3, 2016

GDAL: Clip Rasters

Introduction

GDAL利用shapefile文件裁剪栅格影像,并配置裁剪边界之外的背景数值。注意shapefile文件与栅格影像具有完全一致的投影信息。

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
% Created by LI Xu
% Version 1.0
% April 19, 2016

% Description:
% Clip rasters from a shapefile boundary

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/


clear;
clc;

% Source Directory
SouDir='input';
% Destination Directory
DesDir='output';
% All Input Files
files=dir(fullfile(SouDir, '*.tif'));
% Vector File
vecpath='shapefile.shp';
[~, layername, ~]=fileparts(vecpath);
% Output No Data
NoData=-2;


% Loop
for ii=1:length(files)
    filename=files(ii).name;
    filepath=fullfile(SouDir, filename);
    
    otpath=fullfile(DesDir, filename);
    % gdalwarp -of GTiff -cutline INPUT.shp -cl shapefile  -crop_to_cutline INPUT.tif  OUTPUT.tif
    strcmd=['gdalwarp -of GTiff -cutline ', vecpath, ' -cl ', layername, ' -crop_to_cutline '];
    strcmd=[strcmd, '-dstnodata ' num2str(NoData),' ', filepath, ' ', otpath];
    
    py.os.system(strcmd);
    
    disp([num2str(ii), ':', filename]);
    
end


disp('************************************************');

References

No comments:

Post a Comment