1. 程式人生 > >【Python+OpenCV入門學習】十二、影象的幾何變換

【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()

執行結果如下: