2020-10-24

机器视觉OpenCv+Python 学习(三)-图片几何变换(一)

图片几何变换包括图片剪切、缩放、位移、镜像、旋转等,可以归结为仿射变换。以下为代码实现:

图片位移

import cv2 as cv
import numpy as np
img =cv.imread ('E:/pythonProject/picture/CSet12/monarch.bmp',1)
imgInfo = img.shape
height = imgInfo[0]
width  = imgInfo[1]
print(imgInfo)
matShift =np.float32([[1,0,100],
                    [0,1,100]])                  #仿射变换矩阵
dst =cv.warpAffine(img,matShift,(imgInfo[0],imgInfo[1]))  #向下,向右平移100
print(dst.shape)
#源码
dst2 =np.zeros(imgInfo,np.uint8)
for i in range(0,height-100):
    for j in range(0,width-100):
        dst2[i+100,j+100]=img[i,j]

cv.imshow('img',img)
cv.imshow('dst',dst)
cv.imshow('dst2',dst2)
cv.waitKey(0)

图片剪切

import cv2 as cv

img =cv.imread ('E:/pythonProject/picture/CSet12/lena.png',1)
imgInfo = img.shape
dst =img[100:200,100:300]  # 需要剪切的坐标位置
cv.imshow('dst',dst)
cv.waitKey(0)

图片旋转

import cv2 as cv
import numpy as np
img =cv.imread ('E:/pythonProject/picture/CSet12/monarch.bmp',1)
cv.imshow('img',img)
imgInfo = img.shape
height = imgInfo[0]
width  = imgInfo[1]

matRotate =cv.getRotationMatrix2D((height*0.5,width*0.5),45,0.5)
'''
函数调用形式:
getRotationMatrix2D(Point2f center, double angle, double scale)

参数详解:
Point2f center:表示旋转的中心点
double angle:表示旋转的角度
double scale:图像缩放因子
'''
dst = cv.warpAffine(img,matRotate,(width,height))

cv.imshow('dst',dst)
cv.waitKey(0)
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页