pip3 install line_profiler
@profile
def rank_from_video_blur(dir, start, end, num_out):
idx2v = {}
images = os.listdir(dir)
for image in images:
frame_num = int(re.findall(r'\d+', image)[0])
if frame_num >= start and frame_num <= end:
img = plt.imread(os.path.join(dir, image))
img = cv2.resize(img, (960, 540), interpolation = cv2.INTER_CUBIC)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
v = cv2.Laplacian(gray,cv2.CV_64F).var()
idx2v[v] = image
b = sorted([(k,v) for k,v in idx2v.items()], reverse=True)
results = []
for score, image in b[: min(len(b), num_out)]:
#print('frame: ' + image +' v: ' + str(score))
results.append(os.path.join(dir, image))
#plt.imshow(plt.imread(os.path.join(dir, image)))
#plt.show()
return results
kernprof -l -v loopdemo.py
-l表示逐行分析,-v用于输出。
%Time一列是每一行运行时间百分比,可以看到
img = plt.imread(os.path.join(dir, image))
和v = cv2.Laplacian(gray,cv2.CV_64F).var()
两句消耗了大部分时间,分别消耗165和300s,这是由于我们读取的图片分辨率为1920*1080,共6631帧,因此时间花费很大。
对其进行downsample,再看消耗时间:
分别消耗185和80s,读取图片时间差不多不变,而对其进行拉普拉斯变换时间变为了将近1/4。