Search code examples
pythonk-means

function for image's average color using dictionary


I want to calculate average color of image using dictionary image_dict:

import numpy as np 
def average_color(image_dict):

''' A function to compute the average RGB value of an image. First, average over rows to obtain an average value per column. Then, average over the resulting values to obtain one average value per color channel.

image_dict: The dictionary containing the loaded image :return: A 3-dimensional np array: 1 average per color channel '''

return np.array([0,0,0]) 

Solution

  • assuming your image is in image_dict['img'] and it's of a shape (W, L, C) for width, length, and channels you can just average on the first and second axis.

    import numpy as np
    def average_color(image_dict):
        return np.mean(image_dict['img'], axis=(0, 1))
    

    but generally, I wouldn't write a function for that and just use np.mean(image_dict['img'], axis=(0, 1)) where needed.