gpt4 book ai didi

c# - 获取图像的RGB值并可能在C#中移动图像文件

转载 作者:太空宇宙 更新时间:2023-11-03 16:39:31 24 4
gpt4 key购买 nike

我正在考虑用 C# 做一个项目,该项目查看一个尚未确定扩展名的图像文件,并记下 RGB 值,如果它太暗则将其移动到另一个文件夹供我稍后查看

所以这里是 block 形式

从目录加载多个图像 > 检查每个文件的 RGB 值 > 如果太暗 > 移动到不同的文件夹。如果不忽略(保留在原始文件夹中)

我知道基本知识,例如从目录获取文件,但检查整张图片的 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;
}

如何定义阈值?

最佳答案

如果要读取图像的每个像素,必须将其转换为位图。然后您可以使用 GetPixel 方法。但是,这个过程非常慢并且需要大量的 CPU。如果这样做,您确实应该先进行一些测试。

        using (var m = new MemoryStream())
{
using (var img = Image.FromFile(args[0]))
{
img.Save(m, ImageFormat.Bmp);
}

m.Position = 0;

using (var bitmap = (Bitmap)Bitmap.FromStream(m))
{
for (var x = 0; x < bitmap.Width; x++)
{
for (var y = 0; y < bitmap.Height; y++)
{
var color = bitmap.GetPixel(x, y);

// TODO: Do what ever you want
}
}
}
}

关于c# - 获取图像的RGB值并可能在C#中移动图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8111819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com