gpt4 book ai didi

python - Cython + OpenCV 和 NumPy

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:44 25 4
gpt4 key购买 nike

我有一个主要包含 OpenCV 和 NumPy 以及一些 SciPy 的程序。该系统需要是帧速率接近 30 fps 的实时系统,但目前只有大约 10 fps。使用 Cython 会有助于加快速度吗?我问是因为 OpenCV 已经用 C++ 编写并且应该已经非常优化,据我所知,NumPy 也已经非常优化。那么使用 Cython 是否有助于改善我的程序的处理时间?

最佳答案

希望这对某人有帮助

找到这个很棒的帖子 Use Cython to get more than 30X speedup on your Python code

在通过摄像头的视频流中对每两帧使用相同的阶乘计算

video_python.py

import numpy as np
import cv2
import time

def function(number):

cap = cv2.VideoCapture(0)

increment = 0

while(True):
# Capture frame-by-frame
ret, frame = cap.read()

# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Display the resulting frame
cv2.imshow('frame',gray)

start_time = time.time()
y = 1
for i in range(1, number+1):
y *= i

increment+=1
if increment >2:
# print(time.time()-start_time)
print('Python increment ',increment)
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
return 0

video_cython.pyx

import numpy as np
import cv2
import time

cpdef int function(int number):

cdef bint video_true = True

cap = cv2.VideoCapture(0)

cdef int y = 1
cdef int i

cdef int increment = 0
cdef int increment_times = 0

while(video_true):
# Capture frame-by-frame
ret, frame = cap.read()

# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Display the resulting frame
cv2.imshow('frame',gray)

start_time = time.time()


for i in range(1, number+1):
y *= i
increment_times+=1

if increment_times > 2:
# print(time.time()-start_time)
print('Cython increment ',increment_times)
break

if cv2.waitKey(1) & 0xFF == ord('q'):
break

cap.release()
cv2.destroyAllWindows()
return 0

设置.py

from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules = cythonize('video_cython.pyx',compiler_directives={'language_level' : "3"}))

然后运行

python setup.py build_ext --inplace

video_test.py

import video_python
import video_cython
import time
number = 100000

start = time.time()
video_python.function(number)
end = time.time()

py_time = end - start
print("Python time = {}".format(py_time))

start = time.time()
video_cython.function(number)
end = time.time()

cy_time = end - start
print("Cython time = {}".format(cy_time))

print("Speedup = {}".format(py_time / cy_time))

结果:

Python increment 3

Python time = 6.602917671203613

Cython increment 3

Cython time = 0.4903101921081543

Speedup = 13.466817083311046

所以在循环中做任何与 python 相关的事情都可以提高速度

关于python - Cython + OpenCV 和 NumPy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50535498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com