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 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));
Caught front-end user exception: MATLAB:m_illegal_character
Move the data back to the CPU from the GPU by using the gather
(Parallel Computing Toolbox) function.
I_gpuresult = gather(Igray_gpu);
Display the result.
imshow(I_gpuresult)
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
arrayfun
(Parallel Computing Toolbox) | gather
(Parallel Computing Toolbox) | gpuArray
(Parallel Computing Toolbox)