function [cx, cy, w, h, orient, count] = getObjectRegion(keypt1, keypt2, matches, objbox, thresh)

% Find parameters for object bounding box
objx = mean(objbox([1 3])); % x-center
objy = mean(objbox([2 4])); % y-center
objw = objbox(3)-objbox(1);
objh = objbox(4)-objbox(2);

% Find parameters for keypoints in image 1
s1 = keypt1(3, matches(1, :));
o1 = keypt1(4, matches(1, :));
x1 = keypt1(1, matches(1, :));
y1 = keypt1(2, matches(1, :));

% Find parameters for keypoints in image 2
s2 = keypt2(3, matches(2, :));
o2 = keypt2(4, matches(2, :));
x2 = keypt2(1, matches(2, :));
y2 = keypt2(2, matches(2, :));

% vote from each keypoint
vote_w = s2./s1*objw;
vote_x = x2 + sum([(objx-x1) ; (objy-y1)] .* [cos(o2-o1) ; -sin(o2-o1)],1).*(s2./s1);%(objx-x1)./s1.*s2;
vote_y = y2 + sum([(objx-x1) ; (objy-y1)] .* [sin(o2-o1) ; cos(o2-o1)],1).*(s2./s1); %(objy-y1)./s1.*s2;
vote_o = mod(o2-o1+pi/4, 2*pi)-pi/4; % pi/4 shift is so that 0 rotation doesn't get split bins

% Use four uniform bins for each dimension within range of x.  This
% certainly isn't optimal, but it gets the job done for this problem.
nbins = 4;
bs = assign2bins(vote_w, nbins);
bo = assign2bins(vote_o, nbins);
bx = assign2bins(vote_x, nbins);
by = assign2bins(vote_y, nbins);

% note: having many nested for loops and dynamic array extensions (end+1)
% is very slow, but it makes the code easier to read
cx = []; cy = []; w = []; h = []; orient = []; count=[];
for ks = 1:nbins
    for ko = 1:nbins
        for kx = 1:nbins
            for ky = 1:nbins
                ind = bs==ks & bo==ko & bx==kx & by==ky;
                if sum(ind)>thresh                    
                    cx(end+1) = median(vote_x(ind));
                    cy(end+1) = median(vote_y(ind));
                    w(end+1) =  median(vote_w(ind));
                    h(end+1) = median(vote_w(ind))/objw*objh;                    
                    % "orient" for SIFT seems to be defined differently than "orient" in display code, 
                    %   probably because of flipped vertical axis
                    orient(end+1) = -median(vote_o(ind)); 
                    count(end+1) = sum(ind);                
                end                    
            end
        end
    end
end

% creates nb uniform bins within range of x and assigns each x to a bin
function b = assign2bins(x, nb)
b = min(max(ceil((x-min(x))/(max(x)-min(x))*nb), 1), nb);

