简体   繁体   中英

How to speed up convolution like function in Python?

I am using the convolution code from here but instead of having the result of the convolution be k = (roi * K).sum() I want to be able to change the operation applied to the (roi * K) . For instance: np.std(roi * K) or min(roi * K) .

Unfortunatelly this code is not optimized to run fast, and I wanted it to go faster.

I tried to find an already implemented method like this but I didn't find any. If there is anything like this out there with fast execution that would be great. If not what would be the best strategy to optimize this code?

Tweaking the code a bit to print the execution time this is the result:

[INFO] applying small_blur kernel
Convolve Time: 2.21276
OpenCV Time: 0.00088
Ratio Convolve/OpenCV: 2519.95248
[INFO] applying large_blur kernel
Convolve Time: 2.50598
OpenCV Time: 0.00611
Ratio Convolve/OpenCV: 410.16292
[INFO] applying sharpen kernel
Convolve Time: 2.10106
OpenCV Time: 0.00027
Ratio Convolve/OpenCV: 7750.65084
[INFO] applying laplacian kernel
Convolve Time: 2.10883
OpenCV Time: 0.00019
Ratio Convolve/OpenCV: 11111.88317
[INFO] applying sobel_x kernel
Convolve Time: 2.16267
OpenCV Time: 0.00021
Ratio Convolve/OpenCV: 10474.46882
[INFO] applying sobel_y kernel
Convolve Time: 2.09571
OpenCV Time: 0.00022
Ratio Convolve/OpenCV: 9513.05519
[INFO] applying emboss kernel
Convolve Time: 2.10961
OpenCV Time: 0.00026
Ratio Convolve/OpenCV: 8125.21671

You can try looking at numba

Numba translates Python functions to optimized machine code at runtime using the industry-standard LLVM compiler library. Numba-compiled numerical algorithms in Python can approach the speeds of C or FORTRAN.

If your code is numerically orientated (does a lot of math), uses NumPy a lot and/or has a lot of loops, then Numba is often a good choice. In these examples we'll apply the most fundamental of Numba's JIT decorators, @jit, to try and speed up some functions to demonstrate what works well and what does not.

You can install it by

$ pip install numba

and usage is as simple as calling the @jit decorator on top of your functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM