Primary Colors in an image

I am trying to find colors in an image with frequency of more than one time to create a very simple color palette from an input image. To do so, I went this far …

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class ColorAnalyzer : MonoBehaviour
{
    public Texture2D RawImage;

    public Color Color1;
    public Color Color2;
    public Color Color3;
    public Color Color4;
    public Color Color5;

    void Start()
    {
        // getting all the pixels with the mipmap level of 5
        Color[] arrayOfColors = RawImage.GetPixels(5);

        // identifying unique colors
        Color[] distinctColors = arrayOfColors.Distinct().ToArray();
        // subtracting unique colors from the main array
        Color[] colorsWithFrequencyOfMoreThanOne = arrayOfColors.Except(distinctColors).ToArray();

        Debug.Log("ArrayColors lengh: " + arrayOfColors.Length); // console says 512
        Debug.Log("DistinctColors lengh: " + distinctColors.Length); // console says 496
        Debug.Log("colorsWithFrequencyOfMoreThanOne lengh: " + colorsWithFrequencyOfMoreThanOne.Length); // console says 0

    }
}

Does anybody know why my “Except” function does not work and says “null” instead of “16”?

Uhm you have a logic flaw here. distinctColors contains ALL colors you have in your image. However it only contains distinct colors. So duplicates are only counted once.

“Except” returns a new collection based on the incoming color array that only contains elements which do not exist inside the provided array. Since your exclusion array contains all colors the resulting collection will of course be empty. What makes you think that Except only removes each color “once”.

A very simple example:

int[] numbers = new int[]{1,2,5,3,1,5,1,1};
int[] distinctNumbers = new int[]{1,2,3,5};
int[] result = numbers.Except(distinctNumbers); // --> { } empty array

Except grabs all elements from the source collection which are not part of the exclusion list. However as you can see the 0th element “1” is part of the exclusion list. However the 4th, 6th and 7th element is also a “1” and therefore not included in the result.

You can’t simply subtract one array from another. Arrays are not sets. Also if you want to remove the element “5” one time, do you remove the first 5 (element #2) or do you remove the second (element #5)?

You may want to do something like what is explained in this SO answer