Rich's Wordpress

又一个WordPress站点

OpenCV 5: Transformations

Read in images and import both numpy and cv2:

import numpy as np
import cv2 as cv

img = cv.imread('Image/Cat3.jpg')

cv.imshow('Cat', img)

Translation

#Translation
def translate(img, x,y):
    transMat = np.float32([[1,0,x],[0,1,y]])
    dimentions = (img.shape[1], img.shape[0])
    return cv.warpAffine(img, transMat, dimentions)

# -x ---> Left
# x ---> Right
# -y ---> Up
# y ---> Down

translated = translate(img, 100, 100)
cv.imshow('Translated', translated)

Rotation

# Rotation
def rotate(img, angle, rotPoint=None):
    (height,width) = img.shape[:2]

    if rotPoint is None:
        rotPoint = (width//2, height//2)

    rotMat = cv.getRotationMatrix2D(rotPoint, angle, 1.0)
    dimentions = (width, height)
    return cv.warpAffine(img,  rotMat, dimentions)

rotated = rotate(img, 45)
cv.imshow('Rotated', rotated)

Flipping

# Flipping
flip = cv.flip(img, flipCode=-1)
cv.imshow('Flipped', flip)

# 0 ---> flip vertically
# 1 ---> flip horizontally
# -1 ---> flip both vertically and horizontally

cv.waitKey(0)
OpenCV 5: Transformations
Scroll to top