如何处理图像范围错误?

以下matlab脚本将较大的蒙版图像剪切到较小灰度图像的边界框并遮盖较小图像的区域。 只要较小的图像位于较大图像的范围内,此功能就很有用。 但是,如果较小的图像超出较大图像的范围(附加屏幕截图),则会出现以下错误:

Index exceeds matrix dimensions.

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

我希望将较大图像范围之外的小图像的任何像素值转换为0. 我可以使用哪些方法来处理此图像范围错误?


在这里输入图像描述


%% 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);

我能想到的最简单的方法是使用逻辑索引来检查索引有效性。 这里有一个小例子来说明如何完成它:

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
链接地址: http://www.djcxy.com/p/61167.html

上一篇: How to handle image extent error?

下一篇: Implementing imclose(IM, SE) in opencv