current position：Home>Understand the principle of affine transformation and python implementation code
Understand the principle of affine transformation and python implementation code
20220202 04:21:49 【Eason_ Sun】
Affine transformation of images is often used in data enhancement of computer vision , By affine transformation, we mean rigid body transformation , That is, two parallel lines are still parallel after affine transformation , Perspective transformation is not rigid body transformation , Beyond the scope of this article . Usually flip 、 translation 、 rotate 、 Shrinkage 、 Any combination of staggered transformation belongs to affine transformation . Affine transformation can be expressed by the following formula ：
Where the rotation angle acts on a b d e,scale Act on a e, Shear transformation acts on b d, Translation acts on c f, As shown in the figure below ：
1. cv2.getRotationMatrix2D Detailed explanation
opencv Of cv2.getRotationMatrix2D Function can obtain the rotation transformation matrix . Enter the coordinates of the center point (centerX,centerY), Rotation Angle θ And scaling 1, give M Transformation matrix ：
How is this affine transformation matrix derived ？ Affine transformation matrix adopts polar coordinate system, which is easy to reason . Let's first rotate a point based on the origin , Here's the picture , take V1 The dot rotates counterclockwise θ Angle to V2 spot , Let's first assume that the scale is 1.
V1 The angle between the point and the origin line and the horizontal line a,V2 The angle between the point and the origin line and the horizontal line b=a+θ. Calculate the rotation transformation matrix ： remember V1=(x1, y1), V2=(x2, y2)
But usually we rotate based on the center point , If you need to go around any point （tx,ty） rotate , We can
1. First translate the rotation point to the origin
2. Then perform the above rotation operation
3. Press 1 The reverse operation of translation goes back
You can get the transformation matrix of rotating points around any point ：
2. warpAffine operation
2.1 obtain M Affine transformation of matrix
Get the transformation matrix M, Each point of the image is M The rotated image can be obtained by transformation , This step can be done by opencv Of warpAffine obtain . But through the above operation , After rotation, the large image will lose information , As shown in the figure below ：
2.2 Expand the canvas
With the same canvas size , There will be some images beyond , Display incomplete , So we need to expand the canvas to ： The new height is composed of two blue lines in the picture :new_H=int(w∗abs(sin(radias(angle)))+h∗abs(cos(radias(angle))))
The new width consists of two red lines in the picture : new_W=int(h∗fabs(sin(radians(angle)))+w∗fabs(cos(radians(angle))))
The new canvas expansion is based on the expansion of the upper left corner of the original image . therefore , In the transformation matrix M On , We can adjust the translation parameters ：
M[0,2]+=(new_W−w)/2
M[1,2]+=(new_H−h)/2
3. Image affine transformation code
Talk is cheap, show me the code. Go straight to the code ：
def affine_transform(image, angle, scale=1.0):
h, w = image.shape[:2]
center_x, center_y = width // 2, height // 2
M = cv2.getRotationMatrix2D((center_x, center_y), angle, scale)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
new_h = int(h * cos + w * sin)
new_w = int(h * sin + w * cos)
M[0, 2] += (new_w − w) / 2
M[0, 1] += (new_h − h) / 2
new_image = cv2.warpAffine(image, M, (new_w, new_h))
return new_image
Copy code
4. Single point affine transformation code
When we perform affine transformation data enhancement , The coordinate points of the target need to be transformed accordingly .
def affine_points(points, center_x, center_y, h, w, scale=1.0):
points = np.array(points, dtype=np.float32)
points = np.hstack((points, np.ones((points.shape[0], 1))))
M = cv2.getRotationMatrix2D((center_x, center_y), angle, scale)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
new_h = int(h * cos + w * sin)
new_w = int(h * sin + w * cos)
M[0, 2] += (new_w − w) / 2
M[0, 1] += (new_h − h) / 2
new_points = np.dot(M, points.T).T
return new_points
Copy code
copyright notice
author[Eason_ Sun],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020421465974.html
The sidebar is recommended
 1313. Unzip the coding list (Java / C / C + + / Python / go / trust)
 Python Office  Python edit word
 Collect it quickly so that you can use the 30 Python tips for taking off
 Strange Python strip
 Python crawler actual combat, pyecharts module, python realizes China Metro data visualization
 DOM breakpoint of Python crawler reverse
 Django admin custom field stores links in the database after uploading files to the cloud
 Who has powder? Just climb who! If he has too much powder, climb him! Python multithreaded collection of 260000 + fan data
 Python Matplotlib drawing streamline diagram
 The game comprehensively "invades" life: Python releases the "cool run +" plan!
guess what you like

Python crawler notes: use proxy to prevent local IP from being blocked

Python batch PPT to picture, PDF to picture, word to picture script

Advanced face detection: use Dlib, opencv and python to detect face markers

"Python 3 web crawler development practice (Second Edition)" is finally here!!!!

Python and Bloom filters

Python  singleton pattern of software design pattern

Lazy listening network, audio novel category data collection, multithreaded fast mining cases, 23 of 120 Python crawlers

Troubleshooting ideas and summary of Django connecting redis cluster

Python interface automation test framework (tools)  interface test tool requests

Implementation of Morse cipher translator using Python program
Random recommended
 [Python] numpy notes
 24 useful Python tips
 Pandas table beauty skills
 Python tiktok character video, CV2 module, Python implementation
 I used Python to climb my wechat friends. They are like this
 20000 words take you into the python crawler requests library, the most complete in history!!
 Answer 2: why can you delete the table but not update the data with the same Python code
 [pandas learning notes 02]  advanced usage of data processing
 How to implement association rule algorithm? Python code and powerbi visualization are explained to you in detail (Part 2  actual combat)
 Python adds list element append() method, extend() method and insert() method [details]
 python wsgi
 Introduction to Python gunicorn
 Python dictionary query key value pair methods and examples
 Opencv Python reads video, processes and saves it frame by frame
 Python learning process and bug
 Imitate the up master and realize a live broadcast room controlled by barrage with Python!
 Essence! Configuration skills of 12 pandas
 [Python automated operation and maintenance road] path inventory
 Daily automatic health punch in (Python + Tencent cloud server)
 [Python] variables, comments, basic data types
 Spring boot calls Python interface
 Using Python to make a key recorder
 Python combat case, pyGame module, python implementation routine confession artifact vs no routine confession artifact
 Python series tutorial 132  why use indentation syntax
 10 minutes to learn how to play excel easily with Python
 Python develops a color dynamic twodimensional code generator in one hour, and uses the virtual environment to package and release the EXE program.
 Elimination of grammar left recursion in Python
 Python testing  the patches in Python
 Python image processing, CV2 module, OpenCV to achieve target tracking
 How to send alarm notification to nail in Python?
 Introduction to pandas operation
 Mail sending, SMTP and exchange sending in Python 3
 Show your hand and use Python to analyze house prices
 The strongest Python visualization artifact, none of them
 8 practical Python skills that are easy to use and don't have to suffer a loss for half a year
 Tips: teach you to generate 30 cool dynamic interactive charts with one click of pandas
 I use one line of Python code to dynamically load dependencies
 Blow up this pandas GUI artifact and automatically turn the code!
 Getting started exploring and analyzing data using Python
 Python image processing, CV2 module, OpenCV to achieve template matching