有一点像游程,又不是。
比如,图片矩阵位[20,52;1,25]
我想把它们变为二进制的同时又能有他们的位数
他们四个转为二进制分别是: 10100 110100 1 11001
我想把它们变成一个数,
10100110100111001
之后要用了还能分离出来,我的想法就是他们分别对应 5 6 1 5,但是转为二进制放进去还是不能实现
我可以给出一个实现方案:
encode
函数用于对矩阵进行压缩, decode
函数用于对压缩后的字符串进行解压.
function [encoded, lens] = encode(A)
% ENCODE compresses a matrix A using run-length encoding
% Convert A to binary
B = dec2bin(A);
% Get the number of bits for each element
lens = strlength(B);
% Concatenate all the binary numbers into a single string
bin_str = string(B(:)');
% Count the number of consecutive characters and group by value
[vals, counts] = categorical(bin_str, 'Ordinal', true);
% Create encoded string
encoded = string([]);
for ii = 1:numel(vals)
encoded = [encoded, num2str(counts(ii)), vals(ii)];
end
end
function decoded = decode(encoded, lens)
% DECODE uncompresses an encoded string back into a matrix A
% Separate the encoded string into counts and values
[encoded_num, encoded_char] = separate_metadata(encoded);
% Convert the binary values back into a matrix A
bin_str = repmat(encoded_char, 1, encoded_num);
bin_str = split(bin_str, lens);
A = bin2dec(bin_str);
% Reshape A back into its original form
decoded = reshape(A, size(lens, 1), []);
end
function [counts, chars] = separate_metadata(str)
% Separate an encoded string into counts and values
% Extract counts and characters separately
counts_str = extractBefore(str, 2:2:end);
chars = extractAfter(str, [1, 2:2:end]);
% Convert counts from string to number
counts = str2double(counts_str);
end
以下是测试代码
% Test on example matrix
A = [20, 52; 1, 25];
[encoded, lens] = encode(A);
decoded = decode(encoded, lens);
% Check if decoded matrix is the same as original matrix
assert(isequal(decoded, A));
encode
函数将矩阵A转换为二进制,并记录每个二进制数的位数。对二进制数进行运行长度编码, 并将极其连接成一个字符串. decode
函数从字符串中解码出数据, 并将其转化为二进制数,然后将它们重新分组为原矩阵中的形状.
需要注意的是, 为了确保压缩后的字符串能够正确地解压缩,我们需要在字符串中正确地记录每个二进制数的位数.