分离前景和背景或在Matlab中更改背景图像的值

时间:2016-05-07 10:12:31

标签: matlab

如何将背景图像颜色更改为黑色或将RGB值更改为黑色背景。我只想拍摄原始的叶子图像。

叶子图像

enter image description here

1 个答案:

答案 0 :(得分:2)

要将背景颜色更改为黑色,您需要以下内容:

  1. 使用阈值计算背景蒙版 阈值可以通过使用函数graythresh自动查找,也可以通过查看图像直方图手动查找。

  2. 使用第1阶段的值执行阈值处理以查找前景蒙版。此外,选择最大的连接组件并执行噪音清理(imclose operation)。

  3. 从FG计算BG,并将原始输入图像中的相应位置清零。

  4. 代码示例:

    I = imread('YaEwk.jpg');
    
    %converts to hsv colorspace, and takes the 3rd dimension. normlizes it.
    im = rgb2hsv(I);
    im = mat2gray(im(:,:,3));
    
    %determines a threshold to distinguish between the leaf and its surroundings.
    T = graythresh(im); 
    
    %defines FG as all the values below the threshold
    %Also, keeps just the biggest connected component and perform noise
    %reduction.
    FG = im < T;
    FG = bwareafilt(FG,1);
    FG = imclose(FG,strel('disk',2));
    
    %defines the background as the opposite of the foreground
    BG = ~FG;
    I(repmat(BG,1,1,3)) = 0;
    
    %smooth the output
    I(:,:,1) = medfilt2(I(:,:,1));
    I(:,:,2) = medfilt2(I(:,:,2));
    I(:,:,3) = medfilt2(I(:,:,3));
    

    结果:

    output image