0. 前言
在学生时代,我们会在实验中输出一些图片,这些图片背景为黑色,我们需要将其背景反色为白色,方便打印:
1. matlab代码
%% 图片反色批量处理
clc
clear
file_path = 'picture\';% 图像文件夹路径
delete('picture_back\*.jpg')
delete('picture_back\*.png')
img_path_list = dir(strcat(file_path,'*.png'));%获取该文件夹中所有.png格式的图像
img_num = length(img_path_list);%获取图像总数
if img_num > 0 %有满足条件的图像
for pn = 1:img_num %逐一读取图像
image_name = img_path_list(pn).name;% 图像名
img_origin = imread(strcat(file_path,image_name));%读取图像
fprintf('%d %s\n',pn,strcat(file_path,image_name));% 显示正在处理的图像名
figure, subplot(2, 1, 1),imshow(img_origin);
I_reverse = imcomplement(img_origin);%反色
subplot(2, 1, 2),imshow(I_reverse);
% imwrite(I_reverse,strcat('picture_back\',image_name(1:end-4) ,'.','jpg'));%去掉后缀保存为.jpg
imwrite(I_reverse,strcat('picture_back\',image_name));%保存为原文件名
end
end
2. 代码使用方式
在.m
文件目录下新建picture
和picture_back
文件夹
3. 输出文件示例
原图片:
输出图片: