Matlab 求阴影部分面积

发布时间:2024年01月05日
clear all
close  all
image = imread('pic.png');
imageGray = rgb2gray(image);
S=size(imageGray);
r1=84;
r2=704;
imageGrayMid=imageGray(r1:r2,:);
threshold=(max(imageGrayMid(:))-min(imageGrayMid(:)))*0.5;
label=imageGrayMid<=threshold;
labelAdd=zeros(S);
labelAdd(r1:r2,:)=label;
Area=sum(label(:))/prod(S);
AreasStr=sprintf('S=%f',Area);

%% 均值滤波
Fsize = [3, 3];
imageGrayMid_2 = imfilter(imageGrayMid, fspecial('average', Fsize));
threshold_2=(max(imageGrayMid_2(:))-min(imageGrayMid_2(:)))*0.5;
label_2=imageGrayMid_2<=threshold_2;
labelAdd_2=zeros(S);
labelAdd_2(r1:r2,:)=label_2;
Area_2=sum(label_2(:))/prod(S);
AreasStr_2=sprintf('S=%f',Area_2);

%% 显示
figure
subplot(221)
imshow(imageGray)
title('S=1')
subplot(222)
imshow(1-labelAdd)
title(AreasStr)
subplot(223)
imageGrayMid_2_Add=[imageGray(1:r1-1,:);  imageGrayMid_2;  imageGray(r2+1:end,:)];
imshow(imageGrayMid_2_Add)
title('S=1,均值滤波后')
subplot(224)
imshow(1-labelAdd_2)
title(AreasStr_2)


纠正一下

clear all
close  all
image = imread('pic.png');
imageGray = rgb2gray(image);
S=size(imageGray);
r1=84;
r2=704;
imageGrayMid=imageGray(r1:r2,:);
threshold=(max(imageGrayMid(:))-min(imageGrayMid(:)))*0.5;
label=imageGrayMid<=threshold;
labelAdd=zeros(S);
labelAdd(r1:r2,:)=label;
Area=sum(label(:))/prod(S);
AreasStr=sprintf('S=%f',Area);

%% 均值滤波
Fsize = [3, 3];
imageGray_2 = imfilter(imageGray, fspecial('average', Fsize));
imageGrayMid_2=imageGray_2(r1:r2,:);
threshold_2=(max(imageGrayMid_2(:))-min(imageGrayMid_2(:)))*0.5;
label_2=imageGrayMid_2<=threshold_2;
labelAdd_2=zeros(S);
labelAdd_2(r1:r2,:)=label_2;
Area_2=sum(label_2(:))/prod(S);
AreasStr_2=sprintf('S=%f',Area_2);

%% 显示
figure
subplot(221)
imshow(imageGray)
title('S=1')
subplot(222)
imshow(1-labelAdd)
title(AreasStr)
subplot(223)
%imageGrayMid_2_Add=[imageGray(1:r1-1,:);  imageGrayMid_2;  imageGray(r2+1:end,:)];
imshow(imageGray_2)
title('S=1,均值滤波后')
subplot(224)
imshow(1-labelAdd_2)
title(AreasStr_2)


?保存图片

%% 保存        
% figure
% imshow(1-labelAdd)
% picName=sprintf('LabelGrayImage.tif');
% saveas(gcf,picName)
% picName=sprintf('LabelGrayImage.png');
% saveas(gcf,picName)

%% 滤波前的标签
Temp=uint8(1-labelAdd);
% imwrite(Temp, picName);
% uint8()转换为无符号8位整型,确保保存后的图像范围正确
%这部非常重要,否则输出图像时会因为数据截断造成值全为255
% grayImage = rgb2gray(Temp); % 先将矩阵转换为RGB格式再进行灰度化处理
grayImage= mat2gray(Temp);
%imwrite(grayImage, 'LabelGrayImage.jpg'); 
imwrite(grayImage, 'LabelGrayImage.png'); 
imwrite(grayImage, 'LabelGrayImage.tif'); 

%% 滤波后的图像
Temp=uint8(imageGray_2);
grayImage= mat2gray(Temp);
imwrite(grayImage, 'GrayImage2.png'); 
imwrite(grayImage, 'GrayImage2.tif'); 

%% 滤波后的标签
Temp=uint8(1-labelAdd_2);
grayImage= mat2gray(Temp);
imwrite(grayImage, 'LabelGrayImage2.png'); 
imwrite(grayImage, 'LabelGrayImage2.tif'); 


文章来源:https://blog.csdn.net/qq_22163371/article/details/135398486
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。