简化版HOG计算

HOG用了很久,今天试着自己写了一个

大部分用的还是matlab工具箱的函数

梯度直方图差值哪里没有编写

代码里有最后显示成向量图的方法

程序编的不对的地方,请大家指正。

第一个是主程序:

clc;
clear;
image = imread('crop001019.png');
figure;
imshow(image);
image = double(image);
image = imresize(image,[128 64]);

block = zeros(16,16);
cell = 8;
block = 16;
for i = 0:1:14
    for j = 0:1:6
        for n = 1:1:16
            for k = 1:1:16
                block(n,k) = image(i*8+n,j*8+k);
            end
        end
        feature = hist(block);
        for e = 1:1:2
            for t = 1:1:2
                result(i*2+e,j*2+t,:) = feature(e,t,:);
            end
        end
    end
end

w = result;
bs = 8;
bim1 = zeros(bs, bs);
bim1(:,round(bs/2):round(bs/2)+1) = 1;
bim = zeros([size(bim1) 9]);
bim(:,:,1) = bim1;
for i = 2:9,
  bim(:,:,i) = imrotate(bim1, -(i-1)*20, 'crop');
end

s = size(w);    
w(w < 0) = 0;    
im = zeros(bs*s(1), bs*s(2));
for i = 1:s(1),
  iis = (i-1)*bs+1:i*bs;
  for j = 1:s(2),
    jjs = (j-1)*bs+1:j*bs; 
%     k = find(w(i,j,:)==max(w(i,j,:)));
%     if length(k)>1
%         k = k(1);
%     end
    for k=1:1:9
        im(iis,jjs) = im(iis,jjs) + bim(:,:,k) * w(i,j,k);
    end
  end
end

scale = max(w(:));
im = uint8(im * (255/scale));
% im = uint8(im);
figure;
imshow(im);
其中的hist为计算每个block的梯度直方图

返回一个2*2*9的矩阵。

代码如下:

function feature = hist(block)
block = block;
feature = zeros(2,2,9);
for i = 0:1:1
    for j = 0:1:1
        for k = 1:1:8
            for n = 1:1:8
                cell(k,n) = block(i*8+k,j*8+n);
            end
        end
        hx = [-1,0,1];
        hy = -hx';
        Fx = imfilter(double(cell),hx);
        Fy = imfilter(double(cell),hy);
        Q = atan2(Fy,Fx);
        Q = abs(Q);
        Q = Q.*180./pi;
        Q = round(Q);
        for u = 1:1:64
            if Q(u)>=0&Q(u)<20 feature(i+1,6) = feature(i+1,6) + 1; end
            if Q(u)>=20&Q(u)<40 feature(i+1,5) = feature(i+1,5) + 1; end
            if Q(u)>=40&Q(u)<60 feature(i+1,4) = feature(i+1,4) + 1; end
            if Q(u)>=60&Q(u)<80 feature(i+1,3) = feature(i+1,3) + 1; end
            if Q(u)>=80&Q(u)<100 feature(i+1,2) = feature(i+1,2) + 1; end
            if Q(u)>=100&Q(u)<120 feature(i+1,1) = feature(i+1,1) + 1; end
            if Q(u)>=120&Q(u)<140 feature(i+1,9) = feature(i+1,9) + 1; end
            if Q(u)>=140&Q(u)<160 feature(i+1,8) = feature(i+1,8) + 1; end
            if Q(u)>=160&Q(u)<=180 feature(i+1,7) = feature(i+1,7) + 1; end
        end
    end
end
feature = feature./64;

有可以优化或者不对的地方,请大神指出。


你可能感兴趣的:(优化,function,image,matlab,IIS,IM)