我正在尝试编写一个脚本来读取文件夹中的所有JPG图像并根据此脚本裁剪它们:
myFolder = 'D:/Temp/';
filePattern = fullfile(myFolder, '*.jpg');
jpegFiles = dir(filePattern);
for k = 1:length(jpegFiles)
baseFileName = jpegFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
%// show image
imshow(fullFileName)
%// Make a binary image
grayImage = rgb2gray(fullFileName);
binaryImage = grayImage < 250;
[y,x] = find(binaryImage); %// Find row and column locations that are non-zero
%// Find top left corner
xmin = min(x(:));
ymin = min(y(:));
%// Find bottom right corner
xmax = max(x(:));
ymax = max(y(:));
%// Find width and height
width = xmax - xmin + 1;
height = ymax - ymin + 1;
%// Crop image
outputImage = imcrop(fullFileName, [xmin ymin width height]);
imshow(outputImage);
end
但是我收到了这个错误:
Warning: Image is too big to fit on screen; displaying at 67%
> In images.internal.initSize (line 71)
In imshow (line 305)
In Untitled2 (line 9)
Error using rgb2gray>parse_inputs (line 82)
MAP must be a m x 3 array.
Error in rgb2gray (line 37)
X = parse_inputs(X);
Error in Untitled2 (line 11)
grayImage = rgb2gray(fullFileName);
如果我在单个图像上应用循环内部,它可以正常工作。
知道我做错了吗?
答案 0 :(得分:1)
这可能意味着您的某些图像不 RGB但是灰度/单通道。您可以通过添加一个检查以确定读入的图像是否有三个通道来解决此问题,如果有,请相应地调用rgb2gray
。此外,rgb2gray
需要图片,但您提供的是字符串:
grayImage = rgb2gray(fullFileName);
首先使用imread
读取图片,然后在此图片上使用rgb2gray
:
for k = 1:length(jpegFiles)
baseFileName = jpegFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
%// show image
imshow(fullFileName)
%// Read in image first
img = imread(fullFileName);
%// Make a binary image
if size(img,3) == 3
grayImage = rgb2gray(img);
else
grayImage = img;
end
%//....
%//rest of your code here
end