首页 > 解决方案 > Adjust regionprops orientation to 0-360 degrees (Matlab)

问题描述

I would like to align video frames to center and reorient an animal walking across the frames. I binarized each frame and fit an ellipse to the animal's body. Binarized with ellipse fit

I used regionprops to find the ellipse, which outputs orientation from -90 to 90 degrees. I rotate each frame depending on the difference between orientation and the desired alignment orientation. The problem I'm having is that sometimes the orientation is aligned to the head and sometimes to the tail, so the alignment is occasionally 180 degrees flipped.

Upright position

Flipped position

I think this can be resolved by putting the orientation output in 0-360 space. Does anyone have a solution for this?

Here is my code:

for i = 1000
frame = read(v,i); 
BW = im2bw(frame,0.95);
imshowpair(frame,BW,'montage') 

% Extract the maximum area
BW = imclearborder(BW);
BW = bwareafilt(BW,1);

% Calculate centroid, orientation and major/minor axis length of the ellipse
s = regionprops(BW,{'Centroid','Orientation','MajorAxisLength','MinorAxisLength'});
centroid(i,:) = s.Centroid; 
orientation(i) = s.Orientation; 
fixed_orientation(i) = s.Orientation; 
delta_angle(i) = -90 - orientation(i); 
if i >=2 
    if diff(sign( fixed_orientation(i-1:i) )) == 2 && abs(fixed_orientation(i-1))-abs(fixed_orientation(i))>=20        
        fixed_orientation(i) = -fixed_orientation(i); 
        delta_angle(i) = -(-90 - fixed_orientation(i)); 

    end 
end 

% Calculate the ellipse line
theta = linspace(0,2*pi);
col = (s.MajorAxisLength/2)*cos(theta);
row = (s.MinorAxisLength/2)*sin(theta);
M = makehgtform('translate',[s.Centroid, 0],'zrotate',deg2rad(-1*s.Orientation));
D = M*[col;row;zeros(1,numel(row));ones(1,numel(row))];

% Visualize the result
figure
imshow(BW)
hold on
plot(D(1,:),D(2,:),'r','LineWidth',2)

end 

figure
for i = 1:1000

rotate_filler = imrotate(read(v,i), delta_angle(i), 'crop'); 
rotated_image(:,:,:,i) = rotate_filler; 
imshowpair(read(v,i), rotated_image(:,:,:,i), 'montage')
pause(0.001)
end 

Any suggestions are appreciated. Thanks!

标签: matlabimage-processingcomputer-visionellipse

解决方案


推荐阅读