Main Content

Perform Pixel-Based Operations on GPU

This example shows how to perform pixel-based operations on a GPU by using functions that send both the data and the operations to the GPU for processing. This method is most effective for element-wise operations that require two or more data sets.

Read and display an image.

I = imread("strawberries.jpg");
imshow(I)

Figure contains an axes object. The axes object contains an object of type image.

Move the data from the CPU to the GPU by creating a gpuArray (Parallel Computing Toolbox) object.

Igpu = gpuArray(I);

Perform an operation on the GPU. This example defines a custom function called rgb2gray_custom that converts an RGB image to grayscale by using a custom weighting of the red, green, and blue color channels. This function is defined at the end of the example. Pass the handle to the custom function and data to the GPU for evaluation by the arrayfun (Parallel Computing Toolbox) function.

Igray_gpu = arrayfun(@rgb2gray_custom, ...
    Igpu(:,:,1),Igpu(:,:,2),Igpu(:,:,3));

Move the data back to the CPU from the GPU by using the gather (Parallel Computing Toolbox) function.

Igray = gather(Igray_gpu);

Display the result.

imshow(Igray)

Figure contains an axes object. The axes object contains an object of type image.

Supporting Function

The rgb2gray_custom helper functions takes a linear combination of three channels and returns a single channel output image.

function gray = rgb2gray_custom(r,g,b)
    gray = 0.5*r + 0.25*g + 0.25*b;
end

See Also

(Parallel Computing Toolbox) | (Parallel Computing Toolbox) | (Parallel Computing Toolbox)

Related Examples

More About