-
Notifications
You must be signed in to change notification settings - Fork 11
GPU calculation with OpenCL
Laurent Thomas edited this page Jun 10, 2020
·
1 revision
OpenCV has a built-in support for OpenCL, which allows to run the calculation on a variety of GPU including built-in graphic adapter.
This does not require a CUDA-capable device. CUDA is not activated by default in this compiled OpenCV.
To run some code on GPU, one just need to convert the Mat object to their UMat equivalent. The opencv function will automatically works with the UMat object "transparently".
Keep in mind though that for small images or only few operations, the calculation on GPU might actually be longer than its CPU equivalent due to the time needed to transfer the image back and forth between the GPU and CPU.
Here is a Fiji jython snippet showing some example of calculation with OpenCL.
#@ImagePlus imp
import org.bytedeco.javacpp.opencv_core as cv2
from org.bytedeco.javacpp.opencv_imgproc import blur
from ijopencv.ij import ImagePlusMatConverter as ImpToMat
from ijopencv.opencv import MatImagePlusConverter as MatToImp
from ij import ImagePlus
# Check that has opencl and use it
print "Has opencl: ", cv2.haveOpenCL()
print "Use opencl: ", cv2.useOpenCL()
# Get device name
dev = cv2.Device.getDefault()
name = dev.name()
print "OpenCL device: ", name.getString()
# I - Convert the ImagePlus to an opencv matrix
imCV = ImpToMat.toMat(imp.getProcessor())
#print imCV
# Classical CPU processing
blured = cv2.Mat() # allocate free Mat
kernel = cv2.Size(5,5)
blur(imCV, blured, kernel)
print "OpenCV Mat: ", blured
# Processing on GPU using OpenCL
#imCL = cv2.UMat(imCV) # Convert to UMat - this works in pure python, but not for Java apparently
imCL = imCV.getUMat(cv2.ACCESS_READ) # Convert to UMat - alternative in java
bluredCL = imCL.clone() # Assign UMat memory (same size and type)
blur(imCL, bluredCL, kernel)
print "OpenCV UMat", bluredCL
# UMat back to Mat
bluredCV = bluredCL.getMat(cv2.ACCESS_READ)
# Display convert UMat in Fiji
imProc = MatToImp.toImageProcessor(bluredCV)
impNew = ImagePlus("testCL", imProc)
impNew.show()