[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
幻方置换,可以自定义幻方矩阵大小和置乱次数
最新推荐文章于 2024-07-23 08:31:54 发布