题目:编写函数,实现算法完成图像矩阵的任意角度旋转,接收两个参数,第一个为图像矩阵,第二个为旋转的角度,输出为旋转后的图像(输入图像可以是彩色的也可以是灰度的)。

一、题目中功能要求

1.算法实现

2.图像矩阵

3.任意角度旋转

二、代码实现

using Images
using FileIO
using ImageCore

#自定义旋转函数(灰度图像)
function rotate_image_custom(img::AbstractArray{T,2}, angle_deg::Real) where T
    angle_rad = deg2rad(angle_deg)
    h, w = size(img)
    
    #计算旋转后图像大小
    new_w = ceil(Int, abs(w*cos(angle_rad)) + abs(h*sin(angle_rad)))
    new_h = ceil(Int, abs(h*cos(angle_rad)) + abs(w*sin(angle_rad)))
    
    #创建输出图像
    out = zeros(T, new_h, new_w)
    
    #中心点
    cx_in = w/2
    cy_in = h/2
    cx_out = new_w/2
    cy_out = new_h/2
    
    #旋转参数
    cosθ = cos(angle_rad)
    sinθ = sin(angle_rad)
    
    for y_out in 1:new_h, x_out in 1:new_w
        #计算原图坐标
        x_rel = x_out - cx_out
        y_rel = y_out - cy_out
        
        x_in = cosθ * x_rel + sinθ * y_rel + cx_in
        y_in = -sinθ * x_rel + cosθ * y_rel + cy_in
        
        #检查是否在原图范围内
        if 1 <= x_in <= w && 1 <= y_in <= h
            # 使用最近邻插值
            x_round = round(Int, x_in)
            y_round = round(Int, y_in)
            x_round = clamp(x_round, 1, w)
            y_round = clamp(y_round, 1, h)
            out[y_out, x_out] = img[y_round, x_round]
        end
    end
    
    return out
end

#处理彩色图像
function rotate_image_custom(img::AbstractArray{T,3}, angle_deg::Real) where T
    #对每个颜色通道分别旋转
    channels = [rotate_image_custom(img[:,:,c], angle_deg) for c in 1:size(img,3)]
    return cat(channels..., dims=3)
end

#主函数
function main()
    input_path = "picture.png"
    output_path = replace(input_path, r"\.\w+$" => "_rotated.png")
    rotation_angle = 30.0  #这里可以改角度
    
    try
        println("正在读取图像: $input_path")
        img = load(input_path)
        
        #转换为数组并处理数据类型
        if eltype(img) <: Colorant
            img_array = channelview(float32.(img))  #转换为Float32
            img_array = permutedims(img_array, (2,3,1))  #调整维度顺序
        else
            img_array = float32.(img)
        end
        
        println("正在旋转图像,角度: $rotation_angle 度")
        rotated = rotate_image_custom(img_array, rotation_angle)
        
        #转换回图像格式
        if ndims(img_array) == 3  #彩色图像
            rotated_img = colorview(RGB, permutedims(rotated, (3,1,2)))
        else  #灰度图像
            rotated_img = colorview(Gray, rotated)
        end
        
        println("正在保存旋转后的图像到: $output_path")
        save(output_path, rotated_img)
        
        println("图像旋转完成并已保存!")
    catch e
        println("发生错误: ", e)
        println("堆栈跟踪:")
        showerror(stdout, e, catch_backtrace())
    end
end

# 执行主程序
main()

三、结果展示

四、疑问

若本代码报错,有以下几种可能:

(1)未安装包/包没更新;

(2)图片格式问题,可能是通道不一样;

(3)图片数据通道异常问题;

(4)查看具体报错信息,咨询AI辅助修改。

欢迎各位同学交流互助交作业!

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐