在计算机视觉领域中,图像处理和分析是一个非常重要的应用。OpenCVSharp 是一个使用 C++ 和 .NET 技术实现的开源计算机视觉库,它提供了丰富的图像处理和分析功能。在 OpenCVSharp 中,Mat 是一个基本的图像数据结构,它可以存储任意类型的数据,包括图像数据。Mat 对象是一个多维数组,其中每个元素都表示一个像素。Mat 对象提供了很多有用的方法,可以方便地读取和修改图像的像素值。 在 OpenCVSharp 中,可以使用 Mat 对象的 .At 方法来读取和修改图像的像素值。这个方法的第一个参数是要读取或修改的像素的位置,可以是行号和列号,也可以是二进制格式的偏移量。
正文
nuget 安装 OpenCVSharp
这里OpenCvSharp4.runtime.win 库需要引用,不然会报错
DllNotFoundException: Unable to load DLL 'OpenCvSharpExtern' or one of its dependencies
OpenCvSharp.Extensions 库
C#private void btnSet_Click(object sender, EventArgs e)
{
// 读取图像
Mat image = Cv2.ImRead("D:\\Video\\C#logo.jpg", ImreadModes.Color);
// 获取图像尺寸
int width = image.Width;
int height = image.Height;
// 遍历图像像素并进行转换
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
//blue,red,green
Vec3b pixel = image.At<Vec3b>(y, x); // 获取像素值
// 假设你想要将像素值的红色通道增加 50
//pixel.Item2 = (byte)Math.Min(pixel.Item2 + 50, 255); // 增加红色通道
pixel.Item0 = 255;
image.Set(y, x, pixel); // 设置像素值
}
}
Mat newImage = new Mat();
// 保存处理后的图像
pictureBox2.Image = BitmapConverter.ToBitmap(image);
// 释放图像资源
image.Dispose();
pictureBox1.Image = Image.FromFile("D:\\Video\\C#logo.jpg");
}
通过索引修改(速度快)
C#private void btnIndexSet_Click(object sender, EventArgs e)
{
// 读取图像
Mat image = Cv2.ImRead("D:\\Video\\C#logo.jpg", ImreadModes.Color);
Mat.Indexer<Vec3b> indexer = image.GetGenericIndexer<Vec3b>();
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
Vec3b color = indexer[y, x];
byte temp = color.Item0;
color.Item0 = color.Item2; // 蓝 <- 红
color.Item2 = temp; // 红 <- 蓝
indexer[y, x] = color;
}
}
// 保存处理后的图像
pictureBox2.Image = BitmapConverter.ToBitmap(image);
// 释放图像资源
image.Dispose();
pictureBox1.Image = Image.FromFile("D:\\Video\\C#logo.jpg");
}
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!