2014-04-04 53 views
0

以下matlab腳本將較大的蒙版圖像剪切到較小灰度圖像的邊界框,並遮蓋較小圖像的區域。只要較小的圖像位於較大圖像的範圍內,此功能就很有用。但是,如果較小的圖像超出了放大圖像(附截圖)時,得到下面的錯誤的程度:如何處理圖像範圍錯誤?

Index exceeds matrix dimensions. 

Error in createMask (line 33) 
In = I(NI(1):NI(2),NI(3):NI(4)); % clipped binary 

我想小畫面中的任何像素值較大的圖像的轉換的範圍之外爲0 我可以使用什麼方法來處理這種圖像範圍錯誤?


enter image description here


%% this program clips a larger image using the extent of a smaller image.. 
% resample the images to match the pixel size and multiply with each other 
%This program requires that the clip image is entirely within the larger image 

[I B] = geotiffread('MASK.tif'); % larger image 
[Ic R] = geotiffread('NDVI.tif'); % clip image 
infoNDVI = geotiffinfo('NDVI.tif'); % geoinfo of clip layer 
infoMASK = geotiffinfo('MASK.tif'); % geoinfo of larger layer 

ncolsMASK = infoMASK.Width; 
nrowsMASK = infoMASK.Height; 
nrowsNDVI = infoNDVI.Height; 
ncolsNDVI = infoNDVI.Width; 

B1 = infoMASK.BoundingBox; 
Bm = infoNDVI.BoundingBox; 

res = infoMASK.PixelScale(1); % res is the pixel dimension 

% Calculate the X and Y distances of the four corners of the clipping image from the origin of the larger image 

d1 = fix([ (Bm(1) -B1(1)) (Bm(3) -B1(3))]/res); 
d2 = fix([ (Bm(1) -B1(1)) (Bm(4) -B1(3))]/res); 
d3 = fix([ (Bm(2) -B1(1)) (Bm(4) -B1(3))]/res); 
d4 = fix([ (Bm(2) -B1(1)) (Bm(3) -B1(3))]/res); 

% calculate row column indices of the clip layer and extract values for the clip extent 
% Downscale resolution of the larger image to match the clip image 
% Multiply the binary images and write that output as a geotiff file 

NI = [ (nrowsMASK - d3(2)) (nrowsMASK - d1(2)) d1(1) d3(1) ];  
In = I(NI(1):NI(2),NI(3):NI(4)); % clipped binary 

resampledIn = imresize(In, [nrowsNDVI, ncolsNDVI]); % resample the binary layer to the size of clipped layer 
intersected = immultiply(resampledIn,Ic); 
outfilename = ['clipIntersect1' '.tif']; 
geotiffwrite('OUTPUT.tif', intersected, R, 'GeoKeyDirectoryTag', infoC.GeoTIFFTags.GeoKeyDirectoryTag); 

回答

1

我能想到的最簡單方法是使用邏輯索引檢查指標的有效性。這裏有一個小例子來說明如何可以做到:

I = ones(10); 
NI = [-2 3 8 12]; 

% Get your rows and columns 
iRows = NI(1):NI(2); 
iCols = NI(3):NI(4); 
desiredSize = [numel(iRows), numel(iCols)]; 

% Check validity 
ilValidRows = iRows > 0 & iRows <= size(I, 1); 
ilValidCols = iCols > 0 & iCols <= size(I, 2); 

% set everything to zero 
In = zeros(desiredSize); 

% assign the values based on logical indexing 
In(ilValidRows, ilValidCols) = I(iRows(ilValidRows), iCols(ilValidCols)); 

您用下列值最終爲In

In = 

    0  0  0  0  0 
    0  0  0  0  0 
    0  0  0  0  0 
    1  1  1  0  0 
    1  1  1  0  0 
    1  1  1  0  0 
+0

大,感謝您的幫助。當我嘗試並將它們放在一起時,出現以下錯誤:'提供了一個map.rasterref.MapCellsReference對象用於功能GEOTIFFWRITE,但其RasterSize值與柵格大小矢量不一致。關於我要去哪裏的任何想法都是錯誤的? – Borealis

+0

不,我從來沒有使用過這個功能。我會檢查功能文件 – hoogamaphone