根据
我的实验,OpenCV在执行图像旋转时表现最快。请查看链接。
编辑:我还应该在这里包含答案:
我将专注于Python中三个最常用的图像编辑库,即Pillow、OpenCV和Scipy。
在下面的代码中,您可以学习如何导入这些库以及如何使用它们旋转图像。我为每个库定义了一个函数,以便在我们的实验中使用它们。
import numpy as np
import PIL
import cv2
import matplotlib.pylab as plt
from PIL import Image
from scipy.ndimage import rotate
from scipy.ndimage import interpolation
def rotate_PIL (image, angel, interpolation):
'''
input :
image : image : PIL image Object
angel : rotation angel : int
interpolation : interpolation mode : PIL.Image.interpolation_mode
Interpolation modes :
PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation in a 2×2 environment), or PIL.Image.BICUBIC
https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.rotate
returns :
rotated image
'''
return image.rotate(angel,interpolation)
def rotate_CV(image, angel , interpolation):
'''
input :
image : image : ndarray
angel : rotation angel : int
interpolation : interpolation mode : cv2 Interpolation object
Interpolation modes :
interpolation cv2.INTER_CUBIC (slow) & cv2.INTER_LINEAR
https://theailearner.com/2018/11/15/image-interpolation-using-opencv-python/
returns :
rotated image : ndarray
'''
h,w = image.shape[:2]
cX,cY = (w//2,h//2)
M = cv2.getRotationMatrix2D((cX,cY),angel,1)
rotated = cv2.warpAffine(image,M , (w,h),flags=interpolation)
return rotated
def rotate_scipy(image, angel , interpolation):
'''
input :
image : image : ndarray
angel : rotation angel : int
interpolation : interpolation mode : int
Interpolation modes :
https://stackoverflow.com/questions/57777370/set-interpolation-method-in-scipy-ndimage-map-coordinates-to-nearest-and-bilinea
order=0 for nearest interpolation
order=1 for linear interpolation
returns :
rotated image : ndarray
'''
return scipy.ndimage.interpolation.rotate(image,angel,reshape=False,order=interpolation)
为了了解哪个库在旋转和插值图像方面更有效,我们首先设计了一个简单的实验。我们在一个由我们的函数rand_8bit()生成的200 x 200像素8位图像上使用所有三个库进行20度旋转。
def rand_8bit(n):
im =np.random.rand(n,n)*255
im = im.astype(np.uint8)
im[n//2:n//2+n//2,n//2:n//4+n//2]= 0
im[n//3:50+n//3,n//3:200+n//3]= 0
return im
im = rand_8bit(200)
image_for_PIL=Image.fromarray(im)
%timeit rotate_PIL(image_for_PIL,20,PIL.Image.BILINEAR)
%timeit rotate_CV(im,20,cv2.INTER_LINEAR)
%timeit rotate_scipy(im,20,1)
结果为:
每次循环平均用时987微秒,标准差为76微秒(7次运行,每次1000次循环)
每次循环平均用时414微秒,标准差为79.8微秒(7次运行,每次1000次循环)
每次循环平均用时4.46毫秒,标准差为1.07毫秒(7次运行,每次100次循环)
这意味着在图像旋转方面,OpenCV是最高效的,而Scipy是最慢的。