MATLAB: Problem using the imcrop function for batch image cropping!

batchcropimageImage Processing Toolboximcropprocessingtif

Hi all,
I wrote a little batch image cropping function based on one my friend wrote but I found it kept getting the same error (after I sorted out the other problems). It seems there is some problem with the imcrop function but I don't know what as I think it is being used in the right way. The aim of the function is to crop all .tif files in a specific folder by the same amount (they all have quite different file names). The images are all the same size to start with. Anyone have any thoughts? Any help would be most appreciated.
The function is:
function fun_im_crop_enlarged_test(basePath)
tifFiles = dir([basePath, '*.tif']);
cropPos = [20, 20, 40, 40];
for k = 1:length(tifFiles)
path1 = [basePath, tifFiles(k).name];
data=imread(path1);
cropIm = imcrop(data, cropPos);
path2 = char([basePath,'_crop_', tifFiles(k).name]);
imwrite(cropIm, path2);
end
The error I am getting is:
??? Error using ==> imcrop>checkCData at 381
Invalid input image.
Error in ==> imcrop>parseInputs at 252
checkCData(a);
Error in ==> imcrop at 94
[x,y,a,cm,spatial_rect,h_image,placement_cancelled] = parseInputs(varargin{:});
Error in ==> fun_im_crop_enlarged_test at 24
cropIm = imcrop(data, cropPos);

Best Answer

Change to insert a whos and tell us what you see in the command window just before it bombs
data=imread(path1);
whos data
whos cropPos
cropIm = imcrop(data, cropPos);
You code is not very robust . For the first example there is no checking of the size of the image to make sure it has at least 40 rows and columns. Also, you're not using fullfile(), not checking to see if tifFiles is null before entering the loop, and not using try/catch. My code is always longer because of all the validation checks I put in there, but I know my code is bulletproof and can be rolled out to users across the globe without worry.
Related Question