先决条件: MATLAB中的图像表示
在MATLAB中,图像存储在矩阵中,矩阵的每个元素对应于图像的单个离散像素。如果我们颠倒每一行中像素(矩阵元素)的顺序,我们可以得到给定图像的镜像。
代码1:使用MATLAB库函数
% Read the target image file
img = imread('leaf.png');
% Reverse the element in each row
mirror_image = flip(img, 2);
% Display the mirror image
imshow(mirror_img);
title('Mirror image');
代码2:使用矩阵处理
% Read the target image file
img = imread('leaf.png');
% Flip the columns left to right
mirror_image = img(:, end :, -1:, 1, :);
% Display the mirror image
imshow(mirror_img);
title('Mirror image');
代码3:使用矩阵处理(使用循环)
Approach:
- Read the source image file in MATLAB environment
- Get the Dimensions of the image matrix
- Reverse the order of the elements of each row in every image plane
- Display the mirror image
下面是上述方法的实现:
% Read the target image file
img = imread('leaf.png');
% Get the dimensions of the image
[x, y, z] =size(img);
% Reverse elements of each row
% in every image plane
for plane = 1: z
for i = 1 : x
len = y;
for j = 1 : y
% To reverse the order of the element
% of a row we can swap the
% leftmost element of the row with
% its rightmost element
if j < y/2
temp = img(i, j, plane);
img(i, j, plane) = img(i, len, plane);
img(i, len, plane) = temp;
len = len - 1;
end
end
end
end
% Display the mirror image
imshow(img);
title('Mirror image');
输入图像: leaf.png
输出: