先决条件: MATLAB中的图像表示
在MATLAB中,图像存储在矩阵中,矩阵的每个元素对应于图像的单个离散像素。如果我们反转每列中像素(矩阵的元素)的顺序,则可以垂直(沿x轴)翻转给定的图像,如下图所示。
代码1:使用MATLAB库函数
% Read the target image file
img = imread('leaf.png');
% Reverse the order of the element in each column
vertFlip_img = flip(img, 1);
% Display the vertically flipped image
imshow(vertFlip_img);
title('Vertically flipped image');
代码2:使用矩阵处理
% Read the target image file
img = imread('leaf.png');
% Flip the columns vertically
vertFlip_img = img(end : -1: 1, :, :);
% Display the vertically flipped image
imshow(vertFlip_img);
title('Vertically flipped 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 column in every image plane
- Display the water image (vertically flipped 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 column
% in each image plane (dimension)
for plane = 1 : z
len = x;
for i = 1 : x
for j = 1 : y
% To reverse the order of the element
% of a column we can swap the
% topmost element of the row with
% its bottom-most element
if i < x/2
temp = img(i, j, plane);
img(i, j, plane) = img(len, j, plane);
img(len, j, plane) = temp;
end
end
len = len - 1;
end
end
% Display the vertically flipped image
imshow(img);
title('Vertically flipped image');
输入图片: leaf.png
输出: