How to calculate the angle rotated of the cut out image?


I have a 200*200 square image, now I draw a circle of 100 diameter with the center of this image as the center, cut this image into two parts along the circle, rotate this circle image by a certain angle and save it as circle.jpg and save the rest as background.jpg. Now what algorithm do I need to calculate How much angle do I need to rotate circle.jpg in order to combine it with background.jpg to form the original image? Is it possible to do this using opencv?





Asked By: hoozecn



I don’t know if there’s a algorithm ready to use. But it should be fun inventing your own.

Let your algorithm walk on the edge of pixels:

Edge walk of image 1

Then let it walk the same way on the other image:

Edge walk on image 2

The length (number of pixels) should be the same, so you can put them on top of each other and calculate the difference in color. Next, shift pixels to the right until you get the least difference in pixel color.

Pixel shift

Answered By: Thomas Weller

Here are my code which solve the above problem perfectly. Thanks to Thomas Weller again.

import cv2
import numpy as np
import os

ARRAY_LENGTH = 785 # resolution

def get_pixels(img, radius, offset):
    center = img.shape[0] // 2, img.shape[1] // 2
    angles = np.linspace(0, 2 * np.pi, ARRAY_LENGTH, endpoint=False)
    x = center[0] + radius * np.cos(angles + offset)
    y = center[1] + radius * np.sin(angles + offset)
    pixels = img[x.astype(int), y.astype(int)]
    return pixels

def match(bg_path, cut_path):
    bg = cv2.imread(bg_path, cv2.IMREAD_GRAYSCALE)
    cut = cv2.imread(cut_path, cv2.IMREAD_GRAYSCALE)
    radius = cut.shape[0] // 2
    pixels_bg = get_pixels(bg, radius + 2, 0)
    pixels_cut = get_pixels(cut, radius - 2, 0)    

    corr = np.fft.ifft(np.fft.fft(pixels_bg) * np.conj(np.fft.fft(pixels_cut)))
    shift = ARRAY_LENGTH - np.argmax(np.abs(corr))

    angle = -((shift - ARRAY_LENGTH) / ARRAY_LENGTH) * 360
    return angle
Answered By: hoozecn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.