数字图像处理-图像合成

图像分割

选择特定拓展名

1
2
3
4
5
6
7
8
img_path =  'pics/';

ext = {'*.jpeg','*.jpg','*.png'};
img_list = [];
for i = 1:numel(ext)
img_list = [img_list ; dir(fullfile(img_path,ext{i}))];
end
img_num = length(img_list);

转换为特定尺寸的灰度图像

1
2
3
4
5
6
7
8
9
10
11
if img_num > 0
for j = 1 : img_num
img_name = img_list(j).name;
img = imread(strcat(img_path,img_name));
img = imresize(img,[640 480]);
G = rgb2gray(img);
strname = strsplit(img_name,'.');
name = strname{1,1};
imwrite(G , strcat(img_path, name , '.gif'));
end
end

求素材图片的RGB平均值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
SIZE = 5;

img_RGB = zeros(img_num,SIZE,SIZE,3);
average_rgb = zeros(img_num,3);

if img_num > 0
for j = 1:img_num
img_name = img_list(j).name;
img = imread(strcat(img_path,img_name));
img = imresize(img,[SIZE SIZE]);
img_RGB(j,:,:,:) = img;

R = img(:,:,1);
G = img(:,:,2);
B = img(:,:,3);

average_rgb(j,1)=mean(mean(R));
average_rgb(j,2)=mean(mean(G));
average_rgb(j,3)=mean(mean(B));
end
end

替换为素材图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
original_Img = 	('original.png');
Image_size = size(original_Img);

Image_RGB = zeros(Image_size(1),Image_size(2),3);
Image_RGB = original_Img(:,:,:);

for row = 1 : SIZE :Image_size(1)-SIZE
for col = 1 : SIZE :Image_size(2)-SIZE
rgb_mean = zeros(3);
for k = 1:3
temp = original_Img(row:row+SIZE-1 ,col:col+SIZE-1,k);
rgb_mean(k) = mean(mean(temp));
end

deviation = zeros(1,img_num);
for k = 1:img_num
deviation(k) = abs(average_rgb(k,1) - rgb_mean(1)) + abs(average_rgb(k,2) - rgb_mean(2)) + abs(average_rgb(k,3) - rgb_mean(3)); 求目标区域与每一个素材图片的RGB误差
end

[min_value,min_position] = min(deviation); %得到最小值下标

Image_RGB(row:row+SIZE-1 ,col:col+SIZE-1,:) = img_RGB(min_position,:,:,:);
end
end

Image_RGB = uint8(Image_RGB);
imwrite(Image_RGB,'0.jpg');

实验结果

素材图片

original pic

After