寻找径向段的最近邻居

时间:2015-10-10 11:51:28

标签: algorithm matlab geometry nearest-neighbor feature-descriptor

首先,不要害怕这个问题的外观;)

我正在尝试在matlab中实现一个名为Circular Blurred Shape Model的形状描述符,其中一部分是获取每个径向段的最近邻居列表,如图1d所示。

我在MATLAB中进行了一个简单而简单的实现,但是我坚持算法的第5步和第6步,主要是因为我无法理解这个定义:

Xb{c,s} = {b1, ..., b{c*s}} as the sorted set of the elements in B* 
so that d(b*{c,s}, bi*) <= d(b*{c,s}, bj*), i<j

对我而言,这听起来像一个级联排序,首先按升序距离排序,然后按升序索引排序,但我找到的最近邻居不符合论文。

Circulare Blurred Shape Model Description Algorithm

作为一个例子,我向你展示了我为段b {4,1}获得的最近邻居,这是图1d中标记为“EX”的那个)

我得到b {4,1}的最近邻居列表:b{3,2}, b{3,1}, b{3,8}, b{2,1}, b{2,8}

根据论文的正确性是:b{4,2}, b{4,8}, b{3,2}, b{3,1}, b{3,8}

然而,我的分数实际上是按欧几里德距离测量的最接近所选分段的设置!距离b{4,1} <=> b{2,1}小于b{4,1} <=> b{4,2}b{4,1} <=> b{4,8} ...

enter image description here

这是我的(丑陋,但直截了当)MATLAB代码:

width  = 734;
height = 734;

assert(width == height, 'Image must be square in size!');

% Radius of the correlogram
R = width;

% Number of circles in correlogram
C = 4;

% Number of sections in correlogram
S = 8;

% "width" of ring segments
d = R/C;

% angle of one segment in degrees
g = 360/S;

% set of bins for the circular description of I
B = zeros(C, S);

% centroid coordinates for bins
B_star = zeros(C,S,2);


% calculate centroids of bins
for c=1:C
    for s=1:S
        alpha = deg2rad(max(s-1, 0)*g + g/2);
        r     = d*max((c-1),0) + d/2;

        B_star(c,s,1) = r*cos(alpha);
        B_star(c,s,2) = r*sin(alpha);
    end
end

% create sorted list of bin numbers which fullfill
% d(b{c,s}*, bi*) <= d(b{c,s}, bj*) where i<j

% B_star_dists is a simple square distance matrix for getting
% the distance between two centroids c_i,s_i and c_j,s_j
B_star_dists = zeros(C*S, C*S);
for i=1:C*S
    [c_i, s_i] = ind2sub([C,S], i);
    % x,y centroid coordinates for point i
    b_star_i   = [B_star(c_i, s_i, 1), B_star(c_i, s_i, 2)];

    for j=1:C*S
        [c_j, s_j] = ind2sub([C,S], j);
        % x,y centroid coordinates for point j
        b_star_j   = [B_star(c_j, s_j, 1), B_star(c_j, s_j, 2)];

        % store the euclidean distance between these two centroids
        % in the distance matrix.
        B_star_dists(i,j) = norm(b_star_i - b_star_j);
    end
end

% calculate nearest neighbour "centroids" for each centroid
% B_NN is a cell array, B{idx} gives an array of indexes to the 
% nearest neighbour centroids. 

B_NN = cell(C*S, 1);
for i=1:C*S
    [c_i, s_i] = ind2sub([C,S], i);

    % get a (C*S)x2 matrix of all distances, the first column are the array
    % indexes and the second column are the distances e.g
    % 1   d1
    % 2   d2
    % ..  ..
    % CS  d{c,s}

    dists = [transpose(1:C*S), B_star_dists(:, i)];

    % sort ascending by the distances first (e.g second column) then
    % sort ascending by the array index (e.g first column)
    dists = sortrows(dists, [2,1]);

    % middle section has nine neighbours, set as default
    neighbour_count = 9;

    if c_i == 1
        % inner region has S+3 neighbours
        neighbour_count = S+3;
    elseif c_i == C
        % outer most ring has 6 neighbours
        neighbour_count = 6;
    end

    B_NN{i} = dists(1:neighbour_count,1);
end

% FROM HERE ON JUST VISUALIZATION CODE

figure(1);
hold on;
for c=1:C
    % plot circles
    r = c*d;
    plot(r*cos(0:pi/50:2*pi), r*sin(0:pi/50:2*pi), 'k:');
end

for s=1:S
    % plot lines

    line_len = C*d;
    alpha    = deg2rad(s*g); 

    start_pt = [0, 0];
    end_pt   = start_pt + line_len.*[cos(alpha), sin(alpha)];

    plot([start_pt(1), end_pt(1)], [start_pt(2), end_pt(2)], 'k-');
end

for c=1:C
    % plot centroids of segments
    for s=1:S
        segment_centroid = B_star(c,s, :);
        plot(segment_centroid(1), segment_centroid(2), '.k');
    end
end

% plot some nearest neighbours
% list of [C;S] 
plot_nn = [4;1];

for i = 1:size(plot_nn,2) 
   start_c = plot_nn(1,i);
   start_s = plot_nn(2,i);

   start_pt = [B_star(start_c, start_s,1), B_star(start_c, start_s,2)];
   start_idx = sub2ind([C, S], start_c, start_s);

   plot(start_pt(1), start_pt(2), 'xb');

   nn_idx_list = B_NN{start_idx};

   for j = 1:length(nn_idx_list)
      nn_idx = nn_idx_list(j); 
      [nn_c, nn_s] = ind2sub([C, S], nn_idx);
      nn_pt = [B_star(nn_c, nn_s,1), B_star(nn_c, nn_s,2)];

      plot(nn_pt(1), nn_pt(2), 'xr');
   end
end

可以找到完整的论文here

3 个答案:

答案 0 :(得分:2)

论文谈到“地区邻居”;这些是欧几里德距离意义上的“最近邻居”的解释是不正确的。它们只是某个区域的邻居区域,找到它们的方法很简单:

区域有2个坐标:(c,s)其中c表示它们所属的同心圆,从中心的1到边缘的C,s表示它们所属的扇区,从1开始从角度0°开始到S以角度360°结束。

c和s坐标与区域坐标最多相差1的每个区域都是相邻区域(区段编号从S到1环绕)。根据区域的位置,有3种情况: (如图1d所示)

  • 该区域是中间区域(标记为MI),例如区域b(2,4)
    有2个相邻的圈子和2个相邻的扇区,总共9个区域:
    圈1,2或3中的每个区域和扇区3,4或5:
    b(1,3), b(2,3), b(3,3), b(1,4), b(2,4), b(3,4), b(1,5), b(2,5), b(3,5)

  • 该区域是内部区域(标记为IN),例如区域b(1,8)
    只有一个相邻的圆圈和2个相邻的扇区,但所有的内部区域都是邻居,所以共有S + 3个区域:
    第2圈和第7,8或1区的每个区域:
    b(2,7), b(2,8), b(2,1)
    以及内圈的每个区域:
    b(1,1), b(1,2), b(1,3), b(1,4), b(1,5), b(1,6), b(1,7), b(1,8)

  • 该区域是外部区域(标记为EX),例如区域b(3,1)
    只有一个相邻的圈子和2个相邻的扇区,总共有6个区域:
    圈2或3中的每个区域和扇区8,1或2:
    b(2,8), b(2,1), b(2,2), b(3,8), b(3,1), b(3,2)

答案 1 :(得分:2)

要将一些matlab添加到@ m69的great answer,您可以自动化邻居的索引,如下所示:

%assume C and S defined according to the answer of @m69
iif=@(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();
ncfun=@(c) iif(c==1,c+1,c==C,c-1,true,[c-1, c+1]);
nsfun=@(s)mod([s-1, s+1]-1,S)+1;
neighbs=@(c,s) [b(c,nsfun(s)), b(ncfun(c),s)', reshape(b(ncfun(c),nsfun(s)),1,[])];
  1. 第一个定义an inline if用于匿名函数,以便在单独的文件中定义函数(c情况需要这样做)。这具有语法iif(condition1,result1,condition2,result2,...),其中每个条件在彼此之后进行测试,并且返回与产生true的第一个条件相对应的结果。

  2. 第二个使用if:return [c-1,c + 1]定义径向邻居索引,除非其中任何一个未定义(这将导致数组绑定违规)

  3. 第三个定义角度扇区的周期性索引,例如S=4 nsfun(2)==[1, 3]nsfun(4)==[3, 1]

  4. 我刚刚添加了一个示例,其中给定的有效c,s neighbs(c,s)对将返回b(1:C,1:S)的邻居的子阵列:首先是上下/左 - 正确的邻居,然后是(最多)四个角落。

答案 2 :(得分:0)

在花了太多时间后,我发现了,计算元素b {c,s}的邻近区域的技巧是:

  • 获取c的相邻环的所有段,包括c本身,即c-1, c, c+1,如果它是最内圈,则只有c,c+1,如果它是最外层的c-1, c }

  • 计算从b {c,s}到上一步所有选定质心的欧氏距离,包括点b {c,s}本身

  • 按升序对距离进行排序,并取前N个段。

描述符效果很好,但是它的旋转不变性取决于具有最高密度的轴,在某些情况下,这对噪声/遮挡非常敏感,即描述符可能是+/- 1旋转关闭。

这是MATLAB中完整的CBSM描述符实现,没有以任何方式进行优化(我听说MATLAB讨厌for循环):

<强> csbm.m

function [descriptor] = csbm(I, R, C, S)
    % Input:
    % ------
    % I = The image, binary, must be square in sice
    % R = The radius of the correlogram, could be half the image width
    % C = Number of circles
    % S = Number of segments per circle

    % Output:
    % -------
    % A C*S-by-1 row vector, the descriptor

    [width, height] = size(I);
    assert(width == height, 'Image must be square in size!');

    % "width" of ring segments
    d = R/C;

    % angle of one segment in degrees
    g = 2*pi/S;

    % centroid coordinates for bins
    B_star = zeros(C*S,2);

    % initialize the descriptor
    descriptor = zeros(C*S,1);

    % calculate centroids of bins
    for c=1:C
        for s=1:S
            alpha = max(s-1, 0)*g + g/2;
            r     = d*max((c-1),0) + d/2;
            ind   = (c-1)*S+s; %sub2ind(cs_size, c,s);

            B_star(ind, :) = [r*cos(alpha), r*sin(alpha)];
        end
    end

    % calculate nearest neighbor regions
    B_NN = cell(C*S,1);

    for c=1:C
        min_circle = max(1,c-1);
        max_circle = min(C,c+1);

        start_sel  = (min_circle-1)*S+1;
        end_sel    = (max_circle)*S;

        centroids  = B_star(start_sel:end_sel, :);

        for s=1:S
            current_ind   = (c-1)*S+s;
            centroid      = B_star(current_ind, :);
            num_centroids = length(centroids);
            distances     = sqrt(sum((centroids-repmat(centroid, num_centroids,1)).^2,2));

            distances     = horzcat(distances, transpose((start_sel:end_sel)));
            distances     = sortrows(distances, [1,2]);

            neighbour_count = 9;

            if c == 1
                % inner region has S+3 neighbours
                neighbour_count = S+3;
            elseif c == C
                % outer most ring has 6 neighbours
                neighbour_count = 6;
            end


            B_NN{current_ind} = distances(1:neighbour_count, 2);
        end
    end

    for x=1:width
        x_centered = x-width/2;

        for y=1:width
            if I(x,y) == 0
                continue;
            end

            y_centered = y-width/2;

            % bin the image point
            r = sqrt(x_centered^2 + y_centered^2);
            a = wrapTo2Pi(atan2(y_centered, x_centered));

            % get bin
            c_pixel = max(1, floor(r/d));
            s_pixel = max(1, floor(a/g));

            if c_pixel > C
                continue;
            end

            ind_pixel = (c_pixel-1)*S+s_pixel;
            pt_pixel  = [x_centered, y_centered];

            % get neighbours of this bin
            neighbours = B_NN{ind_pixel};

            % calculate distance to neighbours
            nn_dists   = sqrt(sum((B_star(neighbours, :) - repmat(pt_pixel, length(neighbours), 1)).^2,2));

            D = sum(1./nn_dists);

            % update the probabilities vector
            descriptor(neighbours) = descriptor(neighbours) + 1./(nn_dists.*D);
        end
    end

    % normalize the vector v
    descriptor   = descriptor./sum(descriptor);

    % make it rotationally invariant
    G = zeros(S/2, 2*C);

    for s=1:S/2
        for c=1:C
            G(s,c)   = descriptor((c-1)*S+s);
            G(s,c+C) = descriptor((c-1)*S+s+S/2);
        end
    end

    [~, max_G_idx] = max(sum(G,2));

    L_G = 0;
    R_G = 0;

    for j=1:C
        for k=1:S
            if k > (max_G_idx) && k < (max_G_idx+S/2)
                L_G = L_G + descriptor((j-1)*S+k); 
            elseif k ~= max_G_idx && k ~= (max_G_idx+S/2)
                R_G = R_G + descriptor((j-1)*S+k); 
            end
        end
    end

    if L_G > R_G
        % B is rotated k=i+S/2-1 positions to the left:
        fprintf('rotate %d to the left\n', max_G_idx+S/2-1);
        rotate_by = -(max_G_idx+S/2-1);
    else
        % B is rotated k=i-1 positions to the right:
        fprintf('rotate %d to the right\n', max_G_idx-1);
        rotate_by = -(max_G_idx-1);
    end

    % segments are grouped by circle
    % so for every circle we get all segments and circular shift them
    for c=1:C
       range_sel = ((c-1)*S+1):(c*S);
       segments  = descriptor(range_sel);
       descriptor(range_sel) = circshift(segments, [rotate_by,0]);
    end
end

<强> plot_descriptor.m

function plot_descriptor(R,C,S, descriptor)
    % Input:
    % ------
    % R Radius for the correlogram in pixels, can be arbitrary
    % C Number of circles
    % S Number of segments per circle
    % descriptor The C*S-by-1 descriptor vector


    % "width" of ring segments
    d = R/C;

    % angle of one segment in degrees
    g = 2*pi/S;

    % full image
    [x,y] = meshgrid(-R:R);
    [theta, rho] = cart2pol(x,y);
    theta = wrapTo2Pi(theta);
    brightness   = zeros(size(rho));

    min_val     = min(descriptor);
    max_val     = max(descriptor);
    scale_fact  = 1/(max_val-min_val);

    for c=1:C
        rInner = (c-1)*d;
        rOuter = c*d;

        for s=1:S
            idx = (c-1)*S+s;

            minTheta = (s-1)*g;
            maxTheta = (s*g);

            matching_theta = find(theta > minTheta & theta < maxTheta);
            matching_rho   = find(rho > rInner & rho < rOuter);
            matching_idx   = intersect(matching_theta, matching_rho);

            intensity = descriptor(idx)*scale_fact;

            brightness(matching_idx) = intensity;
        end
    end

    figure; imshow(mat2gray(brightness));

如何运行

I = imread('bat-18.gif');
I = transpose(im2bw(I, graythresh(I)));
I = edge(I);

[width, height] = size(I);
R = width/2;
C = 24;
S = 24;

descriptor = csbm(I, R, C, S);
plot_descriptor(R,C,S,descriptor);

输出:

Bat image example

只是为了踢,在编码时出现了一些可怕的图片:

enter image description here