Python converting an image to use less colors

后端 未结 2 796
無奈伤痛
無奈伤痛 2021-01-07 02:05

I want to take an image and (somehow) read it as an array of pixels. Meaning each element of the 2d array would be either a hex code or RGB 3-tuple that represent the color

2条回答
  •  一向
    一向 (楼主)
    2021-01-07 03:04

    Library (libraries) to use?

    scikit-image or OpenCV would be my preferred choices.

    Methods? (Are there any widely used algorithms for this kind of problem?)

    K-means clustering is a popular approach to color quantization.

    Am I using the wrong programming language? (Is there one that offers this kind of functionality but easier to use?)

    Python is arguably the "easiest" language for this task.

    DEMO

    Consider this image:

    The following code reduces the number of colors from +500K to only 6:

    import numpy as np
    from skimage import io
    from sklearn.cluster import KMeans
    
    original = io.imread('https://i.stack.imgur.com/QCl8D.jpg')
    n_colors = 6
    
    arr = original.reshape((-1, 3))
    kmeans = KMeans(n_clusters=n_colors, random_state=42).fit(arr)
    labels = kmeans.labels_
    centers = kmeans.cluster_centers_
    less_colors = centers[labels].reshape(original.shape).astype('uint8')
    
    io.imshow(less_colors)
    

    And this is how the color quantized image looks:

提交回复
热议问题