对于OpenCvSharp的配置网上已经给出了很多教程,在此本人参考在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.Threading.Tasks;
using System.Windows.Forms;
//导入Opencv
using OpenCvSharp;
//Mat转换时需要该模块
using OpenCvSharp.Extensions;
namespace OpenCvSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string nameImage;
private void button1_Click_1(object sender, EventArgs e)
{
//打开(文本框)
OpenFileDialog ofdWenJian = new OpenFileDialog();
//只允许用户选择一个文件
ofdWenJian.Multiselect = false;
//筛选文件类型
ofdWenJian.Filter = "ALL Image Files|*.bmp;*.gif;*.jpg;*.png";
//显示对话框
ofdWenJian.ShowDialog();
//获取图片的绝对路径
nameImage = ofdWenJian.FileName;
if (nameImage == "")
{
MessageBox.Show("未获取到图像路径", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
//关闭当前窗体
this.Close();
return;
}
//在pictrueBox1控件中显示插入的图片
pictureBox1.LoadAsync(nameImage);
}
private void button2_Click(object sender, EventArgs e)
{
//读取图片信息
Mat src = new Mat(nameImage, ImreadModes.Grayscale);
//构造平移矩阵
//T(tx, ty) tx为水平偏移值,ty为垂直偏移值
int tx = 100, ty = 100;
OpenCvSharp.Size size = new OpenCvSharp.Size(3, 2);
Mat translation = Mat.Zeros(size, MatType.CV_32FC1);
translation.Set<float>(0, 0, 1);
translation.Set<float>(0, 2, tx);
translation.Set<float>(1, 1, 1);
translation.Set<float>(1, 2, ty);
Console.Write(translation.Get<float>(0, 0) + ",");
Console.Write(translation.Get<float>(0, 1) + ",");
Console.WriteLine(translation.Get<float>(0, 2));
Console.Write(translation.Get<float>(1,0) + ",");
Console.Write(translation.Get<float>(1,1) + ",");
Console.WriteLine(translation.Get<float>(1,2));
//放射变换
Mat dst = new Mat();
Cv2.WarpAffine(src, dst, translation, src.Size());
//把mat格式的图片转换成bmp;
Bitmap bitmap = BitmapConverter.ToBitmap(dst);
pictureBox2.Image = bitmap;
}
}
}