SDKs

- iOS 13.0+
- Xcode 11.0+

Framework

- Accelerate

## Overview

In this sample code project, you’ll convert a 3-channel 8-bit ARGB image to a 1-channel grayscale image by using a matrix of coefficients that define the color conversion.

vImage provides matrix multiplication operations that offer functionality analogous to the dot product (that is, returning the sum of the products of the corresponding elements in two vectors). `v`

and `v`

multiply each channel of an interleaved image with a value in a matrix and return the sum of the multiplications to a planar image.

The following shows how `v`

calculates the result for each pixel:

### Define the Coefficient Values

Luma coefficients model an eye’s response to red, green, and blue light. The following formula shows the Rec. 709 luma coefficients for the color-to-grayscale conversion, and it calculates luminance. In the formula, *Y* represents the luminance of the red, green, and blue values:

The following shows how you declare the luma coefficients:

### Define the Coefficients Matrix

`v`

accepts integer values for the matrix; multiply each fractional coefficient in the matrix by `divisor`

:

The matrix multiply function requires an `Int32`

`divisor`

, but the coefficients are `Float`

values. To simplify the matrix initialization, declare and use `f`

to multiply each coefficients by the divisor.

### Perform the Matrix Multiply

The color-to-grayscale calculation is the sum of the products of each color value and its corresponding coefficient, so define pre- and post-bias as zero. Call `v`

to perform the matrix multiplication:

On return, the `destination`

contains a grayscale representation of your original image.

### Create a Grayscale Core Graphics Image

Finally, you can create a 1-channel grayscale `CGImage`

instance from the destination buffer. The image format contains 8 bits per component and 8 bits per pixel. A single channel format has the same number of bits per pixel as bits per component.

To create the image, pass the destination buffer and grayscale format to `create`

:

On return, `result`

contains a single-channel image that you can, for example, use to instantiate a `UIImage`

instance and display onscreen: