我正在寻找一种更快的方法来规范化Python中的图像。我想将所有像素转换为0到1之间的值。
INPUT:JPEG格式的150x150 RGB图像。
OS / HARDWARE:具有8GB RAM的LINUX / P40 GPU
USE-CASE:用于实时分类任务的图像预处理。
每幅图像的当前时间约为5-10毫秒。我正在寻找一种可以减少这个时间的方法。
我尝试了两种方法,使用numpy和opencv。
norm = (img - np.min(img)) / (np.max(img) - np.min(img))
norm = cv2.normalize(img, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
这两种方法对我的用例都很慢。任何人都可以用更快的图像规范化方法指导我吗?
你的时间对我来说似乎很慢。也许您的安装出了问题?
我试过这个测试程序:
#!/usr/bin/python3
import sys
import numpy as np
import cv2
from PIL import Image
from profilehooks import profile
@profile
def try_numpy(img):
ar = np.array(img).astype(np.float32)
for i in range(1000):
mn = np.min(ar)
mx = np.max(ar)
norm = (ar - mn) * (1.0 / (mx - mn))
@profile
def try_cv2(img):
for i in range(1000):
norm = cv2.normalize(img, None, alpha=0, beta=1,
norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
img = Image.open(sys.argv[1])
try_numpy(img)
img = cv2.imread(sys.argv[1])
try_cv2(img)
在这款运行Ubuntu 19.04的这款适度的2015 i5笔记本上,我看到:
$ ./try291.py ~/pics/150x150.png
*** PROFILER RESULTS ***
try_cv2 (./try291.py:17)
function called 1 times
1002 function calls in 0.119 seconds
Ordered by: cumulative time, internal time, call count
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.001 0.001 0.119 0.119 try291.py:17(try_cv2)
1000 0.118 0.000 0.118 0.000 {normalize}
*** PROFILER RESULTS ***
try_numpy (./try291.py:9)
function called 1 times
10067 function calls in 0.113 seconds
Ordered by: cumulative time, internal time, call count
List reduced from 52 to 40 due to restriction <40>
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.064 0.064 0.113 0.113 try291.py:9(try_numpy)
2000 0.004 0.000 0.045 0.000 fromnumeric.py:69(_wrapreduction)
所以他们每次通话大约需要0.1ms,比你看到的数字快50倍。
为了进一步加快速度: