# coding: utf-8
# !/usr/bin/python
"""
@File : 幾何變換.py
@Author : jiaming
@Modify Time: 2020/1/31 15:51
@Contact :
@Version : 1.0
@Desciption : 幾何變換
對圖像進行各種幾何變換:移動、旋轉、仿射變換
cv2.getPerspectiveTransform()
"""
import os
import sys
import numpy as np
import cv2
import pprint
from matplotlib import pyplot as plt
rawPath = os.path.abspath(__file__)
currentFile = os.path.basename(sys.argv[0])
dataPath = rawPath[:rawPath.find(currentFile)] + r'static\\'
"""
OpenCV 提供了兩個變換函數,cv2.warpAffine(martix(2x3),) 和 cv2.warpPerspective(martix(
3x3),)
"""
擴充縮放
"""
擴充縮放:
改變圖像大小。OpenCV提供的函數 cv2.resize 可以實作這個功能 插值方法推薦: cv2.INTER_CUBIC 和
cv2.INTER_LINEAR
對shrinking:cv2.INTER_AREA該方法可以避免波紋的出現
對zooming:優選的interpolation方法:cv2.INTER_CUBIC和cv2.INTER_LINEAR(預設)
None: 圖像輸出尺寸,但是後面設定了縮放因子
res = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
res = cv2.resize(img, (width, leight), interpolation=cv2.INTER_CUBIC)
"""
平移
""""
平移:
建構移動矩陣
将參數傳給 cv2.warpAffine()
"""
img = cv2.imread('xxx')
rows, cols = img.shape
M = np.float32([[1, 0, 100], [0, 1, 50]]) # 類型是 np.float32 移動步幅:(100, 50)
dst = cv2.warpAffine(img, M, (cols, rows)) # 第三個參數是輸出圖像大小 (寬,高)
cv2.imshow('dst', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
旋轉
"""
旋轉:
cv.getRotationMatrix
"""
img = cv2.imread('xxx')
rows, cols = img.shape
# 第一個參數是旋轉中心
# 第二個為旋轉角度
# 第三個為旋轉後的縮放因子
M = cv2.getRotationMatrix2D(((cols - 1) / 2.0, (rows - 1) / 2.0), 90, 1)
# 第三個參數是輸出圖像的尺寸中心
dst = cv2.warpAffine(img, M, (cols, rows))
cv2.imshow('dst', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
仿射變換
"""
仿射變換:
原圖中所有的平行線在結果圖像中同樣平行
cv2.getAffineTransform
"""
img = cv2.imread('xxx')
rows, cols, ch = img.shape
pts1 = np.float32([[50, 50], [200, 50], [50, 200]])
pts2 = np.float32([[10, 100], [200, 50], [100, 250]])
M = cv2.getAffineTransform(pts1, pts2)
dst = cv2.warpAffine(img, M, (cols, rows))
plt.subplot(121), plt.imshow(img), plt.title('Input')
plt.subplot(122), plt.imshow(dst), plt.title('Output')
plt.show()
透視變換
"""
透視變換:
對于透視變換,需要一個3x3變換矩陣。
即使在轉換之後,直線仍将保持筆直. 要找到此變換矩陣,
輸入圖像上需要4個點,輸出圖像上需要相應的點. 在這4個點中,
其中3個不應該共線. 然後可以通過函數cv2.getPerspectiveTransform找到變換矩陣.
然後将cv2.warpPerspective應用于此3x3變換矩陣。
"""
img = cv2.imread('xxx')
rows, cols, ch = 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(img, M, (300, 300))
plt.subplot(121), plt.imshow(img), plt.title('Input')
plt.subplot(122), plt.imshow(dst), plt.title('Output')
plt.show()