本文實例為大家分享了opencv實現圖像幾何變換的具體代碼,供大家參考,具體內容如下
圖像的擴大與縮小有專門的一個函數,cv2.resize(),那么關于伸縮需要確定的就是縮放比例,可以是x與y方向相同倍數,也可以單獨設置x與y的縮放比例。另外一個就是在縮放以后圖像必然就會變化,這就又涉及到一個插值問題。那么這個函數中,縮放有幾種不同的插值(interpolation)方法,在縮小時推薦cv2.INTER_ARER,擴大是推薦cv2.INTER_CUBIC和cv2.INTER_LINEAR。默認都是cv2.INTER_LINEAR,比如:
import cv2 import matplotlib.pyplot as plt img = cv2.imread('d:/1.jpg') # 插值:interpolation # None本應該是放圖像大小的位置的,后面設置了縮放比例, #所有就不要了 res1 = cv2.resize(img,None,fx=2,fy=2,interpolation=cv2.INTER_CUBIC) #直接規(guī)定縮放大小,這個時候就不需要縮放因子 height,width = img.shape[:2] res2 = cv2.resize(img,(2*width,2*height),interpolation=cv2.INTER_CUBIC) plt.subplot(131) plt.imshow(img) plt.subplot(132) plt.imshow(res1) plt.subplot(133) plt.imshow(res2) plt.show()
import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread('d:/1.jpg') H = np.float32([[1, 0, 100], [0, 1, 50]]) rows, cols = img.shape[:2] res = cv2.warpAffine(img, H, (rows, cols)) # 需要圖像、變換矩陣、變換后的大小 plt.subplot(121) plt.imshow(img) plt.subplot(122) plt.imshow(res) plt.show()
為了構造這個矩陣,opencv提供了一個函數:
cv2.getRotationMatrix2D(),這個函數需要三個參數,旋轉中心,旋轉角度,旋轉后圖像的縮放比例,比如下例:
import cv2 import matplotlib.pyplot as plt img = cv2.imread('d:/1.jpg') rows, cols = img.shape[:2] # 第一個參數旋轉中心,第二個參數旋轉角度,第三個參數:縮放比例 M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 45, 1) # 第三個參數:變換后的圖像大小 res = cv2.warpAffine(img, M, (rows, cols)) plt.subplot(121) plt.imshow(img) plt.subplot(122) plt.imshow(res) plt.show()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。