MATLAB: How can i make automatic rotation using PCA to set the galaxies oriantation to be horizontal

cropgalaxies rotationimageorientationrotaterotate image

Please help me >>
Annotation 2020-02-07 203925.png
How can i make automatic rotation using PCA to set the galaxies oriantation to be horizontal and cropping the image?
Knowing that the galaxies in the original images have different directions
I searched a lot and could not find any code

Best Answer

This approach uses the Orientation property of the regionprops() function to get the angle between the x-axis and the major axis of the galaxy ellipse. It uses the orientation angle to rotate the image so the galaxy is horizontal.
There are several plots produced to show the steps of this process. They can be commented out in your final function/script. The image file I'm analyzing in this script is attached.
See the inline comments for detail.
% Identify file
file = 'PGC0001862.png'; % full path is better; see fullfile()
% Binarize the image
I = imread(file);
BW = imbinarize(rgb2gray(I));
% Filter out noise by isolating the object with the largest perimeter
BWfilter = bwpropfilt(BW,'perimeter',1);
% Show orginal and binary images for a sanity check
clf()
imshowpair(I,BWfilter,'montage')
% Get the orientation of the main object
stats = regionprops(BWfilter,'Orientation'); % 56.981 for this image
% rotate the image
IRot = imrotate(I, -stats.Orientation);
% Show image before/after rotation for sanity check
clf()
subplot(1,2,1)
imshow(I)
subplot(1,2,2)
imshow(IRot)
linkaxes(); % to match aspect ratios


% Crop the rotated image based on the limits of the binary image
BWfilterRot = imrotate(BWfilter, -stats.Orientation);
[rows, cols] = find(BWfilterRot);
BWcrop = BWfilterRot(min(rows):max(rows), min(cols):max(cols)); % only needed for sanity-check
Icrop = IRot(min(rows):max(rows), min(cols):max(cols),:);
% Show the cropped RGB and BW images
clf()
subplot(1,2,1)
imshow(Icrop)
subplot(1,2,2)
imshow(BWcrop)
linkaxes(); % to match aspect ratios
% Show original and final image
clf()
subplot(1,2,1)
imshow(I)
subplot(1,2,2)
imshow(Icrop)
linkaxes(); % to match aspect ratios