Make writing a habit together! This is the 14th day of my participation in the “Gold Digging Day New Plan · April More Text Challenge”. Click here for more details.

0. Preparation

Right-click the new project, select Python File, create a new Python File, and import the cv2 library at the beginning with import cv2, import numpy and rename it to NP.

import cv2
import numpy as np
Copy the code

We also know that in OpenCV, the axes are x to the right, y to the down, and the origin of the coordinates is in the upper left corner. For example, the image below is 640 pixels long and 480 pixels wide. OK, let’s start this section.

1. Scene Description

Given any image, slice out the area you want and display it at the specified size. And the segmented image is parallel to the displayed window in linear space. For example: I want to get K below. In the original picture, K is lying on its side, but after splitting it, it should stand upright. So how do you achieve this effect?To achieve this effect, we need to obtain some important information, such as the four coordinates of the card K in the image above. We can use the drawing tool to open the picture, and then place the mouse on the four points of the segmentation area to get the coordinate information.

Since the width and height axes of the drawing image are the same as those of OpenCV, when I place the mouse over the upper left corner of K, the lower left corner of the drawing is displayed (734Pixels,185Pixel), that's the coordinates of this point in the upper left corner.Copy the code

2. Perspective transformation

The above requirement seems difficult to implement, but with the CV2 library, it is actually only 9 lines of code.

  1. First, we set the width of the output image to 250 and the height to 350.
  2. And then read our image, which is the image above.
  3. Define the four point coordinates of the target area, which are: upper left, upper right, lower left and lower right. We got that in the previous step.
  4. Pst2 is the position of the output picture in the picture box.
  5. Using library functionswarpPerspectiveAchieve perspective transformation, interested in understanding the principle.
  6. Finally, two images are printed and displayed.
width,height=250.350
img=cv2.imread("Resources/poker.jpg")
pst1=np.float32([[734.185], [1101.266], [621.679], [1030.789]])
pst2=np.float32([[0.0],[width,0], [0,height],[width,height]])
matrix=cv2.getPerspectiveTransform(pst1,pst2)
imgOutput=cv2.warpPerspective(img,matrix,(width,height))

cv2.imshow("Image",img)
cv2.imshow("Output",imgOutput)
cv2.waitKey(0)
Copy the code

Let’s take a look at the effect. The image on the left is our perspective transformation, and the image on the right is the original image:

Section 5, which is actually quite interesting, has many applications in life. It is better to see it a thousand times than to see it once. Go and knock it again