Matlab实现水平方向和垂直方向平移量为30和100的平移操作,将平移前后的图像在一个figure中进行对比显示
时间: 2024-03-01 14:50:08 浏览: 17
下面是实现图像的水平方向和垂直方向平移量为30和100的平移操作,并将平移前后的图像在一个figure中进行对比显示的 Matlab 代码:
```matlab
% 读入图像
img = imread('lena.png');
% 显示原图像
figure, imshow(img), title('Original Image');
% 图像水平移动
shift_distance_horizontal = 30; % 水平方向平移量
shifted_img_horizontal = imtranslate(img, [shift_distance_horizontal, 0]);
% 图像竖直移动
shift_distance_vertical = 100; % 垂直方向平移量
shifted_img_vertical = imtranslate(img, [0, shift_distance_vertical]);
% 在一个figure中显示平移前后的图像
figure,
subplot(1,2,1), imshow(img), title('Original Image');
subplot(1,2,2), imshow(shifted_img_horizontal),
title(['Horizontally Shifted Image: ', num2str(shift_distance_horizontal), ' pixels']);
hold on
h = plot([1 size(img,2)], [size(img,1)-shift_distance_vertical size(img,1)-shift_distance_vertical], 'r', 'LineWidth', 2);
text(10, size(img,1)-shift_distance_vertical-10, [num2str(shift_distance_vertical), ' pixels'], 'Color', 'r', 'FontSize', 12);
hold off
```
在这个程序中,我们首先使用 `imshow` 函数显示原图像。然后,我们分别使用 `imtranslate` 函数实现图像的水平和垂直平移操作,并将平移后的图像保存在 `shifted_img_horizontal` 和 `shifted_img_vertical` 中。
最后,我们使用 `subplot` 函数在一个figure中显示平移前后的图像。我们将原图像显示在左边的子图中,将水平平移后的图像显示在右边的子图中,并在子图的标题中显示平移的像素数。我们在垂直平移后的图像上添加了一条红色的水平线,并在线上方添加了文本,显示平移的像素数。
你可以将这个程序保存为一个Matlab文件,比如 `image_shift.m`,然后在Matlab命令行中运行它。