I wrote the code to rotate, scale, and crop the image all at once.
I wrote it to make a framed movie efficiently. When making a frame-by-frame movie, you may want to shoot it wider for the time being and then trim it later. If you hit a tripod during shooting, the angle and size may deviate slightly even if you try to reproduce the previous angle of view. In order to perform trimming while correcting such deviations, I wrote a code to rotate and scale the image before trimming.
# -*- coding: utf-8 -*-
import sys
import cv2
import os
import numpy as np
ORIGINAL_IMG_DIR = "./"
TRIMMED_IMG_DIR = "./cuttest/"
if __name__ == '__main__':
#Upper left coordinate of the area to be trimmed
startX = 963
startY = 736
#The size of the area to be trimmed
width = 2270
height = 1450
#The angle you want to rotate (positive value is counterclockwise)
angle = -0.1
#Expansion ratio
scale = 1.0
#Get the file name in the target directory
files = os.listdir(ORIGINAL_IMG_DIR)
#Extract the file with the image extension you want to process
files = [name for name in files if name.split(".")[-1] in ["png","jpg"]]
for val in files:
src_mat = cv2.imread(ORIGINAL_IMG_DIR+val,1)
#Get image size(side,Vertical)
size = tuple([src_mat.shape[1], src_mat.shape[0]])
#dst image ready
dst_mat = np.zeros((size[1], size[0], 4), np.uint8)
#Center position of the image(x, y)
center = tuple([int(size[0]/2), int(size[1]/2)])
#Calculation of rotation transformation matrix
rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)
#Affine transformation
img_dst = cv2.warpAffine(src_mat, rotation_matrix, size, dst_mat, flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_TRANSPARENT)
dst = img_dst[startY:height+startY, startX:width+startX]
cv2.imwrite(TRIMMED_IMG_DIR+val, dst)
print('cut '+val)
In the above, the image is rotated and scaled first, and the upper left coordinates of the trimming area are specified for the image after this rotation and scaling. Therefore, please note that the trimming position may deviate from the assumption when extreme rotation or scaling is performed. If you want to align the upper left image of the trimming area with the position in the original image, apply a rotation matrix to startX and startY (I have not tried it, but I think it can be done by using numpy etc.).
Reference site Resize / Rotate / Crop
Recommended Posts