How to measure the rotation of a image in MATLAB?

前端 未结 3 875
Happy的楠姐
Happy的楠姐 2021-01-06 06:42

I have two images. One is the original, and the another is rotated.

\"Original

Now, I need to d

3条回答
  •  自闭症患者
    2021-01-06 07:03

    You can detect the corners of one of the colored rectangles in both the image and the rotated version, and use these as control points to infer the transformation between the two images (like in image registration) using the CP2TFORM function. We can then compute the angle of rotation from the affine transformation matrix:

    Here is an example code:

    %# read first image (indexed color image)
    [I1 map1] = imread('http://i.stack.imgur.com/LwuW3.png');
    
    %# constructed rotated image
    deg = -15;
    I2 = imrotate(I1, deg, 'bilinear', 'crop');
    
    %# find blue rectangle
    BW1 = (I1==2);
    BW2 = imrotate(BW1, deg, 'bilinear', 'crop');
    
    %# detect corners in both
    p1 = corner(BW1, 'QualityLevel',0.5);
    p2 = corner(BW2, 'QualityLevel',0.5);
    
    %# sort corners coordinates in a consistent way (counter-clockwise)
    p1 = sortrows(p1,[2 1]);
    p2 = sortrows(p2,[2 1]);
    idx = convhull(p1(:,1), p1(:,2)); p1 = p1(idx(1:end-1),:);
    idx = convhull(p2(:,1), p2(:,2)); p2 = p2(idx(1:end-1),:);
    
    %# make sure we have the same number of corner points
    sz = min(size(p1,1),size(p2,1));
    p1 = p1(1:sz,:); p2 = p2(1:sz,:);
    
    %# infer transformation from corner points
    t = cp2tform(p2,p1,'nonreflective similarity');    %# 'affine'
    
    %# rotate image to match the other
    II2 = imtransform(I2, t, 'XData',[1 size(I1,2)], 'YData',[1 size(I1,1)]);
    
    %# recover affine transformation params (translation, rotation, scale)
    ss = t.tdata.Tinv(2,1);
    sc = t.tdata.Tinv(1,1);
    tx = t.tdata.Tinv(3,1);
    ty = t.tdata.Tinv(3,2);
    translation = [tx ty];
    scale = sqrt(ss*ss + sc*sc);
    rotation = atan2(ss,sc)*180/pi;
    
    %# plot the results
    subplot(311), imshow(I1,map1), title('I1')
    hold on, plot(p1(:,1),p1(:,2),'go')
    subplot(312), imshow(I2,map1), title('I2')
    hold on, plot(p2(:,1),p2(:,2),'go')
    subplot(313), imshow(II2,map1)
    title(sprintf('recovered angle = %g',rotation))
    

    screenshot

提交回复
热议问题