Perform Thresholding and Morphological Operations on GPU
This example shows how to perform image processing operations on a GPU. The example uses filtering to highlight the watery areas in an aerial photograph.
Read and display an image.
imOriginal = imread("concordaerial.png"); imshow(imOriginal)
Move the image to the GPU by creating a
gpuArray (Parallel Computing Toolbox) object.
imGPUoriginal = gpuArray(imOriginal);
As a preprocessing step, change the RGB image to a grayscale image.
im2gray performs the conversion operation on a GPU because the input argument is a
imGPUgray = im2gray(imGPUoriginal);
View the image in the Image Viewer app and inspect the pixel values to find the value of watery areas. To use Image Viewer, you must bring the image data back onto the CPU by using the
gather (Parallel Computing Toolbox) function. As you move the mouse over the image, you can view the value of the pixel under the cursor at the bottom of the Image Viewer. In the image, areas of water are dark and have pixel values less than 70.
To get a new image that contains only the pixels with values less than 70, threshold the image on the GPU.
imWaterGPU = imGPUgray<70;
Display the thresholded image. Unlike Image Viewer, the
imshow function supports
Remove small objects from the image while preserving the shape and size of larger objects by using morphological opening. The
imopen function performs morphological opening and supports
imWaterMask = imopen(imWaterGPU,strel("disk",5)); imshow(imWaterMask)
Create a copy of the original image that will contain the enhanced data. Convert the data type to
imGPUenhanced = im2single(imGPUoriginal);
Get the blue channel from the original image.
blueChannelOriginal = imGPUenhanced(:,:,3);
Enhance the saturation of the blue channel by increasing the strength of the blue channel for pixels where the mask is
blueChannelEnhanced = blueChannelOriginal + 0.2*single(imWaterMask);
The maximum value of the enhanced blue channel exceeds the maximum value expected of images of data type
single. Rescale the data to the expected range [0, 1] by using the
blueChannelEnhanced = rescale(blueChannelEnhanced);
Replace the blue channel with the enhanced blue channel.
imGPUenhanced(:,:,3) = blueChannelEnhanced;
Display the enhanced image. Pixels corresponding to water have a more saturated blue color in the enhanced image than in the original image.
imshow(imGPUenhanced) title("Enhanced Image")
After filtering the image on the GPU, move the data back to the CPU by using the
gather function. Write the modified image to a file.
outCPU = gather(imGPUenhanced); imwrite(outCPU,"concordwater.png")
gpuArray (Parallel Computing Toolbox) |
gather (Parallel Computing Toolbox)
- Run MATLAB Functions on a GPU (Parallel Computing Toolbox)
- Functions Supporting GPU Computing