Xiao Qiang learns python+opencv -1.4.1 translation, rotation, scaling, flip-practice __python

Source: Internet
Author: User
Tags translate function vars python script
Xiao Qiang learns python+opencv -1.4.1 translation, rotation, scaling, flip-practice

Xiao Qiang learns the Pythonopencv of 141 translation rotation and scaling flip summary of translation rotation Zoom summary

Below, we translate, rotate, scale, and flip the theme pictures for this section.
translation

First, we create the Python script translation.py and add the following code:

# import library Import
NumPy as NP
import argparse
import cv2

# define translation translate function
def translate (image, X, y): 
  # definition translation Matrix
    M = Np.float32 ([[1, 0, X], [0, 1, y]])
    shifted = Cv2.warpaffine (image, M, (image.shape[1), image.shape[ 0])

    # returns the converted image return
    shifted


# construction parameter parser
AP = argparse. Argumentparser ()
ap.add_argument ("I", "--image", Required=true, help= "Path to the image")
args = VARs ( Ap.parse_args ())

# Load image and show image
= Cv2.imread (args["image")
cv2.imshow ("Original", image)

# The original artwork is done up, down, left, right translation operation
shifted = translate (image, 0,)
cv2.imshow ("shifted down", shifted)
shifted = Translate (image, 0, -100)
cv2.imshow ("shifted up", shifted)
shifted = translate (image, 0)
Cv2.imshow ("shifted right", shifted)
shifted = translate (image, -50, 0)
cv2.imshow ("shifted left", shifted) C26/>cv2.waitkey (0)

Execute script

Python translation.py--image trip.jpg

The display is as follows:

Rotate

Create the Python script rotation.py and enter the following:

# import library import NumPy as NP import argparse import Cv2 # define rotation rotate function def rotate (image, Angle, Center=none, scale=1.0):

    # Get Image Dimensions (h, W) = Image.shape[:2] # If no rotation center is specified, the image center is set to the rotation center if centre is None:center = (W/2, H/2) # perform rotation M = cv2.getrotationmatrix2d (center, angle, scale) rotated = Cv2.warpaffine (image, M, (W, h)) # return Rotated image return rotated # construction parameter Parser AP = Argparse.  Argumentparser () ap.add_argument ("I", "--image", Required=true, help= "Path to the image") args = VARs (Ap.parse_args ()) # Load image and Show image = Cv2.imread (args["image") cv2.imshow ("Original", image) # Rotate the original to different angles rotated = rotate (image,) Cv2.imsh OW ("Rotated by Degrees", rotated) rotated = rotate (image, -45) cv2.imshow ("Rotated by-45 Degrees", rotated) rotated = Rotate (image,) cv2.imshow ("Rotated by Degrees", rotated) rotated = rotate (image, -90) cv2.imshow ("Rotated by-90 Deg Rees ", rotated) rotated = rotate (image, 180) cv2.imshow (" Rotated by 180 Degrees ", rotated) cv2.Waitkey (0) 

Execute script

Python rotation.py--image trip.jpg

Scaling

Here we want to take a small size, but more clear image. Used to compare the weight between zooming and narrowing to see if there is a loss.

Create the Python script resize.py and enter the following:

# import Library Imports Argparse Import Cv2 # define scaling resize function def resize (image, Width=none, Height=none, Inter=cv2. Inter_area): # Initialize scaling and get image size Dim = None (H, W) = Image.shape[:2] # If both width and height are 0, return the original if width is Non E and None:return image # width is 0 if width is None: # The scaling ratio is calculated according to height r = HEIGHT/FL
        Oat (h) Dim = (Int (w * r), height) # if height is 0 else: # Calculate scaling by width R = width/float (W) Dim = (Width, int (h * r)) # Zoom Image resized = cv2.resize (image, Dim, Interpolation=inter) # Returns the scaled image Retu RN Resized # construction parameter parser AP = Argparse.  Argumentparser () ap.add_argument ("I", "--image", Required=true, help= "Path to the image") args = VARs (Ap.parse_args ()) # Load parameters and display (because the original is larger, we first reduce the original image) (Cv2.imread (args["image") cv2.imshow ("Original", image) # Create an array of interpolation methods methods = [(CV 2.inter_nearest ", Cv2. Inter_nearest), ("Cv2. Inter_linear ", Cv2. Inter_linear), ("Cv2. Inter_area ", Cv2. Inter_area), ("CV2. Inter_cubic ", Cv2. Inter_cubic), ("Cv2. Inter_lanczos4 ", Cv2. INTER_LANCZOS4)] # Loop executes the methods for the array of interpolation methods for (name, methods) in methods: # magnify 3 times times resized = resize (image, Width=image.sha PE[1] * 3, Inter=method) cv2.imshow ("ZoomIn method: {}". Format (name), resized) # shrink twice times resized = resize (image, WIDTH=IMAGE.SHAPE[1]/2, Inter=method) cv2.imshow ("Zoomout method: {}". Format (name), resized) Cv2.waitkey (0)

Execute script

Python resize.py--image motor.jpg

Use CV2. Inter_nearest interpolation method, zoom out and enlarge the following diagram respectively:

Use CV2. Inter_linear interpolation method, zoom out and enlarge the following diagram respectively:

Use CV2. Inter_area interpolation method, zoom out and enlarge the following diagram respectively:

Use CV2. Inter_cubic interpolation method, zoom out and enlarge the following diagram respectively:

Use CV2. Inter_lanczos4 interpolation method, zoom out and enlarge the following diagram respectively:

Summary in general, Cv2. The Inter_nearest speed is the fastest, but the quality is not high. If the resources are very limited, you can consider using them. Otherwise, this is not selected, especially if you are sampling (increasing) the size of the image. You can consider using CV2 when increasing the size of the image (up sample). Inter_linear and Cv2. Inter_cubic two kinds of interpolation methods. Cv2. Inter_linear method than Cv2. The Inter_cubic method is slightly faster, but whichever effect is good. When the size of the image (sampled) is reduced, the OpenCV document suggests using CV2. Inter_area. PS. I feel in fact, the sampling methods are similar, take the fastest (cv2.inter_nearest) is good. Flip

Create the Python script flip.py and enter the following:

# import Library Import
argparse
import cv2

# construct parameter parser
AP = argparse. Argumentparser ()
ap.add_argument ("I", "--image", required=true, help = ' Path to ' image ')
args = VARs ( Ap.parse_args ())

# Load image and show image
= Cv2.imread (args["image")
cv2.imshow ("Original", image)

# Flip Image horizontally
flipped = Cv2.flip (image, 1)
cv2.imshow ("flipped horizontally", flipped)

# portrait Flip image
flipped = Cv2.flip (image, 0)
cv2.imshow ("flipped vertically", flipped)

# at the same time flip the image in both landscape and portrait
flipped = Cv2.flip (image, -1)
cv2.imshow ("Flipped horizontally & vertically", flipped)
Cv2.waitkey (0)

Execute script python flip.py--image motor.jpg
Summing up This section we use functions, which are defined as:
A) def translate (image, X, y): Use def definition, with function name and formal parameter, then colon
b) The function body indents a tab
c) If there are nested statements, indent the scaling in order to keep the aspect ratio in mind. Scaling, the next sampling interpolation algorithm is more relaxed choice, you can choose Cv2. Inter_area. When sampling, choose according to the situation. In general, select Cv2. Inter_linear. Select Cv2 when resources are tense. Inter_nearest.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.