clc;
close all;
clear all;
file_path='文件路徑';
img_path_list=dir(strcat(file_path,'*jpg'));%獲取文件
img_num = length(img_path_list); %獲取圖像總數量
I=cell(1,img_num);
if img_num > 0 %判斷符合條件的圖像
for j=1:img_num %逐一讀取
img_name = img_path_list(j).name; %圖像名
img = imread(strcat(file_path,img_name));
I{j} = img;
end
img1=rgb2gray(I{1});
img2=rgb2gray(I{2});
img_jian=(img1-img2)+(img2-img1);%避免數據溢出,因爲可能數據爲負數
img_yuzhi=graythresh(img_jian);
img_erzhi=imbinarize(img_jian,img_yuzhi);
end
shuzu = strel('square', 4); %創造一個4X4的矩陣元素
pengzhang = imdilate(img_erzhi, shuzu); %進行膨脹
liantong = bwlabel(pengzhang); %標記連通區域
stats = regionprops(liantong);
num = length(stats) ; %連通域總個數
subplot(121),imshow(I{1});
hold on
for index=1:num
rectangle('Position',stats(index).BoundingBox,'curvature',[1,1],'LineWidth',1,'EdgeColor','r') ;
end
subplot(122),imshow(I{2});
for index=1:num
rectangle('Position',stats(index).BoundingBox,'curvature',[1,1],'LineWidth',1,'EdgeColor','r') ;
end
實現結果
學一項東西總要實踐一下。