Jump to content

Image Colour Count with Python

A python-based tool for image colour count extraction.

Image 1: Sample image for colour analysis (left) and resulting histogram with the background colour ignored (right)

Asset Description

Extract colours count from an image using tools commonly available in Python: PIL for image reading and numpy.

Asset Details

Technical Information

The implemented asset is a python script to count the occurrence of every colour in an image. The colour count is either the count of each colour present in the shape, or the count of the occurrences of the specified reference colours: if reference colours are specified, each pixel colour is counted as the closest reference colour instead as a separate colour.

Usage

In order to use the implemented algorithm, the user has to start by downloading the script. After that, the following variables can be set:

  • input_folder: set the folder containing the images for which the colour count should be computed. Defaults to the directory the script is executing;
  • output_folder: set the folder to save the computation results. Defaults to the directory the script is executing;
  • optionally set the reference colours, if needed. Other colours different from the specified reference colours will be counted as the most similar reference colour. If no reference colour is specified, each colour is counted as is. Reference colours should be specified as <colour_name>: (R, G, B);
  • optionally set which colours should be ignored, e.g. the background, so that their value does not get included in the histogram computation. Reference colours should be specified as tuples of (R, G, B);
  • optionally set the threshold to avoid plotting colours with an occurrence lower than such threshold. Please note that occurrences will still be computed for every colour, only the plot is affected.
  • Execute the script. The script will read the images contained in the folder specified in input_folder and for each of them it will produce in output_folder a JSON file containing the absolute and relative frequency for each colour. It will also generate a histogram for each image with the colours' occurrences. If a threshold is defined, only the histograms related to the colours whose relative frequency is above it will be displayed.

    Maturity

    Well-established: development has reached a satisfying level of maturity and performs its task completely. No further development is planned in the future. The script will only see eventual maintenance intervention if improvement is deemed necessary.

    Licence

    Mozilla Public Licence v2.0 - MPL 2.0

    Resources

    Acknowledgement

    This work was performed as part of the PERNOUD pilot in the context of the AI REDGIO 5.0 project

    Relevant Categories