幻方置换,可以自定义幻方矩阵大小和置乱次数

[filename, pathname] = uigetfile({'*.png;*.jpg;*.jpeg;*.bmp', 'Image Files (*.png, *.jpg, *.jpeg, *.bmp)'}, '选择一张图像');
if isequal(filename, 0)
    disp('用户取消了选择');
else
    filepath = fullfile(pathname, filename);
    % 读取图像
    img = imread(filepath);
    n = 5;  % 5 x 5 幻方矩阵
    count = 3;  % 置乱次数
    % 应用幻方置乱
    MagicImg = Magic2024(img, n, count);
    % 显示结果图像
    imshow(MagicImg);
end
function MagicImg = Magic2024(img, n, count)
    if size(img, 3) > 1
        img = rgb2gray(img);
    end
    
    n = max(1, floor(n));  %n>1
    n = 2*fix(n/2) + 1; 
    count = max(0, floor(count));  % 非负数
    
    [rows, cols] = size(img);
    
    % 大小为n的幻方
    magic_square = magic(n);
    
    for iter = 1:count
        % Create a copy of the image to modify
        modified_img = img;
        
        % 将图像重新整形为大小为n x n的块,并对每个块进行加扰
        for i = 1:ceil(rows/n)
            for j = 1:ceil(cols/n)
                row_start = (i-1)*n + 1;
                row_end = min(i*n, rows);
                col_start = (j-1)*n + 1;
                col_end = min(j*n, cols);
                
                block = img(row_start:row_end, col_start:col_end);
                
                
                if size(block, 1) ~= n || size(block, 2) ~= n
                    continue; 
                end
                
                % 幻方置乱
                block_indices = reshape(magic_square, [], 1);  
                scrambled_block = block(block_indices);  
                
                % 放回相应块
                modified_img(row_start:row_end, col_start:col_end) = reshape(scrambled_block, size(block));
            end
        end
        
        %为下一次迭代更新图像
        img = modified_img;
    end
    
    MagicImg = cast(img, class(img));
end

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值