欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用OpenCV和PIL旋转90,180,270效率对比

程序员文章站 2022-05-17 10:05:37
...

最近需要一个批量旋转图像的程序,现在发现的有3种方法,所以就想看看哪个效率高点,所以进行了以下测试。

1、OpenCV使用仿射变换

这个参考了 OpenCV Python – Rotate Image 90, 180, 270 – Example

import cv2
import time
# read image as grey scale
img = cv2.imread('0916_174.jpg')
# get image height, width
(h, w) = img.shape[:2
                    ]
# calculate the center of the image
center = (w / 2, h / 2)
 
angle90 = 90
angle180 = 180
angle270 = 270
 
scale = 1.0

start = time.time()
# time.sleep(1)
for i in range(200):
# Perform the counter clockwise rotation holding at the center
    # 90 degrees
    M = cv2.getRotationMatrix2D(center, angle90, scale)
    rotated90 = cv2.warpAffine(img, M, (h, w))
    
    # 180 degrees
    M = cv2.getRotationMatrix2D(center, angle180, scale)
    rotated180 = cv2.warpAffine(img, M, (w, h))
    
    # 270 degrees
    M = cv2.getRotationMatrix2D(center, angle270, scale)
    rotated270 = cv2.warpAffine(img, M, (h, w))
end  = time.time()
print(f'cost is {end - start}')
# cost is 1.568622350692749

使用OpenCV的transpose和flip

这个参考OpenCV图像镜像

import cv2
import time 


image = cv2.imread('0916_174.jpg')

# cv2.imshow("image", image)
start = time.time()
# time.sleep(1)
for i in range(200):
#镜像

    image2 = cv2.flip(image, 0)#相对于原图顺时针旋转180度的水平镜像翻转
                               # ,等于转置图像顺时针旋转270度

    # cv2.imshow("2", image2)

    image3 = cv2.flip(image, 1) #相对于原图水平镜像翻转 , 等于转置图像顺时针旋转90度

    # cv2.imshow("3", image3)

    #转置
    image=cv2.transpose(image) #转置图像

    # cv2.imshow("0", image)

    image11 = cv2.flip(image, -1)#等于原图顺时针旋转270度的水平镜像翻转,相对于转置图像顺时针旋转180度

    # cv2.imshow("11", image11)

    # cv2.waitKey(0)
end  = time.time()
print(f'cost is {end - start}')
#cost is 3.548659324645996

3、使用PIL自带的rotate函数

import os
from PIL import Image
import time
img = Image.open('0916_174.jpg')


start = time.time()
# time.sleep(1)
for i in range(200):
    img = img.transpose(Image.ROTATE_90)  # 将图片旋转90度
    img = img.transpose(Image.ROTATE_180)  # 将图片旋转180度
    img = img.transpose(Image.ROTATE_270)  # 将图片旋转270度
# img.show("img/rotateImg.png")
#img.save("img/rotateImg.png")
end  = time.time()
print(f'cost is {end - start}')
#cost is 1.4058425426483154

最后发现PIL函数的旋转效率最好,放射变换其次,transpose最慢

相关标签: opencv