我正在看C#中的一個項目,看看圖像文件不確定的擴展,並注意到RGB值,如果它太黑暗將其移動到我的另一個文件夾看看以後獲取圖像的RGB值,並可能移動圖像文件在C#
所以這裏以方框圖的形式
加載多個圖片來自目錄>檢查每一個文件的RGB值>如果太暗>移動到不同的文件夾。如果不忽略(在原來的文件夾中保留)
我知道像從get目錄獲取文件但檢查整個圖片的RGB值,然後移動它或忽略它的基礎知識我很難過。
我有這樣的代碼:
private void button1_Click(object sender, EventArgs e)
{
CompareImages(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "checked"), 127.0, new string[] {"*.jpg", "*.png"});
}
private void CompareImages(string sourceFolder, string disposedImgFolder, double threshold, string[] extensions)
{
if (Directory.Exists(sourceFolder))
{
DirectoryInfo dir = new DirectoryInfo(sourceFolder);
List<FileInfo> pictures = new List<FileInfo>();
foreach (string ext in extensions)
{
FileInfo[] fi = dir.GetFiles(ext);
pictures.AddRange(fi);
}
Directory.CreateDirectory(disposedImgFolder);
int j = 0;
if (pictures.Count > 0)
{
for (int i = 0; i < pictures.Count; i++)
{
Image img = null;
Bitmap bmp = null;
try
{
img = Image.FromFile(pictures[i].FullName);
bmp = new Bitmap(img);
img.Dispose();
double avg = GetAveragePixelValue(bmp);
bmp.Dispose();
if (avg < threshold)
{
string dest = Path.Combine(disposedImgFolder, pictures[i].Name);
if (File.Exists(dest) == false)
{
pictures[i].MoveTo(dest);
j++;
}
else
{
}
}
else
{
}
}
catch
{
if (img != null)
img.Dispose();
if (bmp != null)
bmp.Dispose();
}
}
MessageBox.Show("Done, " + j.ToString() + " files moved.");
}
}
}
private unsafe double GetAveragePixelValue(Bitmap bmp)
{
BitmapData bmData = null;
try
{
bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
int stride = bmData.Stride;
IntPtr scan0 = bmData.Scan0;
int w = bmData.Width;
int h = bmData.Height;
double sum = 0;
long pixels = bmp.Width * bmp.Height;
byte* p = (byte*)scan0.ToPointer();
for (int y = 0; y < h; y++)
{
p = (byte*)scan0.ToPointer();
p += y * stride;
for (int x = 0; x < w; x++)
{
double i = ((double)p[0] + p[1] + p[2])/3.0;
sum += i;
p += 4;
}
}
bmp.UnlockBits(bmData);
double result = sum/(double)pixels;
return result;
}
catch
{
try
{
bmp.UnlockBits(bmData);
}
catch
{
}
}
return -1;
}
如何定義的threashold?
您必須指定「太黑」的含義。您是否想將所有像素亮度值的平均值與閾值進行比較?這會忽略高對比度圖像中的黑暗區域... – foowtf
太黑我的意思是圖像的RGB值爲黑色或類似的地方 – Matthew
含義單一黑色像素會使圖像太暗?然後使用弗朗西斯的解決方案,如果性能對於您的應用來說不是太重要。 – foowtf