4/16/2022

opencv, cv2, rotate image & point

 

refer to code.

sample point is 100,100

firstly, I rotated image as 90 degree and point.

And compare origin image & pt where rotated point is placed in right position.

..

import numpy as np
import cv2
from matplotlib import pyplot as plt

def rotate_image(angle, width, height):
image_center = (width/2, height/2)
rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1.)
abs_cos = abs(rotation_mat[0,0])
abs_sin = abs(rotation_mat[0,1])
bound_w = int(height * abs_sin + width * abs_cos)
bound_h = int(height * abs_cos + width * abs_sin)
rotation_mat[0, 2] += bound_w/2 - image_center[0]
rotation_mat[1, 2] += bound_h/2 - image_center[1]
return rotation_mat, (bound_w, bound_h)

#open image
image = cv2.imread('img.png')
sample_pt =(100,100)

#get rotate mat, bound
height, width = image.shape[:2]
rotation_mat, (bound_w, bound_h) = rotate_image(90, width, height)

#rotate image
image_90 = cv2.warpAffine(image, rotation_mat, (bound_w, bound_h))
#rotate pt
sample = np.array([100, 100, 1])
sample_90 = np.matmul(rotation_mat, sample)


#origin image & pt
cv2.circle(image, sample_pt, 1, (0, 0, 255), 2, cv2.LINE_AA)

#rotated image & pt
cv2.circle(image_90, (int(sample_90[0]), int(sample_90[1])), 1, (0, 0, 255), 2, cv2.LINE_AA)


image = image[:,:,::-1]
plt.figure(figsize=(10, 10), dpi=100)
plt.imshow(image)

image_90 = image_90[:,:,::-1]
plt.figure(figsize=(10, 10), dpi=100)
plt.imshow(image_90)

..


origin image with point

90 rotated image and point

Thank you.

www.marearts.com


No comments:

Post a Comment