matlan批量处理图片二值化方法代码
时间: 2024-05-01 15:19:59 浏览: 126
以下是MATLAB中使用im2bw函数进行图片二值化的示例代码,该代码可以批量处理一组图片:
```matlab
% 设置文件夹路径
folder = 'C:\Users\UserName\Documents\Images';
% 获取文件夹中所有图片的信息
filelist = dir(fullfile(folder,'*.jpg')); % 修改后缀名以适应不同的图片格式
% 循环处理每张图片
for i = 1:length(filelist)
% 读取图片
filename = fullfile(folder,filelist(i).name);
img = imread(filename);
% 图片二值化
gray_img = rgb2gray(img); % 先转为灰度图像
bw_img = im2bw(gray_img, 0.5); % 以0.5为阈值进行二值化
% 保存处理后的图片
[pathstr,name,ext] = fileparts(filename);
new_filename = fullfile(folder, [name, '_bw', ext]); % 在文件名后面加上后缀"_bw"
imwrite(bw_img, new_filename);
end
```
在上面的代码中,我们首先设置了需要处理的图片所在的文件夹路径,接着使用dir函数获取该文件夹中所有后缀名为".jpg"的图片信息。然后,我们使用一个循环遍历所有图片,读取每张图片并将其转为灰度图像,接着使用im2bw函数将灰度图像二值化,并使用imwrite函数将处理后的二值化图片保存到文件夹中。在保存文件时,我们在文件名后面加上后缀"_bw"以区分原始图片和处理后的二值化图片。
阅读全文
相关推荐

















