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('concordaerial.png'); imshow(I)

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

Igpu = gpuArray(I);

Perform an operation on the GPU. This example defines a custom function calledrgb2gray_customthat 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 thearrayfun(Parallel Computing Toolbox)function.

Igray_gpu = arrayfun(@rgb2gray_custom,...Igpu(:,:,1),Igpu(:,:,2),Igpu(:,:,3));
Caught front-end user exception: MATLAB:m_illegal_character

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

I_gpuresult = gather(Igray_gpu);

Display the result.

imshow(I_gpuresult)

Supporting Function

Thergb2gray_customhelper functions takes a linear combination of three channels and returns a single channel output image.

functiongray = 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