Main Content

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');

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. rgb2gray performs the conversion operation on a GPU because the input argument is a gpuArray.

imGPUgray = rgb2gray(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 gpuArray input.


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 gpuArray input.

imWaterMask = imopen(imWaterGPU,strel('disk',5));

Create a copy of the original image that will contain the enhanced data. Convert the data type to single.

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 1 (true).

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 rescale function.

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.

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);

See Also

(Parallel Computing Toolbox) | (Parallel Computing Toolbox)

Related Examples

More About