如opencv开发前的准备工作中所说,此系列文章是在学习Practical Python and OpenCV(点击下载)这本书的一些记录,发出来的文章跳过了第三章对RGB,以及numpy简单操作等介绍,请大家下载原书查看,在原书中对一下段落已进行翻译注释。文章系列完整展示代码点击下载
Translation
1 | import numpy as np |
以上多次使用warpAffine重复性很高而且 使用起来不方便,我们可以定义一个叫imutils.py的模块封装这个方法如下:
1 | import numpy as np |
再实现上面平移的动作:
1 | import numpy as np |
Rotation 旋转一个角度q的图像。
1 | import numpy as np |
封装rotate方法1
2
3
4
5
6
7def rotate(image, angle ,center= None,scale = 1.0):
(h,w)= image.shape[:2]
if center is None:
center =(w /2,h/2)
M = cv2.getRotationMatrix2D(center,angle,scale)
rotated = cv2.warpAffine(image, M ,(w,h))
return rotated
调用方式:
1 | rotated = imutils.rotate(image,60,None,0.5) |
resize 调整大小
1 | import numpy as np |
Flipping 旋转
我们可以在x或y轴周围翻转图像,甚至可以翻转图像(We can flip an image around either the x or y axis, or even both.)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25import argparse
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i","--image",required = True,help ="Path to the image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])
cv2.imshow("Original",image)
flipped = cv2.flip(image,1)
cv2.imshow("Flipped Horizontally",flipped)
#使用1的翻转代码值表示我们将水平地围绕y轴翻转图像。
flipped = cv2.flip(image,0)
# 指定一个0的翻转代码表示我们想要垂直翻转图像,围绕X轴
cv2.imshow("Flipped Vertically",flipped)
flipped = cv2.flip(image,-1)
# 使用负向翻转代码将图像翻转两个轴。
cv2.imshow("Flipped Horizontally&Vertically",flipped)
cv2.waitKey(0)
Cropping 裁剪
图片的裁剪使用NumPy数组切片来完成图像裁剪1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import numpy as np
import argparse
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i","--image",required =True, help="Path to the image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])
cv2.imshow("Original",image)
#NumPy数组中高度在前面,宽度在后面
cropped = image[30:220 ,10:335]
#所以我们需要截取的区域值定义需要按照numpy的格式,如上[starty:endy,startx:endx]
# 1.Start y: The starting y coordinate. In this case, we
# start at y = 30.
# 2. End y: The ending y coordinate. We will end our crop
# at y = 220.
# 3. Start x: The starting x coordinate of the slice. We start
# the crop at x = 10.
# 4. End x: The ending x-axis coordinate of the slice. Our
# slice ends at x = 335.
cv2.imshow("update",cropped)
cv2.waitKey(0)
凡事往简单处想,往认真处行。