【计算机视觉(6)】-仿射变化和透视变换的代码实现:

时间:2024-06-01 07:14:46
import cv2                       
import matplotlib.pyplot as plt 
image = cv2.imread("img/cat.jpg") 
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_shape = image.shape # 获取图像的垂直尺寸、水平尺寸、通道数(image.shape[0],image.shape[1],image.shape[2])  
M1 = cv2.getRotationMatrix2D((image_shape[0] / 2, image_shape[1] / 2), 45, 1) # 求出绕图像中心逆时针旋转45度的旋转矩阵  
image_clockwise = cv2.warpAffine(image, M1, (image_shape[0], image_shape[1])) # 图像旋转  
M2 = cv2.getRotationMatrix2D((image_shape[0] / 2, image_shape[1] / 2), -45, 1) # 求出绕图像中心顺时针旋转45度的旋转矩阵  
image_anticlockwise = cv2.warpAffine(image, M2, (image_shape[0], image_shape[1])) # 图像旋转  
image_list = [image, image_clockwise, image_anticlockwise] 
titles = ["Original", "anticlockwise", "clockwise"]  
for i in range(3):  
    plt.subplot(1, 3, i + 1), plt.imshow(image_list[i], 'gray')  
    plt.xticks([]), plt.yticks([]) 
plt.show() 

代码实现效果图:
在这里插入图片描述

import cv2                       
import matplotlib.pyplot as plt 
import numpy as np  
image = cv2.imread("img/cat.jpg") 
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_shape = image.shape # 获取图像的垂直尺寸、水平尺寸、通道数(image.shape[0],image.shape[1],image.shape[2])  
h, w = image_shape[:2] # 获取高和宽  
pts1 = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]) # 获取原图的四个角点  
pts2 = np.float32([[0, 0], [200, h - 36], [w - 36, h - 36], [w - 1, 0]]) # 变换后的四个顶点坐标  
M = cv2.getPerspectiveTransform(pts1, pts2) # 先得确定透视变换的系数  
dst = cv2.warpPerspective(image, M, (500, 526)) # 对原图进行仿射变换  
image_list = [image, dst] 
titles = ["Original", " perspective"] 
for i in range(2):  
    plt.subplot(1, 2, i + 1), plt.imshow(image_list[i], 'gray')  
    plt.title(titles[i])  
    plt.xticks([]), plt.yticks([]) 
plt.show()  

代码实现效果图:
在这里插入图片描述