Image Rotation based of the location of four circles in the image

2 次查看(过去 30 天)
I have a collection of colour matrices which are sometimes rotated (see attached image).
I have written code that detects the circles in the corners and returns the corrdinates.
function [centers] = find_circle_coordinates(img)
binary_img = ~imbinarize(rgb2gray(img));
[centers, radii] = imfindcircles(binary_img, [20 30]);
disp(centers);
end
I now want to rotated the images that do not have the circles in the corners, so that the rotated image has the circles in the corner. But I am somewhat stuck on finding a reliable way of achieving it. Any help on the rotation is much appreciated.

采纳的回答

chicken vector
chicken vector 2023-4-19
编辑:chicken vector 2023-4-22
Assuming that you you have x and y coordinates of the centers:
% Get centers' coordinates:
xCenters = centers(:,1);
yCenters = centers(:,2);
% Find upper circles coordinates:
[ySorted, idx] = sort(yCenters,'descend');
xUpper = xCenters(idx([1,2]));
yUpper = ySorted([1,2]);
% Get 2nd circle relative components with respect to 1st:
xRelative = xUpper(2) - xUpper(1);
yRelative = yUpper(2) - yUpper(1);
% Compute the angle:
angle = atan2d(-yRelative,xRelative);
% Rotate the image:
rotatedImg = imrotate(img, angle);
I couldn't test this so some little fixes may be required.
  2 个评论
DGM
DGM 2023-4-19
编辑:DGM 2023-4-19
The cropping can be done easier if we keep the mask.
inpict = imread('swchartrot.png');
% binarize and find centers
mask = ~imbinarize(rgb2gray(inpict)); % this will be needed later
centers = imfindcircles(mask, [20 30]);
% Get centers' coordinates:
xCenters = centers(:,1);
yCenters = centers(:,2);
% Find upper circles coordinates:
[ySorted, idx] = sort(yCenters);
xUpper = xCenters(idx([1,2]));
yUpper = ySorted([1,2]);
% Get 2nd circle relative components with respect to 1st:
xRelative = xUpper(2) - xUpper(1);
yRelative = yUpper(2) - yUpper(1);
% Compute the angle:
angle = -atan2d(-yRelative,xRelative);
% Rotate the image and the mask
rotatedImg = imrotate(inpict,angle);
rotatedmask = imrotate(mask,angle);
% use the rotated mask to find the extents
% use the extents to crop the image
[~,rows,cols] = crop2box(rotatedmask);
rotatedImg = rotatedImg(rows,cols,:);
imshow(rotatedImg)
Luca
Luca 2023-4-19
You are absolute legneds, thank you very much! That worked like a charm!

请先登录,再进行评论。

更多回答(0 个)

产品


版本

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by