【问题标题】:MATLAB Auto CropMATLAB 自动裁剪
【发布时间】:2014-07-30 21:21:04
【问题描述】:

我正在尝试将下面的图像自动裁剪为边界框。背景将始终是相同的颜色。我已经尝试了答案 Find the edges of image and crop it in MATLAB 以及有关 Mathworks 文件交换的各种应用程序和示例,但我一直无法获得正确的边界框。

我正在考虑将图像转换为黑白,将其转换为二进制并删除所有更接近白色而不是黑色的内容,但我不知道该怎么做。

【问题讨论】:

    标签: matlab image-processing crop bounding-box


    【解决方案1】:

    这是一个不错的方法

    img = im2double(imread('http://i.stack.imgur.com/ZuiEt.jpg')); % read image and convert it to double in range [0..1]
    b = sum( (1-img).^2, 3 ); % check how far each pixel from "white"
    
    % display
    figure; imshow( b > .5 ); title('non background pixels'); 
    
    % use regionprops to get the bounding box
    st = regionprops( double( b > .5 ), 'BoundingBox' ); % convert to double to avoid bwlabel of logical input
    
    rect = st.BoundingBox; % get the bounding box
    
    % display
    figure; imshow( img );
    hold on; rectangle('Position', rect ); 
    


    Jak's request之后,这里是第二行的解释

    在将img 转换为double 类型(使用im2double)后,图像作为h-by-w-by-3 类型的double 矩阵存储在内存中。每个像素有 3 个介于 0 和 1 之间的值(不是 255!),表示其 RGB 值 0 为暗,1 为亮。
    因此(1-img).^2 检查每个像素和每个通道 (RGB) 与 1 的距离有多远 - 明亮。像素越暗 - 这个距离越大。
    接下来,我们使用sum( . ,3 ) 命令将每个通道的距离求和为每个像素的单个值,从而得到h-by-w 每个像素到白色的距离的二维矩阵。
    最后,假设背景是亮白色,我们选择所有远离明亮b > .5 的像素。这个阈值并不完美,但它很好地捕捉到了物体的边界。

    【讨论】:

    • 只是为了让它完整我使用:crop = imcrop(img,rect); imshow(裁剪);
    • 你能解释更多关于它的数学,尤其是第二行吗?
    【解决方案2】:

    根据Shai的回答,我提出了一种仅基于黑白图像上的find来规避regionprops(图像处理工具箱)的方法。

    % load
    img = im2double(imread('http://i.stack.imgur.com/ZuiEt.jpg'));
    % black-white image by threshold on check how far each pixel from "white"
    bw = sum((1-img).^2, 3) > .5; 
    % show bw image
    figure; imshow(bw); title('bw image');
    
    % get bounding box (first row, first column, number rows, number columns)
    [row, col] = find(bw);
    bounding_box = [min(row), min(col), max(row) - min(row) + 1, max(col) - min(col) + 1];
    
    % display with rectangle
    rect = bounding_box([2,1,4,3]); % rectangle wants x,y,w,h we have rows, columns, ... need to convert
    figure; imshow(img); hold on; rectangle('Position', rect);
    

    【讨论】:

    • 您正在以一种非常规的方式定义rect:Matlab 使用[x y w h] 格式(正如您在使用rectangle 时可能注意到的那样)。
    • @Jak 你可以提出这个新问题。
    • @Shai Matlab 在所有与图像相关的方法中都存在将 x 定义为二级维度的问题。为了避免我这边的混淆,我跳过了 x 和 y 并且经常只谈论与 Matlab 的其余部分更一致的第一维(行)和第二维(列)。编辑代码使其更清晰可见。
    【解决方案3】:

    裁剪图像 首先在要裁剪的位置创建边界框。

    crp = imcrop(original_image_name,boundry_box);

    我已经在我的作业中做到了这一点。这真的有效!!!!!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 2015-05-30
      • 2014-07-29
      • 2022-01-22
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多