Python opencv 图像矫正——透视变换
发布日期:2021-05-14 23:02:42 浏览次数:22 分类:精选文章

本文共 1760 字,大约阅读时间需要 5 分钟。

基于透视的图像矫正是一种常用的图像处理技术,主要用于消除透视畸变,恢复图像的准确几何关系。以下是实现该技术的核心步骤和方法:

1. 获取图像四个顶点

在实际应用中,首先需要从图像中提取四个顶点,这些顶点通常是图像的关键点(如四个角)。可以通过以下方法实现:

  • 使用边缘检测算法(如Canny边缘检测)找到图像的轮廓。
  • 对轮廓进行分析,提取四个主要顶点。
  • 通过近似多边形(ApproximBDP)算法得到四边形近似。

2. 形成变换矩阵

一旦获得四个顶点坐标,可以利用这些点构建三维变换矩阵。变换矩阵由旋转、缩放、平移和剪切参数组成,具体计算步骤如下:

  • 将四个点转换为矩阵形式。
  • 利用三点共线性条件,求解变换矩阵。
  • 验证变换矩阵的正确性。

3. 透视变换

通过变换矩阵对原始图像进行透视变换,实现图像的几何校正。具体操作步骤:

  • 将原始图像矩阵与变换矩阵相乘。
  • 输出变换后的图像,去除畸变。

以下是实现过程的代码示例:

from imutils.perspective import four_point_transform
import imutils
import cv2
def Get_Outline(input_dir):
image = cv2.imread(input_dir)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 75, 200)
return image, gray, edged
def Get_cnt(edged):
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
docCnt = None
if len(cnts) > 0:
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx) == 4:
docCnt = approx
break
return docCnt
if __name__ == "__main__":
input_dir = "21.png"
image, gray, edged = Get_Outline(input_dir)
docCnt = Get_cnt(edged)
result_img = four_point_transform(image, docCnt.reshape(4, 2))
for peak in docCnt:
peak = peak[0]
cv2.circle(image, tuple(peak), 10, (255, 0, 0))
cv2.imshow("original", image)
cv2.imshow("gray", gray)
cv2.imshow("edged", edged)
cv2.imshow("result_img", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

4. 结果展示

通过上述方法,可以清晰地看到原始图像与经过透视变换后的图像差异。四个关键点以红色圆圈标注,方便直观验证变换效果。

上一篇:一行代码
下一篇:Python 把图片横向/纵向拼接

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年04月06日 08时19分15秒