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、实现效果

原图
提取结果

GitHub 加速计划 / opencv31 / opencv
226
21
下载
OpenCV: 开源计算机视觉库
最近提交(Master分支:1 个月前 )
d3d247f1 Remove mention of 'tangential lens distortion' from fisheye documentation. 7 小时前
ec60a98a Fix generation when returned class and function are in a namespace 8 小时前
Logo

新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐