Contents

kMeans()

Applies the k-means algorithm to find the most common colors in an image.

Declaration

class func kMeans() -> any CIFilter & CIKMeans

Return Value

A one-dimensional CIImage containing the colors.

Discussion

This filter uses the k-means clustering algorithm to find the most common colors in an input image. The result is a CIImage with count x 1 dimensions. Each RGBA pixel in the result image represents the center of a k-means cluster. The RGB components contain the color and the alpha component represents the weight of the color. You typically use the kMeans() filter in conjunction with the palettize() filter to produce an image with a reduced number of colors.

inputImage

A CIImage to process.

extent

A CGRect specifying the area of the image to analyze.

means

An optional CIImage containing a set of colors to use as seeds for the k-means clustering.

count

The number of k-means color clusters that should be created. Maximum is 128, and default is 8.

passes

The number of k-means passes that should run. Maximum is 20, and default is 5.

perceptual

Whether the k-means color palette should use a perceptual color space.

The following code example uses the kMeans() filter followed by the palettize() filter to reduce the colors in the image to four:

func kMeans(inputImage: CIImage) -> CIImage {
    let filter = CIFilter.kMeans()
    filter.inputImage = inputImage
    filter.extent = inputImage.extent
    filter.count = 4
    filter.passes = 5
    return filter.outputImage!
}

func palettize(inputImage: CIImage, paletteImage: CIImage) -> CIImage {
    let palettize = CIFilter.palettize()
    palettize.inputImage = inputImage
    palettize.paletteImage = paletteImage
    return palettize.outputImage!
}

let palette = kMeans(inputImage: image)
let palettized = palettize(inputImage: image, palette.settingAlphaOne(in: palette.extent))

[Image]

See Also

Filters