【Python+OpenCV 图像透视变换 warpPerspective函数】

Python+OpenCV 图像透视变换 warpPerspective函数

1、函数介绍

warpPerspective():对图像进行透视变换。简单来说,就是有这么一副图像,它的拍摄视角不是从正面拍摄的,而是带有一定的角度,我们希望能得到从正面观察的视角。

2、代码实例

这里我们用一张从斜上方拍摄的四张扑克牌的图片,用图像透视法提取出J、Q、K三张扑克牌的主视角图。
代码如下

import cv2
import numpy as np

img = cv2.imread("Photos/cards.jpg")

width,height = 250,350  #所需图像大小

#找K
pts1 = np.float32([[527,144],[772,192],[404,396],[677,457]])  #所需图像部分四个顶点的像素点坐标
pts2 = np.float32([[0,0],[width,0],[0,height],[width,height]]) #定义对应的像素点坐标
matrix_K = cv2.getPerspectiveTransform(pts1,pts2)  #使用getPerspectiveTransform()得到转换矩阵
img_K = cv2.warpPerspective(img,matrix_K,(width,height))  #使用warpPerspective()进行透视变换

#找Q
pts3 = np.float32([[63,325],[340,279],[89,634],[403,573]])
pts4 = np.float32([[0,0],[width,0],[0,height],[width,height]])
matrix_Q = cv2.getPerspectiveTransform(pts3,pts4)
img_Q = cv2.warpPerspective(img,matrix_Q,(width,height))

#找J
pts5 = np.float32([[777,107],[1019,84],[842,359],[1117,332]])
pts6 = np.float32([[0,0],[width,0],[0,height],[width,height]])
matrix_J = cv2.getPerspectiveTransform(pts5,pts6)
img_J = cv2.warpPerspective(img,matrix_J,(width,height))

cv2.imshow("Original Image",img)
cv2.imshow("img K",img_K)
cv2.imshow("img Q",img_Q)
cv2.imshow("img J",img_J)

cv2.waitKey(0)

3、实现效果

原图
提取结果

猜你喜欢

转载自blog.csdn.net/LPYchengxuyuan/article/details/121956672