---
title: kMeans()
framework: coreimage
role: symbol
role_heading: Type Method
path: coreimage/cifilter-swift.class/kmeans()
---

# kMeans()

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

## Declaration

```swift
class func kMeans() -> any CIFilter & CIKMeans
```

## Return Value

Return Value A one-dimensional CIImage containing the colors.

## Discussion

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. tip: The colors in the result of the kMeans() filter have an alpha component that indicates the weight of the color. You should set this value one using settingAlphaOne(in:) before using the palette. 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))

## See Also

### Filters

- [areaAverage()](coreimage/cifilter-swift.class/areaaverage().md)
- [areaHistogram()](coreimage/cifilter-swift.class/areahistogram().md)
- [areaLogarithmicHistogram()](coreimage/cifilter-swift.class/arealogarithmichistogram().md)
- [areaMaximum()](coreimage/cifilter-swift.class/areamaximum().md)
- [areaMaximumAlpha()](coreimage/cifilter-swift.class/areamaximumalpha().md)
- [areaMinimum()](coreimage/cifilter-swift.class/areaminimum().md)
- [areaMinimumAlpha()](coreimage/cifilter-swift.class/areaminimumalpha().md)
- [areaMinMax()](coreimage/cifilter-swift.class/areaminmax().md)
- [areaMinMaxRed()](coreimage/cifilter-swift.class/areaminmaxred().md)
- [columnAverage()](coreimage/cifilter-swift.class/columnaverage().md)
- [histogramDisplay()](coreimage/cifilter-swift.class/histogramdisplay().md)
- [rowAverage()](coreimage/cifilter-swift.class/rowaverage().md)
