-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_transformations.py
More file actions
80 lines (67 loc) · 2.44 KB
/
image_transformations.py
File metadata and controls
80 lines (67 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import cv2 as cv
import numpy as np
# ------------------------------------------------
# Load the image
# ------------------------------------------------
Image = cv.imread('images/elder-man.jpg')
if Image is None:
print("Error: Could not load image. Check the file path.")
exit()
# ------------------------------------------------
# Utility Functions
# ------------------------------------------------
def rescaleFrame(frame, scale=0.15):
"""
Rescales an image by a given scale factor.
"""
width = int(frame.shape[1] * scale)
height = int(frame.shape[0] * scale)
dimensions = (width, height)
return cv.resize(frame, dimensions, interpolation=cv.INTER_AREA)
def translate(image, x, y):
"""
Shifts an image along the x and y axes.
"""
transMat = np.float32([[1, 0, x], [0, 1, y]])
dimensions = (image.shape[1], image.shape[0])
return cv.warpAffine(image, transMat, dimensions)
def rotate(img, angle, rotPoint=None):
"""
Rotates an image around a point (default = image center).
"""
(h, w) = img.shape[:2]
if rotPoint is None:
rotPoint = (w // 2, h // 2)
rotMat = cv.getRotationMatrix2D(rotPoint, angle, 1.0)
return cv.warpAffine(img, rotMat, (w, h))
# ------------------------------------------------
# Apply Transformations
# ------------------------------------------------
# 1. Translation
translated = translate(Image, 100, 100)
cv.imshow('Translated', rescaleFrame(translated))
cv.imwrite("Output/elder-man_translated.jpg", translated)
# 2. Rotation
rotated = rotate(Image, -45)
cv.imshow('Rotated (-45%)', rescaleFrame(rotated))
cv.imwrite("Output/elder-man_rotated-45.jpg", rotated)
rotated_twice = rotate(rotated, -90)
cv.imshow('Rotated Again (-90%)', rescaleFrame(rotated_twice))
cv.imwrite("Output/elder-man_rotated-90.jpg", rotated_twice)
# 3. Resizing
resized = cv.resize(Image, (500, 500), interpolation=cv.INTER_CUBIC)
cv.imshow('Resized (500x500)', resized)
cv.imwrite("Output/elder-man_resized-500x500.jpg", resized)
# 4. Flipping
flipped = cv.flip(Image, 1)
cv.imshow('Flipped (horizontal)', rescaleFrame(flipped))
cv.imwrite("Output/elder-man_flipped-horizontal.jpg", flipped)
# 5. Cropping
cropped = Image[200:400, 300:400]
cv.imshow('Cropped', rescaleFrame(cropped))
cv.imwrite("Output/elder-man_cropped.jpg", cropped)
# ------------------------------------------------
# Exit
# ------------------------------------------------
cv.waitKey(0)
cv.destroyAllWindows()