MATLAB: Detect orientation of screw image

image processingmachine vision

The screw as shown in the image is not completely horizontal. I would like to detect the orientation of screw and form a new image that can make sure that the screw is completely horizontal. Is there a way to do that?
20.bmp

Best Answer

Using this script lets you know which angle to rotate. Then use this information to rotate the image and check the orientation again:
%% read image and find points that should lie on a straight line
img = rgb2gray(imread('20.bmp'));
res = detectHarrisFeatures(img,'MinQuality', 0.1, 'ROI', [1 386 762 20]);
% Extract coordinates of the points

x_vals = double(res.Location(:,1));
y_vals = double(res.Location(:,2));
% find slope and offset of the line formed by the points and use arctan to

% estimate the angle the srew is different from horizontal orientation

slope_and_offset = polyfit(x_vals, y_vals,1);
angle = atand(slope_and_offset(1));
fprintf('\nThe screw is oriented %.5f degree to the horizontal.\n', angle)
%% rotate the image
img_rot = imrotate(img,angle);
% search points again on rotated image
res_new = detectHarrisFeatures(img_rot,'MinQuality', 0.1, 'ROI', [1 395 762 10]);
% Extract coordinates of the points
x_vals_rot = double(res_new.Location(:,1));
y_vals_rot = double(res_new.Location(:,2));
% find slope and offset of the line formed by the points and use arctan to
% estimate the angle the srew is different from horizontal orientation
slope_and_offset_rot = polyfit(x_vals_rot, y_vals_rot,1);
angle_rot = atand(slope_and_offset_rot(1));
fprintf('\nThe screw is oriented %.5f degree to the horizontal after rotation.\n\n', angle_rot)
%% plot results
subplot(1,2,1)
hold on
title('Original Image')
imshow(img)
scatter(res.Location(:,1),res.Location(:,2),'or')
hold off
subplot(1,2,2)
hold on
title('Corrected Image')
imshow(img_rot)
scatter(res_new.Location(:,1),res_new.Location(:,2),'ob')
hold off
The keypoint is to define the ROI to the algorithm, so that you only detect points that are valid to reach high presicion.
Related Question