Rotate and scale the image before cropping [python] [OpenCV]

Overview

I wrote the code to rotate, scale, and crop the image all at once.

background

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.

code

# -*- 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

Rotate and scale the image before cropping [python] [OpenCV]
[Python] Accessing and cropping image pixels using OpenCV (for beginners)
I tried "smoothing" the image with Python + OpenCV
I tried "differentiating" the image with Python + OpenCV
I tried "binarizing" the image with Python + OpenCV
[Python + OpenCV] Whiten the transparent part of the image
Python OpenCV tried to display the image in text.
Image editing with python OpenCV
I tried "gamma correction" of the image with Python + OpenCV
Remove double-byte spaces before and after the character string (python)
Python application: Data cleansing # 3: Use of OpenCV and preprocessing of image data
Environment construction of python and opencv
Shining life with Python and OpenCV
Python: Rotate and mask seaborn heatmaps
Automatic image interpolation with OpenCV and Python (Fast Marching Method, Navier-Stokes)
[Python] Using OpenCV with Python (Image Filtering)
Neural network with OpenCV 3 and Python 3
[Python] Using OpenCV with Python (Image transformation)
Quickly install OpenCV 2.4 (+ python) on OS X and try the sample
[Image processing] Edge detection using Python and OpenCV makes Poo naked!
I just erased the object using image repair (inpaint) (OpenCV: Python)
Find image similarity with Python + OpenCV
Try blurring the image with opencv2
Introduction to image analysis opencv python
Judge the extension and download the image
How to crop the lower right part of the image with Python OpenCV
[Python] Specify the image area and apply OCR (monitor automatic recording device)
Send and receive image data as JSON over the network with Python
Read the graph image with OpenCV and get the coordinates of the final point of the graph
Get and estimate the shape of the head using Dlib and OpenCV with python
[python] Send the image captured from the webcam to the server and save it
Build Python3 and OpenCV environment on Ubuntu 18.04
Line graphs and scale lines in python
Capturing images with Pupil, python and OpenCV
Image processing with Python & OpenCV [Tone Curve]
Image acquisition from camera with Python + OpenCV
Academia Potter and the Mysterious Python Pass
Easy introduction of python3 series and OpenCV3
Add lines and text on the image
Light image processing with Python x OpenCV
Python open and io.open are the same
GAE --With Python, rotate the image based on the rotation information of EXIF and upload it to Cloud Storage.
Find the position in the original image from the coordinates after affine transformation (Python + OpenCV)
I want to crop the image along the contour instead of the rectangle [python OpenCV]
Hello World and face detection with OpenCV 4.3 + Python
Head orientation estimation using Python and OpenCV + dlib
[Python] What are the two underscore (underscore) functions before?
Image characters and post to slack (python slackbot)
Summary of the differences between PHP and Python
[Python] Get / edit the scale label of the figure
I tried object detection using Python and OpenCV
The answer of "1/2" is different between python2 and 3
[Xonsh] The Python shell is sharp and god
What is wheezy in the Docker Python image?
GUI image cropping tool made with Python + Tkinter
ffmpeg-Build a python environment and split the video
Specifying the range of ruby and python arrays
How to crop an image with Python + OpenCV
Install OpenCV 4.0 and Python 3.7 on Windows 10 with Anaconda
About the difference between "==" and "is" in python
Compare the speed of Python append and map