Opencv-python实用教程

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)

6.1.1

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

6.1.2
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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值