一、结果
二、代码
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