今天利用python+opencv简单的旋转图片
!/usr/bin/python3
# -*- coding: UTF-8 -*-
import numpy as np
import argparse
import imutils
import cv2
ap=argparse.ArgumentParser()
ap.add_argument("-i","--image",required=True,help="Path to the image")
args=vars(ap.parse_args())
image=cv2.imread(args["image"])
cv2.namedWindow("Original",0)
cv2.resizeWindow("Original",640,480)
cv2.imshow("Original",image)
(h,w)=image.shape[:2]
center=(w//2,h//2)
M=cv2.getRotationMatrix2D(center,45,1.0)
rotated=cv2.warpAffine(image,M,(w,h))
cv2.namedWindow("Rotated by 45 Degrees",0)
cv2.resizeWindow("Rotated by 45 Degrees",640,480)
cv2.imshow("Rotated by 45 Degrees",rotated)
M=cv2.getRotationMatrix2D(center,-90,1.0)
rotated=cv2.warpAffine(image,M,(w,h))
cv2.namedWindow("Rotated by -90 Degrees",0)
cv2.resizeWindow("Rotated by -90 Degrees",640,480)
cv2.imshow("Rotated by -90 Degrees",rotated)
rotated=imutils.rotate(image,180)
cv2.namedWindow("Rotated by 180 Degrees",0)
cv2.resizeWindow("Rotated by 180 Degrees",640,480)
cv2.imshow("Rotated by 180 Degrees",rotated)
cv2.waitKey(0)
运行:
./pic_rotation.py -i nv.jpg
结果:
介绍两个函数:
cv2.getRotationMatrix2D()
第一个参数:表示向以哪一点进行旋转?这里就是图像的中心
第二个参数:表示我们希望旋转的角度。这里为正45度,表示顺时针旋转45度
第三个参数:表示图像旋转后的大小,这里设为1表示大小与原图大小一致
通过cv2.warpAffine()方法,我们便可进行旋转图像的操作
第一个参数为原图,第二个参数为旋转矩阵,第三个参数为图像(宽,高)的元组,然后将旋转后的图像显示出来