本示例是《OpenCV3编程入门》中6.7.3的示例程序的C# + EMGU 3.4.1版,比较简单,代码如下:
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;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
namespace ThresholdOperation
{
public partial class Form1 : Form
{
int g_nThresholdValue = 100; //Threshold函数阈值
int g_nThresholdType = 3;
Mat srcImage = new Mat();
Mat grayImage = new Mat();
Mat dstImage = new Mat();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//读入原始图片
srcImage = CvInvoke.Imread("landscape.jpg");
if (srcImage.IsEmpty)
MessageBox.Show("读取图片错误,请确定目录下存在imread函数指定的图片!", "Warning");
//显示原始图
imageBox1.Image = srcImage;
//存留一份原图的灰度图
CvInvoke.CvtColor(srcImage, grayImage, ColorConversion.Bgr2Gray);
//Lable初始值显示
Lable_ModeValue.Text = "模式:" + TrackBar_Mode.Value.ToString();
Lable_ThresholdValue.Text = "阈值:" + TrackBar_ThresholdValue.Value.ToString();
//调用threshold函数
on_Threshold();
}
//TrackBar事件,改变thresholdType的值
private void TrackBar_Mode_Scroll(object sender, EventArgs e)
{
//调用threshold函数
on_Threshold();
//Lable内容更新
Lable_ModeValue.Text = "模式:" + TrackBar_Mode.Value.ToString();
}
//TrackBar事件,改变threshold的值
private void TrackBar_ThresholdValue_Scroll(object sender, EventArgs e)
{
//调用threshold函数
on_Threshold();
//Lable内容更新
Lable_ThresholdValue.Text = "阈值:" + TrackBar_ThresholdValue.Value.ToString();
}
//帮助菜单
private void ToolStripMenuItem_OpIntro_Click(object sender, EventArgs e)
{
Form form2 = new Form();
form2.Text = "按键操作说明";
form2.Size = new Size(400, 150);
form2.Show();
RichTextBox rtb = new RichTextBox();
rtb.AppendText("按键【ESC】 - 退出程序\n");
rtb.AppendText("滚动条模式0 - 二进制阈值\n");
rtb.AppendText("滚动条模式1 - 反二进制阈值\n");
rtb.AppendText("滚动条模式2 - 截断阈值\n");
rtb.AppendText("滚动条模式3 - 阈值化为0\n");
rtb.AppendText("滚动条模式4 - 反阈值化为0");
rtb.Dock = DockStyle.Fill;
form2.Controls.Add(rtb);
}
//键盘按键响应
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
MessageBox.Show("程序退出...");
Application.Exit();
}
}
//自定义函数,调用Threshold函数
void on_Threshold()
{
//首先为Threshold函数的参数赋值
g_nThresholdValue = TrackBar_ThresholdValue.Value;
g_nThresholdType = TrackBar_Mode.Value;
//调用阈值函数
CvInvoke.Threshold(grayImage, dstImage, g_nThresholdValue, 255, (ThresholdType)g_nThresholdType);
//显示效果图
imageBox2.Image = dstImage;
}
}
}
程序运行效果如图:
如果需要完整的程序资源,可到如下链接下载: