opencv-python几何变换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lissdy/article/details/78429906

Geometric Transformations of Images

扩展缩放

  • cv2.resize()
# -*- coding: utf-8 -*-
# 改变图像尺寸
import cv2
import numpy as np
img=cv2.imread('demo.jpg')

# src   输入图像
# dsize 输出图像的尺寸,为空时的计算逻辑是 Size(round(fx*src.cols), round(fy*src.rows)), dsize 和 fx,fy不能同时为0
# fx    x轴的缩放因子,为0时的计算逻辑是(double)dsize.width/src.cols
# fy    y轴的缩放因子,为0时的计算逻辑是(double)dsize.height/src.rows
# interpolation 插值方法
res = cv2.resize(img,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_AREA)

#或者直接设置输出图像的尺寸,不设置缩放因子,达到的效果是一样的
#height,width=img.shape[:2]
#res=cv2.resize(img,(width/2,height/2),interpolation=cv2.INTER_AREA)

cv2.imshow('res',res)
cv2.imshow('img',img)
cv2.waitKey(0)

image.png

平移

  • cv2.warpAffine()

平移矩阵.jpg

# -*- coding: utf-8 -*-
import cv2
import numpy as np

img = cv2.imread('demo.jpg',0)
rows,cols = img.shape # 默认返回行数,列数,通道数
# 构建平移矩阵
M = np.float32([[1,0,100],[0,1,50]])

# 调用warpAffine进行平移
# img 图像
# M 平移矩阵
# (width,height) 输出图像大小
dst = cv2.warpAffine(img,M,(cols,rows))
cv2.imshow('img',dst)
cv2.waitKey(0)

result.jpg

旋转

  • cv2.getRotationMatrix2D()与cv2.warpAffine()
# -*- coding: utf-8 -*-
# 旋转
import cv2
import numpy as np
img=cv2.imread('demo.jpg',0)

rows,cols = img.shape
# cv2.getRotationMatrix2D()用于构建旋转矩阵
# 参数一:旋转中心
# 参数二:旋转角度
# 参数三:缩放因子
M = cv2.getRotationMatrix2D((cols/2,rows/2),90,1)
# 参数三是输出图像的尺寸
dst = cv2.warpAffine(img,M,(cols,rows))
cv2.imshow('dst',dst)
cv2.waitKey(0)

result.jpg

仿射变换

# -*- coding: utf-8 -*-
# 仿射变换
import cv2
import numpy as np
from matplotlib import pyplot as plt

img=cv2.imread('demo.jpg',0)
rows,cols = img.shape
pts1 = np.float32([[50,50],[200,50],[50,200]])
pts2 = np.float32([[10,100],[200,50],[100,250]])

M = cv2.getAffineTransform(pts1,pts2)
dst = cv2.warpAffine(img,M,(cols,rows))
plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()

result.jpg

透视变换

# -*- coding: utf-8 -*-
# 透视变换
import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('demo.jpg')
rows,cols,ch = img.shape
pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(300,300))
plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()

result.jpg

猜你喜欢

转载自blog.csdn.net/lissdy/article/details/78429906