1.缩放
- cv2.resize()
- 插值方法flag的值有:INTER_AREA、INTER_CUBIC、INTER_LINEAR等
def scale(self):
#【1】使用缩放系数
res1=cv2.resize(self.img,None,fx=2,fy=2,interpolation=cv2.INTER_CUBIC)
#【2】设定目标图像大小
height,width=self.img.shape[:2]
res2=cv2.resize(self.img,(2*width,2*height),interpolation=cv2.INTER_CUBIC)
print(self.img.shape)
print(res1.shape)
print(res2.shape)
缩放前后的图像尺寸变化:放大了2倍。
(640, 640, 3)
(1280, 1280, 3)
(1280, 1280, 3)
2.平移
- cv2.warpAffine(img,M,(width,height))
平移矩阵的形式:
def translate(self):
rows,cols,ch=self.img.shape
M=np.float32([[1,0,100],[0,1,50]])#x方向平移100个像素,y方向平移50个像素
dst=cv2.warpAffine(self.img,M,(cols,rows))#第二个参数是变换矩阵,第三个参数是输出图像的宽高。
print(self.img.shape)
print(dst.shape)
(640, 640, 3)
(640, 640, 3)
3.旋转
- cv2.getRotationMatrix2D()
- cv2.warpAffine()
旋转
的矩阵:
opencv还允许在任意位置旋转:
除了
,我们还需要指定center和scale。
def rotate(self):
rows=self.img.shape[0]
cols=self.img.shape[1]
M=cv2.getRotationMatrix2D((cols/2,rows/2),45,0.6)
#这里的第一个参数为旋转中心,第二个为旋转角度,第三个为旋转后的缩放因子
dst=cv2.warpAffine(self.img,M,(2*cols,2*rows))
#第三个参数是输出图像的尺寸中心
print(self.img.shape)
print(dst.shape)
(640, 640, 3)
(1280, 1280, 3)
4.仿射变换
- cv2.getAffineTransform()
- cv2.warpAffine()
在仿射变换中,原图中所有的平行线在结果图像中同样平行。为了创建这个矩阵我们需要从原图像中找到三个点以及他们在输出图像中的位置。然后cv2.getAffineTransform 会创建一个2x3 的矩阵,最后这个矩阵会被传给函数cv2.warpAffine。
def affine(self):
rows,cols,ch=self.img.shape
pts1=np.float32([[50,50],[200,50],[50,200]])
pts2=np.float32([[10,100],[200,50],[100,240]])
M=cv2.getAffineTransform(pts1,pts2)
dst=cv2.warpAffine(self.img,M,(cols,rows))
print(self.img.shape)
print(dst.shape)
(640, 640, 3)
(640, 640, 3)
5.透视变换
- cv2.getPerspectiveTransform()
- cv2.warpPerspective()
对于视角变换,我们需要一个3x3 变换矩阵。在变换前后直线还是直线。要构建这个变换矩阵,你需要在输入图像上找4 个点,以及他们在输出图像上对应的位置。这四个点中的任意三个都不能共线。这个变换矩阵可以由函数cv2.getPerspectiveTransform() 构建。然后把这个矩阵传给函数cv2.warpPerspective。
我的这个图片案例其实效果不太明显。可以查看相机标定那里的效果。
def perspective(self):
rows,cols,ch=self.img.shape
pts1=np.float32([[56,65],[368,52],[28,387],[389,390]])
pts2=np.float32([[0,0],[300,0],[0,300],[300,300]])
M=cv2.getPerspectiveTransform(pts1,pts2)
dst=cv2.warpPerspective(self.img,M,(300,300))
print(self.img.shape)
print(dst.shape)
(640, 640, 3)
(300, 300, 3)