Created
September 23, 2021 19:45
-
-
Save notmarek/cb5e08bcdb3f5f426f6dac19bd2f66fb to your computer and use it in GitHub Desktop.
Code to get the most used color in the middle 100x100 area of an image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using SixLabors.ImageSharp; | |
using SixLabors.ImageSharp.PixelFormats; | |
using SixLabors.ImageSharp.Processing; | |
using System.Collections.Generic; | |
namespace picture_perfet | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Image<Rgba32> img = Image.Load(Console.ReadLine()).CloneAs<Rgba32>(); | |
if (img.Width > 100 && img.Height > 100) | |
img.Mutate(x => x.Crop(new Rectangle((img.Width / 2) - 100, (img.Height / 2) - 100, 100, 100))); | |
Console.WriteLine(img.Size()); | |
// we dont need to go trough the full image as it **should** be 100x100 anyway | |
IDictionary<string, int> colors = new Dictionary<string, int>(); | |
for (int y = 0; y < 100; y++) | |
{ | |
Span<Rgba32> row = img.GetPixelRowSpan(y); | |
for (int x = 0; x < 100; x++) | |
{ | |
Rgba32 pixel = row[x]; | |
string hex_clr = pixel.ToHex(); | |
if (!colors.TryAdd(hex_clr, 1)) | |
{ | |
int amount; | |
colors.TryGetValue(hex_clr, out amount); | |
colors[hex_clr] = amount; | |
} | |
} | |
} | |
KeyValuePair<string, int> most = new KeyValuePair<string, int>("", 0); | |
foreach (KeyValuePair<string, int> color in colors) | |
{ | |
int amount = color.Value; | |
if (amount > most.Value) | |
{ | |
most = color; | |
} | |
} | |
Console.WriteLine("Most pixels are: #" + most.Key); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment