C# OpenCvSharp 颜色反转实例详解
作者:乱蜂朝王
OpenCVSharp是OpenCV的.NET wrapper,它比Emgucv更接近于原始的OpenCV,并且有很多的样例参考,其采用LGPL发行,对商业应用友好(基本上相当于BSD),这篇文章主要介绍了C# OpenCvSharp 颜色反转的知识,需要的朋友可以参考下
1、什么是OpenCVSharp
为了解决在Csharp下编写OpenCV程序的问题,我做过比较深入的研究,并且实现了高效可用的方法(GOCW);这几天在搜集资料的时候,偶尔看见了OpenCVSharp,从时间上来看,它已经经过了更久的发展,应该有许多直接借鉴、或者直接使用的地方。
OpenCVSharp有一名日本工程师开发,项目地址为:https://github.com/shimat/opencvsharp。其是OpenCV的.NET wrapper,它比Emgucv更接近于原始的OpenCV,并且有很多的样例参考,其采用LGPL发行,对商业应用友好(基本上相当于BSD)。
2、OpenCVSharp有什么特点
- 直接封装了更多的OpenCV方法,降低了学习的难度,比EmguCV更便于使用
- 大部分继承了IDisposable接口,方便使用using语句
- 可以直接调用原始风格的OpenCV方法
- 可以将图像对象直接转换成GDI使用的Bitmap和WPF的WriteBitmap
- 支持Mono。
在C#中使用OpenCV(使用OpenCVSharp)的实现
效果
灰度图

黑白色反转

彩色反转

项目

代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenCvSharp;
using OpenCvSharp.Extensions;
namespace OpenCvSharp_颜色反转
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
Bitmap bmp;
String imgPath = "";
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = fileFilter;
if (ofd.ShowDialog() != DialogResult.OK) return;
imgPath = ofd.FileName;
bmp = new Bitmap(imgPath);
pictureBox1.Image = bmp;
}
private void button1_Click(object sender, EventArgs e)
{
if (imgPath == "")
{
return;
}
Mat mat = new Mat(imgPath);
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2GRAY);
Mat dst = new Mat(mat.Height, mat.Width, mat.Type(), Scalar.White);
byte grayPixel = 0;
for (int r = 0; r < dst.Rows; r++)
{
for (int c = 0; c < dst.Cols; c++)
{
grayPixel = mat.At<byte>(r, c);
dst.Set<byte>(r, c, (byte)(255 - grayPixel));
}
}
if (pictureBox2.Image != null)
{
pictureBox2.Image.Dispose();
}
pictureBox2.Image = BitmapConverter.ToBitmap(dst);
}
private void button4_Click(object sender, EventArgs e)
{
if (imgPath == "")
{
return;
}
Mat mat = new Mat(imgPath);
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2GRAY);
if (pictureBox2.Image != null)
{
pictureBox2.Image.Dispose();
}
pictureBox2.Image = BitmapConverter.ToBitmap(mat);
}
private void button3_Click(object sender, EventArgs e)
{
if (imgPath == "")
{
return;
}
Mat mat = new Mat(imgPath);
Mat dst = new Mat(mat.Height, mat.Width, mat.Type(), Scalar.White);
Vec3b vec3B;
for (int r = 0; r < dst.Rows; r++)
{
for (int c = 0; c < dst.Cols; c++)
{
vec3B = mat.At<Vec3b>(r, c);
vec3B.Item0 = (byte)(255 - vec3B.Item0);
vec3B.Item1 = (byte)(255 - vec3B.Item1);
vec3B.Item2 = (byte)(255 - vec3B.Item2);
dst.Set<Vec3b>(r, c, vec3B);
}
}
if (pictureBox2.Image != null)
{
pictureBox2.Image.Dispose();
}
pictureBox2.Image = BitmapConverter.ToBitmap(dst);
}
}
}下载
到此这篇关于C# OpenCvSharp 颜色反转的文章就介绍到这了,更多相关C# OpenCvSharp 颜色反转内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
