【发布时间】:2016-12-12 21:32:51
【问题描述】:
所以有人帮我制作了这段代码,它会告诉我照片中最常用的颜色:
class PictureAnalysis
{
public static List<Color> TenMostUsedColors { get; private set; }
public static List<int> TenMostUsedColorIncidences { get; private set; }
public static Color MostUsedColor { get; private set; }
public static int MostUsedColorIncidence { get; private set; }
private static int pixelColor;
private static Dictionary<int, int> dctColorIncidence;
public static void GetMostUsedColor(Bitmap theBitMap)
{
TenMostUsedColors = new List<Color>();
TenMostUsedColorIncidences = new List<int>();
MostUsedColor = Color.Empty;
MostUsedColorIncidence = 0;
// does using Dictionary<int,int> here
// really pay-off compared to using
// Dictionary<Color, int> ?
// would using a SortedDictionary be much slower, or ?
dctColorIncidence = new Dictionary<int, int>();
// this is what you want to speed up with unmanaged code
for (int row = 0; row < theBitMap.Size.Width; row++)
{
for (int col = 0; col < theBitMap.Size.Height; col++)
{
pixelColor = theBitMap.GetPixel(row, col).ToArgb();
if (dctColorIncidence.Keys.Contains(pixelColor))
{
dctColorIncidence[pixelColor]++;
}
else
{
dctColorIncidence.Add(pixelColor, 1);
}
}
}
// note that there are those who argue that a
// .NET Generic Dictionary is never guaranteed
// to be sorted by methods like this
var dctSortedByValueHighToLow = dctColorIncidence.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
// this should be replaced with some elegant Linq ?
foreach (KeyValuePair<int, int> kvp in dctSortedByValueHighToLow.Take(10))
{
TenMostUsedColors.Add(Color.FromArgb(kvp.Key));
TenMostUsedColorIncidences.Add(kvp.Value);
}
MostUsedColor = Color.FromArgb(dctSortedByValueHighToLow.First().Key);
MostUsedColorIncidence = dctSortedByValueHighToLow.First().Value;
}
}
我正在尝试这样实现,但我真的不知道该怎么做才能向我展示最常用的颜色?
string filep = @"C:\Users\User\Desktop\Gallery\image" + NumberOfClick.ToString() + "cropped.png";
Bitmap bMap = Bitmap.FromFile(filep) as Bitmap;
PictureAnalysis.GetMostUsedColor(bMap);
我想从这样一张“真实”照片中确定最常用的颜色:I am cropping her "jacket" from the photo and I want a program that determines it as it is black
【问题讨论】:
-
你想怎么展示?
-
作为字符串,就像在消息框中一样
-
MessageBox.Show("Most used color is " + PictureAnalysis.MostUsedColor.ToString());...但说真的。你想如何显示这种颜色?显示一个新对话框,把它放在 UI 中的某个地方(比如用这种颜色填充的矩形)? -
在这种情况下,给它一个颜色返回类型,或者使用
Color作为ref变量。然后您可以将textBox文本更改为theColor.r.ToString() + " " + theColor.g.ToString() + " " + theColor.b.ToString(); -
@m.rogalski 我试过这种方式,但它显示在任何照片上 Color[A=0; R=0; G = 0; B =0] 我想要红色、蓝色等。
标签: c#