orientation

h = filters2();
h0 = h(:,:,1);
h1 = h(:,:,2);
h2 = h(:,:,3);
h11 = h(:,:,4);
h22 = h(:,:,5);
h12 = h(:,:,6);
hr = h11+h22;
hc = h11-h22;
hs = 2*h12;
bc = imfilter(img,hc);
bs = imfilter(img,hs);
br = imfilter(img,hr);
sz = size(img);
data = zeros(2*sz(1),2*sz(2));
xd = 1:sz(1);
yd = 1:sz(2);
data(xd,yd)=img;
data(sz(1)+xd,yd)=bp2(bc,1,2);
data(xd,sz(2)+yd)=bp2(bs,1,2);
data(sz(1)+xd,sz(2)+yd) = bp2(br,1,2);
imshow(imresize(data,0.5))
Warning: Image is too big to fit on screen; displaying at 67% 
theta = linspace(0,180,91);
N = length(theta);
v = zeros(size(theta));
RECT3 =[  488  278  357  306];
for j=1:N
    angle = theta(j)*pi/180;
    c = cos(angle);
    s = sin(angle);
    g = abs(bs*c-bc*s);
    g2 = imcrop(g,RECT3);
    v(j) = max(max(g2));
end

plot(theta,v);
close all
[vs idx] = sort(v,'descend');
k = idx(1);
angle = theta(k)*pi/180;
fprintf('angle %g\n',theta(k));
if npic==6
    angle = 0;
end
c = cos(angle);
s = sin(angle);
g = abs(bs*c-bc*s);
g2 = imcrop(g,RECT3);
gmax = max(max(g2));
fprintf('gmax %g\n',gmax);
gn = g2/gmax;
imshow(gn);
angle 66
gmax 32.9026
thres = 0.77;
imshow(gn>thres);
sz = size(gn);
x = ones(sz(1),1)*(1:sz(2));
y = (1:sz(1))'*ones(1,sz(2));
gt = gn(:);
x = x(:);
y = y(:);
idx = find(gt>thres);

xpts = x(idx);
ypts = y(idx);
plot(xpts,ypts,'ko');
axis ij
axis square

sort vertices

k = 0;
xw = xpts;
yw = ypts;
xc = xpts;
yc = ypts;
while ~isempty(xw)
    test = (xw-xw(1)).^2+(yw-yw(1)).^2;
    [tsort idx] = sort(test);
    xw = xw(idx);
    yw = yw(idx);
    idx = find(tsort<64);
    k = k + 1;
    xc(k) = mean(xw(idx));
    yc(k) = mean(yw(idx));
    idx = find(tsort>64);
%     k
%     idx'
    xw = xw(idx);
    yw = yw(idx);
end
xc = xc(1:k);
yc = yc(1:k);
plot(xc,yc,'o');
axis ij
axis square;

[xleft ileft] = min(xc);
[xright iright] = max(xc);
[ytop itop] = max(yc);
[ybot ibot] = min(yc);

if npic==6
    u = xc - yc;
    v = xc + yc;
    [xleft ileft] = min(u);
    [xright iright] = max(u);
    [ytop itop] = max(v);
    [ybot ibot] = min(v);
end

xp = [ xc(ileft) xc(itop) xc(iright) xc(ibot) xc(ileft)];
yp = [ yc(ileft) yc(itop) yc(iright) yc(ibot) yc(ileft)];
hold on
plot(xp,yp,'k-');
hold off
i2 = imcrop(img,RECT3);
imshow(i2);
hold on
plot(xp(1:4),yp(1:4),'b-','LineWidth',2);
plot(xp(1),yp(1),'ro','MarkerSize',10);
hold off
phi = atan2(yp(2)-yp(3),xp(3)-xp(2))*180/pi
phi =

   60.1314

imshow(imrotate(i2,-phi));