image2cols:图像分块
function patches = image2cols(im, pSz, stride)
if nargin < 3,
stride = 1;
end
range_y = 1:stride:size(im, 1)-pSz+1;
range_x = 1:stride:size(im, 2)-pSz+1;
if range_y(end) ~= size(im, 1)-pSz+1,
range_y = [range_y size(im, 1)-pSz+1];
end
if range_x(end) ~= size(im, 2)-pSz+1,
range_x = [range_x size(im, 2)-pSz+1];
end
patches = zeros(pSz^2, length(range_y)*length(range_x));
idx = 1;
for y = range_y,
for x = range_x,
p = im(y:y+pSz-1, x:x+pSz-1);
patches(:, idx) = p(:);
idx = idx+1;
end
end
cols2image:根据块复原原始图像(有些tricky)
function img = cols2image(patches, sz, stride)
if nargin < 3,
stride = 1;
end
pSz = sqrt(size(patches, 1));
range_y = 1:stride:sz(1)-pSz+1;
range_x = 1:stride:sz(2)-pSz+1;
if range_y(end) ~= sz(1)-pSz+1,
range_y = [range_y sz(1)-pSz+1];
end
if range_x(end) ~= sz(2)-pSz+1,
range_x = [range_x sz(2)-pSz+1];
end
img = zeros(sz);
w = zeros(sz);
idx = 1;
for y = range_y,
for x = range_x,
img(y:y+pSz-1, x:x+pSz-1) = img(y:y+pSz-1, x:x+pSz-1) + reshape(patches(:, idx), pSz, pSz);
w(y:y+pSz-1, x:x+pSz-1) = w(y:y+pSz-1, x:x+pSz-1) + 1;
idx = idx + 1;
end
end
img = img./w;
demo
clc; clear; close all;
I = imread('./lena.png');
sz = size(I);
pSz = 5; stride = 2;
% 增大 stride,也即增大块间的偏移,减少块的数目
patches = image2cols(I, pSz, stride);
img = cols2image(patches, sz, stride);
imshow(uint8(img))