Problem of the Day
A new programming or logic puzzle every Mon-Fri

Color Finder

Welcome back from the weekend!

We're going to start off the week with an interesting one. Create a function that takes in an image and returns back a list of all the colors in that image. For bonus points return the list in sorted order based on how often each of the colors occurred. Definitely feel free to use libraries such as Pillow to get the data you need.

Permalink: http://problemotd.com/problem/color-finder/

Comments:

  • Ben - 10 years, 2 months ago

    C#

    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Linq;
    
     class Program
     {
         public List<KeyValuePair<Color, int>>  GetColourCount(string file)
        {
            Dictionary<Color, int> colourCount = new  Dictionary<Color, int>();
    
            Bitmap img = new Bitmap(file);
            for (int i = 0; i < img.Width; i++)
            {
                for (int j = 0; j < img.Height; j++)
                {
                    Color pixel = img.GetPixel(i,j);
    
                    if (colourCount.ContainsKey(pixel))
                        colourCount[pixel]++;
                    else
                        colourCount.Add(pixel, 1);
                }
            }
    
            //sort
            List<KeyValuePair<Color, int>> countList = colourCount.ToList();
            countList.Sort((firstPair, nextPair) => { return firstPair.Value.CompareTo(nextPair.Value); } );
    
            return countList;
        }
    }
    

    reply permalink

Content curated by @MaxBurstein