如何在Matlab中实现图像绕X/Y轴的3D空间旋转
Matlab实现图像绕X/Y轴的3D旋转(指定角度+保留尺寸)
核心思路
要实现类似在线工具的3D旋转效果,本质是把图像放在3D空间的Z=0平面,绕X/Y轴旋转指定角度后,通过透视投影映射回2D平面,最后强制输出尺寸与原图像一致。以下是具体实现方案:
绕X轴旋转的代码实现
% 示例输入图像(替换为你的100×100 uint8矩阵) img_orig = randi(255, 100, 100, 'uint8'); theta = 60; % 旋转角度(单位:度) output_size = size(img_orig); fill_val = 128; % 背景填充值 % 自定义变换函数:实现3D绕X轴旋转+透视投影 function [xy_out] = transform_x(xy_in, theta_rad, camera_z) x = xy_in(:, 1); y = xy_in(:, 2); z = zeros(size(x)); % 图像初始在Z=0平面 % 绕X轴旋转计算 y_rot = y * cos(theta_rad) - z * sin(theta_rad); z_rot = y * sin(theta_rad) + z * cos(theta_rad); % 透视投影(相机位于Z=camera_z位置,看向Z=0平面) proj_factor = camera_z / (camera_z - z_rot); x_proj = x * proj_factor; y_proj = y_rot * proj_factor; xy_out = [x_proj, y_proj]; end % 构建变换结构体 theta_rad = deg2rad(theta); camera_z = 2; % 相机距离,可调整以改变透视强度 tform = maketform('custom', 2, 2, [], @(x) transform_x(x, theta_rad, camera_z)); % 执行变换,强制保留原尺寸 img_rot_x = imwarp(img_orig, tform, ... 'Interpolation', 'bicubic', ... 'OutputView', imref2d(output_size), ... 'FillValues', fill_val); % 显示结果 subplot(1,2,1); imshow(img_orig); title('原图像'); subplot(1,2,2); imshow(img_rot_x); title(['绕X轴旋转', num2str(theta), '°']);
绕Y轴旋转的代码实现
仅需修改自定义变换函数和旋转逻辑:
% 自定义变换函数:绕Y轴旋转+透视投影 function [xy_out] = transform_y(xy_in, theta_rad, camera_z) x = xy_in(:, 1); y = xy_in(:, 2); z = zeros(size(x)); % 绕Y轴旋转计算 x_rot = x * cos(theta_rad) + z * sin(theta_rad); z_rot = -x * sin(theta_rad) + z * cos(theta_rad); % 透视投影 proj_factor = camera_z / (camera_z - z_rot); x_proj = x_rot * proj_factor; y_proj = y * proj_factor; xy_out = [x_proj, y_proj]; end % 构建变换并执行 tform_y = maketform('custom', 2, 2, [], @(x) transform_y(x, theta_rad, camera_z)); img_rot_y = imwarp(img_orig, tform_y, ... 'Interpolation', 'bicubic', ... 'OutputView', imref2d(output_size), ... 'FillValues', fill_val); subplot(1,2,1); imshow(img_orig); title('原图像'); subplot(1,2,2); imshow(img_rot_y); title(['绕Y轴旋转', num2str(theta), '°']);
关键说明
- 角度控制:通过修改
theta变量直接指定旋转角度,转换为弧度后参与矩阵计算。 - 尺寸保留:使用
imwarp的OutputView参数,传入imref2d(output_size)强制输出图像与原尺寸一致。 - 透视效果:调整
camera_z值可改变透视强度——值越小,近大远小的效果越明显;值越大,越接近正交投影。 - 旧方法问题:你之前用的
imtransform结合手动 projective 变换,无法直接关联3D旋转角度,且size参数仅能约束输出尺寸,但无法保证变换后的内容完全适配,而imwarp的OutputView能更精准控制输出空间。
内容的提问来源于stack exchange,提问作者ahach
相关产品推荐
相关产品推荐

