MATLAB—背景分割、边缘提取

一、结果

二、代码

I=imread('D:\hongzao.jpg');
subplot(221);imshow(I);
gray = rgb2gray(I);title('原图');
r = I(:,:,1);  %通道R
g = I(:,:,2);  %通道G
b = I(:,:,3);  %通道B
% figure();
subplot(222);imshow(r);title('r');
% figure();
subplot(223);imshow(g);title('g');
% figure();
subplot(224);imshow(b);title('b');

figure();
z=imsubtract(r,b);
subplot(231);imshow(z);title('R-B图');
f=imdivide(z,4);
subplot(232);imshow(f);title('Z/4图');
Level = graythresh(f);  %求取二值化的阈值
BW = im2bw(f, Level);   %按阈值进行二值imshow(BW);
subplot(233);imshow(BW);title('二值图');
BW2 = bwareaopen(BW,1000);%小目标去除
subplot(234);imshow(BW2);title('去除小目标');
img_fill = imfill(BW2, 'holes');
subplot(235);imshow(img_fill);title('孔洞填充');
figure
subplot(121);imshow(~img_fill);title('二值图取反');
edge_img = edge(~img_fill, 'sobel'); 
subplot(122);imshow(edge_img);title('边缘提取');

img1=immultiply(img_fill,r);
img2=immultiply(img_fill,g);
img3=immultiply(img_fill,b);
img=cat(3,img1,img2,img3);

subplot(236);imshow(img);title("红枣");

%RGB分量直方图
fcal=double(I); %后面计算像素点时会有灰度值为255的像素点,将uint8型变为double型,防止溢出
[m,n,h]=size(I);
Y=zeros(h,256);
 
%分别统计原图像RGB基色各灰度级的像素个数
for k=1:h
    for i=1:m
        for j=1:n
            Y(k,fcal(i,j,k)+1)=Y(k,fcal(i,j,k)+1)+1; %哪一灰度级出现一次其相应像素点数+1。灰度级范围是0-255,但矩阵是1-256,列数要额外+1
        end
    end
end
 
X=0:1:255; %建立x坐标轴
figure
histogram=bar(X,Y); %绘制直方图
axis([0 255,-inf inf]) %x坐标轴限制在0-255
xlabel('灰度级');ylabel('像素个数');
 
if h==3 %改变直方图颜色并加轮廓
    title('RGB直方图');
    %分别改变颜色
    set(histogram(1),'FaceColor',[1 0.1882 0.1882]); 
    set(histogram(2),'FaceColor',[0.5 1 0]);
    set(histogram(3),'FaceColor',[0 0.5 1]);
    
    %增加边界轮廓
    hold on
    plot(X,Y(1,:),'Color',[1 0.1882 0.1882]);  %加上边界轮廓
    plot(X,Y(2,:),'Color',[0.5 1 0]);
    plot(X,Y(3,:),'Color',[0 0.5 1]);
    hold off
else
    title('灰度直方图');
end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值