Home > Net >  Measure image sharpness with opencv using gpu
Measure image sharpness with opencv using gpu

Time:01-15

I created a small script that extract the most sharp image from a set of images using Laplacian like that:

sharpness = cv2.Laplacian(cv2.imread(path), cv2.CV_64F).var()

However the code is a bit slow and it seems to only use CPU, then I'm wondering if there's a method that uses the gpu to calculate that value, but only find example to sharpen an image.

CodePudding user response:

Don't optimize before you know what is taking time.

Most time is spent on loading the image. Time it, you'll see. This involves accessing mass storage and decoding the image format. PNG isn't the most complex out there, so it could be worse.

The laplacian calculation uses a specific kernel. Convolving the picture with an arbitrary 3x3 kernel would cost 9 multiplications and 9 additions. This kernel costs one shift and five adds/subs. The CPU's SIMD will eat this for breakfast.

A GPU won't help at all. It takes time to transfer this data to the GPU. Then there are other constant costs (latency, "warm-up") to starting any calculations on a GPU. A CPU would already be done calculating. If you had a ton of pictures, at least the transfer could be pipelined and the upload of kernel code would only be required once.

Both the GPU and the CPU are likely memory-bound in this entire operation, meaning compute capability is far from challenged by this.

If you really wanted to get a GPU involved, the easiest way would be to wrap the numpy array in a cv.UMat and pass the UMat object in instead. OpenCV will then use OpenCL. The result will be a UMat again, so you would need to see what OpenCV function can calculate the variance for you.

h_im = cv.imread(...) # hostside data
d_im = cv.UMat(im) # usable on "device"
d_lap = cv.Laplacian(d_im, cv.CV_32F) # single floats are usually faster than doubles
h_lap = d_lap.get() # retrieve data
# numpy functions unavailable on UMat, hence hostside calculation
var = h_lap.var()
# try cv.meanStdDev, calculates for each channel
  •  Tags:  
  • Related