【问题标题】:Crop images in folder - Matlab裁剪文件夹中的图像 - Matlab
【发布时间】:2015-11-09 23:41:20
【问题描述】:

我正在尝试编写一个脚本来读取文件夹中的所有 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);

如果我在单个图像上应用循环内部,它可以正常工作。

知道我做错了什么吗?

【问题讨论】:

    标签: image matlab image-processing


    【解决方案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
    

    【讨论】:

    • 我编辑/更新了脚本,但它仍然不起作用。还有什么想法吗?
    • @user2788464 我的代码出错了。请看编辑。忘记更改rgb2gray 呼叫。
    猜你喜欢
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 2012-02-12
    • 1970-01-01
    • 2011-09-03
    相关资源
    最近更新 更多