본문 바로가기
OpenCV

[OpenCV] transformations.py

by Lizardee 2024. 4. 10.
Image Transformations

import cv2 as cv
import numpy as np

# Reading an image
img = cv.imread('Photos/boston.jpg')
cv.imshow('Boston', img)


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

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

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


# 2. 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)
    dimensions = (width, height)

    return cv.warpAffine(img, rotMat, dimensions)

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

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


# 3. Resizing
resized = cv.resize(img, (500,500), interpolation=cv.INTER_CUBIC)
cv.imshow('Resized', resized)


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


# 5. Cropping
cropped = img[200:400, 300:400]
cv.imshow('Cropped', cropped)


cv.waitKey(0)

'OpenCV' 카테고리의 다른 글

[OpenCV] splitmerge.py: Color Channels  (0) 2024.04.10
[OpenCV] contours.py  (0) 2024.04.10
[OpenCV] basic.py  (0) 2024.04.10
[OpenCV] draw.py  (0) 2024.04.10
[OpenCV] rescale.py  (0) 2024.04.10