opencv 小tips
pdf 路径 D:\2_Noteexpress数据库\fulltext\电子书\CV\Practical Python and OpenCV by Adrian Rosebrock (z-lib.org).pdf
6.1 Image Transformations
6.1.1 Translation 函数的用法,该函数可以将图像前后左右移动,重点关注M矩阵。
1 import numpy as np
2 import argparse
3 import imutils
4 import cv2
5 6
ap = argparse.ArgumentParser()
7 ap.add_argument("-i", "--image", required = True,
8 help = "Path to the image")
9 args = vars(ap.parse_args())
10
11 image = cv2.imread(args["image"])
12 cv2.imshow("Original", image)
13
14 M = np.float32([[1, 0, 25], [0, 1, 50]])
15 shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape
[0]))
16 cv2.imshow("Shifted Down and Right", shifted)
17
18 M = np.float32([[1, 0, -50], [0, 1, -90]])
19 shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape
[0]))
20 cv2.imshow("Shifted Up and Left", shifted)
辅助函数
1 import numpy as np
2 import cv2
3
4 def translate(image, x, y):
5 M = np.float32([[1, 0, x], [0, 1, y]])
6 shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
7 return shifted
translation.py
21 shifted = imutils.translate(image, 0, 100)
22 cv2.imshow("Shifted Down", shifted)
23 cv2.waitKey(0)
Top-Left: Our original T-Rex image.
Top-Right: Translating our image 25
pixels to the right and 50 pixels
down. Bottom-Left: Shifting T-Rex
50 pixels to the left and 90 pixels up. Bottom-Right: Shifting the
T-Rex down using our convenience
method
6.1.2 Rotation
1 import numpy as np
2 import argparse
3 import imutils
4 import cv2
5 6
ap = argparse.ArgumentParser()
7 ap.add_argument("-i", "--image", required = True,
8 help = "Path to the image")
9 args = vars(ap.parse_args())
10
11 image = cv2.imread(args["image"])
12 cv2.imshow("Original", image)
13
14 (h, w) = image.shape[:2]
15 center = (w // 2, h // 2)
16
17 M = cv2.getRotationMatrix2D(center, 45, 1.0)
18 rotated = cv2.warpAffine(image, M, (w, h))
19 cv2.imshow("Rotated by 45 Degrees", rotated)
20
21 M = cv2.getRotationMatrix2D(center, -90, 1.0)
22 rotated = cv2.warpAffine(image, M, (w, h))
23 cv2.imshow("Rotated by -90 Degrees", rotated)
27 def rotate(image, angle, center = None, scale = 1.0):
28 (h, w) = image.shape[:2]
29
30 if center is None:
31 center = (w / 2, h / 2)
32
33 M = cv2.getRotationMatrix2D(center, angle, scale)
34 rotated = cv2.warpAffine(image, M, (w, h))
35 return rotated
Top-Left: Our original T-Rex image.
Top-Right: Rotating the image by 45
degrees. Bottom-Left: Rotating the
image by −90 degrees. Bottom-Right:
Flipping T-Rex upside down by rotating the image by 180 degrees.