This code is the Gaussian noise symbol in the photo. There was a speed issue: fhd photo is processed in about 0.45 seconds. This is impermissible for my tasks. I need to reach a speed of at least milliseconds.
import numpy as np
import cv2
image = cv2.imread('1.jpg')
row,col,ch= image.shape
mean = 0
var = 0.1
sigma = var**0.5
gauss = np.random.normal(mean,sigma,(row,col,ch))
gauss = gauss.reshape(row,col,ch)
noisy = image + gauss
cv2.imwrite('2.jpg', noisy)
Already optimized the slowest part of the code (generating an array of random numbers) (this operation takes about 0.32s):
gauss = np.random.normal(mean,sigma,(row,col,ch))
gauss = gauss.reshape(row,col,ch
I reduced the matrix a hundred times, and then multiplied it a hundred times:
roww=int(row/100)
b = timeit.default_timer()
gauss = np.random.normal(mean,sigma,(roww,col,ch))
gauss = gauss.reshape(roww*col*ch)
gauss = np.tile(gauss, 100)
gauss = gauss.reshape(row,col,ch)
The code above takes 20ms, of which the most time is spent multiplying one matrix into a large one (18ms):
gauss = np.tile(gauss, 100)
How could you make this operation faster?
And now to the main problem: all this code still takes a very long time (170ms), the most time-consuming operations:
Adding matrices takes 30ms.
noisy=image+gauss
Opening (35ms)
image = cv2.imread("1.jpg"
and saving (90ms) photo:
cv2.imwrite('2.jpg', noisy)
Is it possible to speed up these operations in any way in python? Thanks!
Full code:
import numpy as np
import cv2
image = cv2.imread('1.jpg')
row,col,ch= image.shape
mean = 0
var = 0.1
sigma = 10
roww=int(row/100)
gauss = np.random.normal(mean,sigma,(roww,col,ch))
gauss = gauss.reshape(roww*col*ch)
gauss = np.tile(gauss, 100)
gauss = gauss.reshape(row,col,ch)
noisy=image+gauss
cv2.imwrite('2.jpg', noisy)
numbalibrary, it's compatible with numpy but includes JIT compilation and the ability to run CUDA code, might make it faster. Also see if you could pre-generate a few of those random matrices and keep them around in RAM instead of making a new one every time.