python opencv 进行简单几何变换

本文介绍如何使用Python结合OpenCV库实现图像的放大、缩小、平移及旋转等基本几何变换。通过具体实例演示了每种变换的操作步骤及所需函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

16-python opencv 进行简单几何变换


概述

本节实现的是使用OpenCV里自带的函数,对图像进行简单的几何变换。

  • 放大
  • 缩小
  • 平移
  • 旋转

实现过程

读取原图并显示

不再赘述。

import cv2
import numpy as np

# read the original
img = cv2.imread('../test2.jpg')
cv2.imshow('original', img)

放大

利用OpenCV自带的resize()函数实现放大与缩小。其声明为:

cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]]) → dst

其中各个参数的意义如下:

  • src – input image.
  • dst – output image; it has the size dsize (when it is non-zero) or the size computed from src.size(), fx, and fy; the type of dst is the same as of src.
  • dsize –output image size; if it equals zero, it is computed as:
    dsize = Size(round(fx × src.cols), round(fy × src.rows))
  • fx –scale factor along the horizontal axis; when it equals 0, it is computed as
  • fy –scale factor along the vertical axis; when it equals 0, it is computed as
  • interpolation –interpolation method:
参数意义
INTER_NEARESTa nearest-neighbor interpolation
INTER_LINEARa bilinear interpolation (used by default)
INTER_AREAresampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method.
INTER_CUBICa bicubic interpolation over 4x4 pixel neighborhood
INTER_LANCZOS4a Lanczos interpolation over 8x8 pixel neighborhood

本文将原图放大至原来的2倍。

# expand
rows, cols, channels = img.shape
img_ex = cv2.resize(img, (2*cols, 2*rows), interpolation=cv2.INTER_CUBIC)
cv2.imshow('expand', img_ex)

缩小

这里将原图缩小为原来的一半。

# zoom
img_zo = cv2.resize(img, (cols/2, rows/2), interpolation=cv2.INTER_AREA)
cv2.imshow('zoom', img_zo)

平移

平移可以由平移矩阵描述:

[1001txty](4) (4) [ 1 0 t x 0 1 t y ]

其中

$tx $ t x
ty
$分别为向右和向下平移的距离。这里我们利用np.array()创建这个矩阵,然后调用warpAffine来实现这个变换,并保持图像的大小不变。

# trans
M = np.array([[1, 0, 50],[0, 1, 50]], np.float32)
img_tr =cv2.warpAffine(img, M, img.shape[:2])
cv2.imshow('trans', img_tr)

其中warpAffine()的声明如下:

cv2.warpAffine(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]]) → dst

各个参数的意义如下:

  • src – input image.
  • dst – output image that has the size dsize and the same type as src .
  • M – 2 × 3 transformation matrix.
  • dsize – size of the output image.
  • flags – combination of interpolation methods (see resize() ) and the optional flag WARP_INVERSE_MAP that means that M is the inverse transformation.
  • borderMode – pixel extrapolation method (see borderInterpolate()); when borderMode=BORDER_TRANSPARENT , it means that the pixels in the destination image corresponding to the “outliers” in the source image are not modified by the function.
  • borderValue – value used in case of a constant border; by default, it is 0.

旋转

利用getRotationMatrix2D()获得旋转矩阵,其声明为

cv2.getRotationMatrix2D(center, angle, scale) → retval

各个参数的意义:

  • center – Center of the rotation in the source image.
  • angle – Rotation angle in degrees. Positive values mean counter-clockwise rotation (the coordinate origin is assumed to be the top-left corner).
  • scale – Isotropic scale factor.
  • retval – The output affine transformation, 2x3 floating-point matrix.

然后再利用warpAffine()函数进行变换。

# Rotation
M=cv2.getRotationMatrix2D((cols/2,rows/2), 45, 1)
img_ro =cv2.warpAffine(img, M, img.shape[:2])
cv2.imshow('rotation', img_ro)

源代码

程序的源代码如下:

# created by Huang Lu
# 2016/8/26 17:35
# Department of EE, Tsinghua Univ.

import cv2
import numpy as np

# read the original
img = cv2.imread('../test2.jpg')
cv2.imshow('original', img)

# expand
rows, cols, channels = img.shape
img_ex = cv2.resize(img, (2*cols, 2*rows), interpolation=cv2.INTER_CUBIC)
cv2.imshow('expand', img_ex)

# zoom
img_zo = cv2.resize(img, (cols/2, rows/2), interpolation=cv2.INTER_AREA)
cv2.imshow('zoom', img_zo)

# trans
M = np.array([[1, 0, 50],[0, 1, 50]], np.float32)
img_tr =cv2.warpAffine(img, M, img.shape[:2])
cv2.imshow('trans', img_tr)

# Rotation
M=cv2.getRotationMatrix2D((cols/2,rows/2), 45, 1)
img_ro =cv2.warpAffine(img, M, img.shape[:2])
cv2.imshow('rotation', img_ro)

# wait the key and close windows
cv2.waitKey(0)
cv2.destroyAllWindows()

也可以参考我的GitHub上的,点击这里

运行结果

在命令行进入该源程序所在目录后,运行python main.py后即可显示结果。显示结果如下:

结果

参考

### Python OpenCV 图像几何变换教程 在图像处理中,几何变换是改变图像空间属性的一种重要操作。通过几何变换,可以调整图像的位置、大小、方向或形状。PythonOpenCV 库提供了丰富的功能来实现这些几何变换[^2]。 以下是一些常见的几何变换方法及其代码示例: --- #### 1. 平移 平移操作可以通过定义一个平移矩阵来实现。该矩阵指定图像在 x 和 y 方向上的偏移量。 ```python import cv2 import numpy as np # 加载图像 img = cv2.imread('image.jpg') rows, cols = img.shape[:2] # 定义平移矩阵 M = np.float32([[1, 0, 100], [0, 1, 50]]) # x 方向移动 100 像素,y 方向移动 50 像素 # 应用平移 dst = cv2.warpAffine(img, M, (cols, rows)) cv2.imshow('Original', img) cv2.imshow('Translated', dst) cv2.waitKey(0) cv2.destroyAllWindows() ``` --- #### 2. 缩放 缩放操作可以使用 `cv2.resize()` 函数实现。通过指定缩放比例或目标尺寸来调整图像大小。 ```python # 缩放操作 resized_img = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_LINEAR) # 缩小为原来的一半 cv2.imshow('Resized', resized_img) cv2.waitKey(0) cv2.destroyAllWindows() ``` --- #### 3. 旋转 旋转操作需要定义一个旋转矩阵,包含旋转角度和缩放因子。 ```python # 定义旋转中心、角度和缩放因子 center = (cols // 2, rows // 2) angle = 45 # 逆时针旋转 45 度 scale = 1.0 # 获取旋转矩阵 M = cv2.getRotationMatrix2D(center, angle, scale) # 应用旋转 rotated_img = cv2.warpAffine(img, M, (cols, rows)) cv2.imshow('Rotated', rotated_img) cv2.waitKey(0) cv2.destroyAllWindows() ``` --- #### 4. 仿射变换 仿射变换通过指定输入图像中的三个点及其在输出图像中的对应位置来实现。 ```python # 定义输入和输出的三点坐标 pts1 = np.float32([[50, 50], [200, 50], [50, 200]]) pts2 = np.float32([[10, 100], [200, 50], [100, 250]]) # 获取仿射变换矩阵 M = cv2.getAffineTransform(pts1, pts2) # 应用仿射变换 affine_img = cv2.warpAffine(img, M, (cols, rows)) cv2.imshow('Affine', affine_img) cv2.waitKey(0) cv2.destroyAllWindows() ``` --- #### 5. 透视变换 透视变换需要指定输入图像中的四个点及其在输出图像中的对应位置。 ```python # 定义输入和输出的四点坐标 pts1 = np.float32([[60, 80], [368, 65], [28, 387], [389, 390]]) pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]]) # 获取透视变换矩阵 M = cv2.getPerspectiveTransform(pts1, pts2) # 应用透视变换 perspective_img = cv2.warpPerspective(img, M, (300, 300)) cv2.imshow('Perspective', perspective_img) cv2.waitKey(0) cv2.destroyAllWindows() ``` --- #### 安装 OpenCV 如果尚未安装 OpenCV,可以使用以下命令进行安装[^3]: ```bash pip install opencv-contrib-python ``` 或者使用清华镜像源加速安装: ```bash pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python ``` --- ### 总结 上述代码展示了如何使用 OpenCVPython 中实现图像的几何变换。包括平移、缩放、旋转、仿射变换和透视变换等常见操作。每种变换都需要定义相应的变换矩阵,并调用对应的 OpenCV 函数[^4]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值