【Python+OpenCV入门学习】十二、图像的几何变换

本篇文章介绍图像处理的几何变换,几何变换有平移、缩放、旋转等。

主要学习resize()、warpAffine()等函数的使用。

环境:Windows 7(64)   Python 3.6    OpenCV3.4.2

一、缩放

1.1 resize()函数介绍

resize()函数形式如下:

dst = cv.resize( src, dsize[, dst[, fx[, fy[, interpolation]]]]	)

功能:缩放图像

参数:

src:输入的图像

dst:输出的图像,即缩放后的图像

dsize:输出的图像大小。如果为0,则dsize=Size(round(fx*src.cols), round(fy*src.rows))

fx:水平方向上的缩放因子,如果为0,则fx=(double)dsize.width/src.cols

fy:垂直方向上的缩放因子,如果为0,则fy=(double)dsize.height/src.rows

interpolation:插值方法,当图像进行几何变换时,有些位置的像素值必须通过插值方式计算所得。

注意,dsize与fx/fy不能同时为0。interpolation的取值详细见InterpolationFlags,以下列举常见的几个:

cv.INTER_NEAREST:最近邻插值

cv.INTER_LINEAR:双线性插值

 cv.INTER_CUBIC:双三次插值,默认值。

1.2编程测试

代码如下:

import cv2 as cv
import numpy as np

img = cv.imread('2.png')
#使用参数fx/fy进行缩放为原来的0.5倍
dst1 = cv.resize(img,None,fx=0.5,fy=0.5,interpolation = cv.INTER_CUBIC)

#使用参数dsize缩放为原来的0.5倍
height,width = img.shape[:2]
dst2 = cv.resize(img,(int(0.5*width),int(0.5*height)),interpolation = cv.INTER_CUBIC)


#显示
cv.imshow('src',img)
cv.imshow('scale fx/fy',dst1)
cv.imshow('scale dsize',dst2)

cv.waitKey(0)
cv.destroyAllWindows()

运行结果如下:

                   

二、仿射变换

2.1 warpAffine()函数介绍

函数形式如下:

dst = cv.warpAffine( src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]] )

功能:对图像进行仿射变换。

参数:

src:输入的图像

dst:仿射变换后的图像

M:放射变换的矩阵,2*3的矩阵

dsize:输出的图像大小

flag:插值方法

borderMode:边界模式

borderValue:边界值,默认为0。

注意,仿射变换的计算公式:dst(x,y)=src(M11x+M12y+M13,M21x+M22y+M23),其中,

                                                M=\begin{bmatrix} M_{11} M_{12} M_{13}\\ M_{21} M_{22} M_{23} \end{bmatrix}

M矩阵取不同的值,就可以完成平移,旋转等操作。当想要完成旋转操作时,需要介绍另一个函数 getRotationMatrix2D(),函数形式如下:

retval = cv.getRotationMatrix2D( center, angle, scale )

 

功能:得到二维的旋转矩阵

参数:

center:旋转中心点坐标

angle:旋转角度,逆时针旋转

scale:比例因子

2.2编程实现

代码实现如下:

import cv2 as cv
import numpy as np

img = cv.imread('2.png',0)
rows,cols = img.shape

#平移(100,50)
M_translation = np.float32([[1,0,100],[0,1,50]])
dst1 = cv.warpAffine(img,M_translation,(cols,rows))

#中心旋转逆时针90度
M_rotation = cv.getRotationMatrix2D(((cols-1)/2.0,(rows-1)/2.0),90,1)
dst2 = cv.warpAffine(img,M_rotation,(cols,rows))

cv.imshow('img src',img)
cv.imshow('img translation',dst1)
cv.imshow('img rotation',dst2)
cv.waitKey(0)
cv.destroyAllWindows()

运行结果如下:

猜你喜欢

转载自blog.csdn.net/qq_18995069/article/details/84202927