utilities(matlab)—— 图像分块(image2cols、cols2image)

image2cols:图像分块

function patches = image2cols(im, pSz, stride)
if nargin < 3,
    stride = 1;             % stride:表示块间的偏移
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];
                            % 显然 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(:);
                                % 如果行表示块,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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值