1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| import cv2 as cv import numpy as np
def show_Img(name, img): cv.imshow(name, img) cv.waitKey(0) cv.destroyAllWindows()
def front_rotate_image(image, angle): radians = np.deg2rad(angle)
cos_theta = np.around(np.cos(radians), decimals=4) sin_theta = np.around(np.sin(radians), decimals=4) rotation_matrix = np.array([[cos_theta, sin_theta, 0], [-sin_theta, cos_theta, 0], [0, 0, 1]])
height, width = image.shape[:2] new_width = int(np.round(width * abs(cos_theta) + height * abs(sin_theta))) new_height = int(np.round(height * abs(cos_theta) + width * abs(sin_theta))) print(new_width, new_height) rotated_image = np.zeros((new_height, new_width, 3), dtype=np.uint8) center_x = width / 2 center_y = height / 2 x_step = (new_width - width) * (center_x / width) + (center_x - 1) y_step = (new_height - height) * (center_y / height) + (center_y - 1) translation_matrix1 = np.array([[1, 0, 0], [0, 1, 0], [-center_x, -center_y, 1]]) translation_matrix2 = np.array([[1, 0, 0], [0, 1, 0], [x_step, y_step, 1]]) for y in range(height): for x in range(width): translated_x, translated_y, _ = np.dot([x, y, 1], translation_matrix1)
rotated_x, rotated_y, _ = np.dot([translated_x, translated_y, 1], rotation_matrix)
rotated_x, rotated_y, _ = np.dot([rotated_x, rotated_y, 1], translation_matrix2) if 0 <= rotated_x < new_width and 0 <= rotated_y < new_height: rotated_image[int(np.round(rotated_y)), int(np.round(rotated_x))] = image[y, x] return rotated_image
img = cv.imread("images/kunkun.jpg") theta = 45 h, w, c = img.shape img = cv.resize(img, (w // 2, h // 2)) img_rotated = front_rotate_image(img, theta) show_Img("img_rotated", img_rotated)
|