一、 案例背景
在对图像进行处理时,通常是对图像进行图像变换、图像压缩和图像分割等操作。图像处理过程中,往往需要同时对多张图像进行处理,这样可以大大提高工作效率。
二、理论基础
在图像批量读入与处理过程中,可以按照以下步骤进行:
1) 创建指定路径文件夹,存放待处理图像。
file_path ='.\data\'; % 图像文件夹路径
img_path_list = dir(strcat(file_path,'*.jpg')); %获取该文件夹中所有jpg格式的图像
2) 获取图像数量,批量读入图像。
img_num = length(img_path_list);%获取图像总数量
if img_num > 0 %有满足条件的图像
for j = 1:img_num %逐一读取图像
image_name = img_path_list(j).name% 图像名
image = imread(strcat(file_path,image_name))
三、批量读入图像图像的方法
批量读入图像在MATLAB中可以通过循环读入图像实现批量处理。
%批量读取图像的一种简单办法
clear all;
clc;
n=6
I=cell(1,n);
for i=1:n
imageName=strcat(file_path,
num2str(i),'.bmp');
I{i} = imread(imageName);
figure,imshow(I{i});
end
待处理的批量图像
四、单个图像处理
在批量处理图像前,往往需要对单一图像进行处理,预览图像处理结果。如图14-8所示为单一图像处理结果,代码如下:
clear all;
close all;
clc;
I=imread('C:\Users\Data\TestPic2\1.jpg');
figure,subplot(121),imshow(I),title('原始图像')
I_r=I(:,:,1);
I_g=I(:,:,2);
I_b=I(:,:,3);
I_rb=I_r-I_b;
Obj=im2bw(I_rb,5/255);
subplot(122),imshow(Obj),title('分割后图像')
五、批量图像处理
批量图像往往与单一图像特征非常相似,因此,在对单一图像处理时,设置好最佳参数,可以提高在批量处理时的成功率。代码如下:
clear all;
clc;
path=[uigetdir(),'\']; %选取文件的图片
n=6;
I=cell(1,n); %元胞数组
for i=1:n
imageName=strcat(path,num2str(i),'.jpg');
%imageName=strcat('f:\TestPic2\',num2str(i),'.jpg');
%指定文件
路径有时候换电脑运行,由于路径不对会出错
%I= imread(imageName);
I{i} = imread(imageName);
figure,imshow(I{i});
I_r=I{i}(:,:,1);
I_g=I{i}(:,:,2);
I_b=I{i}(:,:,3);
%imtool(I_rb);
I_rb=I_r-I_b;
%imshow(I_rb);
%figure,imhist(I_rb)
Obj=im2bw(I_rb,5/255);
%figure,imshow(Obj)
subplot(1,2,1),imshow(I{i}),title(strcat('原始图像',num2str(i)));
subplot(1,2,2),imshow(Obj),title(strcat('背景分割后的图像',num2str(i)));
%Obj=uint8(Obj);
imwrite(Obj,strcat(num2str(i),'Obj.jpg'));
end
下图所示为图像批量处理结果:
批量处理图像结果