|
| 1 | +from matplotlib import pyplot as plt |
| 2 | +import numpy as np |
| 3 | +import cv2 |
| 4 | + |
| 5 | + |
| 6 | +def get_rotation( |
| 7 | + img: np.array, pt1: np.float32, pt2: np.float32, rows: int, cols: int |
| 8 | +) -> np.array: |
| 9 | + """ |
| 10 | + Get image rotation |
| 11 | + :param img: np.array |
| 12 | + :param pt1: 3x2 list |
| 13 | + :param pt2: 3x2 list |
| 14 | + :param rows: columns image shape |
| 15 | + :param cols: rows image shape |
| 16 | + :return: np.array |
| 17 | + """ |
| 18 | + matrix = cv2.getAffineTransform(pt1, pt2) |
| 19 | + return cv2.warpAffine(img, matrix, (rows, cols)) |
| 20 | + |
| 21 | + |
| 22 | +if __name__ == "__main__": |
| 23 | + # read original image |
| 24 | + image = cv2.imread("lena.jpg") |
| 25 | + # turn image in gray scale value |
| 26 | + gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) |
| 27 | + # get image shape |
| 28 | + img_rows, img_cols = gray_img.shape |
| 29 | + |
| 30 | + # set different points to rotate image |
| 31 | + pts1 = np.float32([[50, 50], [200, 50], [50, 200]]) |
| 32 | + pts2 = np.float32([[10, 100], [200, 50], [100, 250]]) |
| 33 | + pts3 = np.float32([[50, 50], [150, 50], [120, 200]]) |
| 34 | + pts4 = np.float32([[10, 100], [80, 50], [180, 250]]) |
| 35 | + |
| 36 | + # add all rotated images in a list |
| 37 | + images = [ |
| 38 | + gray_img, |
| 39 | + get_rotation(gray_img, pts1, pts2, img_rows, img_cols), |
| 40 | + get_rotation(gray_img, pts2, pts3, img_rows, img_cols), |
| 41 | + get_rotation(gray_img, pts2, pts4, img_rows, img_cols), |
| 42 | + ] |
| 43 | + |
| 44 | + # plot different image rotations |
| 45 | + fig = plt.figure(1) |
| 46 | + titles = ["Original", "Rotation 1", "Rotation 2", "Rotation 3"] |
| 47 | + for i, image in enumerate(images): |
| 48 | + plt.subplot(2, 2, i + 1), plt.imshow(image, "gray") |
| 49 | + plt.title(titles[i]) |
| 50 | + plt.axis("off") |
| 51 | + plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) |
| 52 | + plt.show() |
0 commit comments