在winform设计器托一个PictureBox、一个按钮,界面如下:
代码
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 OpenCvSharp; //引入opencv
using OpenCvSharp.Extensions; //Mat转换时需要该模块
namespace PictureBoxShowMat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false; //是否可以选择多个文件
dialog.Title = "请选择文件夹";
dialog.Filter = "所有文件(*.*)|*.*";
dialog.RestoreDirectory = true;
string imgName = "";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
imgName = dialog.FileName;
//读取本地的图片
Mat srcImg = new Mat(imgName, ImreadModes.Color);
//把Mat格式的图片转换成Bitmap
Bitmap bitmap = BitmapConverter.ToBitmap(srcImg);
//显示图片
pictureBox1.Image = bitmap;
}
}
}
}
运行结果
Mat转Bitmap需要调用OPenCVSharp拓展模块OpenCvSharp.Extensions, 调用该模块BitmapConverter类的一些方法即可完成相应的转换,该类声明如下: BitmapConverter类定义了一些静态方法,可以把Mat转为Bitmap, 也可以把Bitmap转为Mat. 来看看转Bitmap的源码,在OpenCVSharp源码中查找BitmapConverter类的实现,ToBitmap的实现如下:
///
/// Converts Mat to System.Drawing.Bitmap
///
/// Mat
///
public static Bitmap ToBitmap(this Mat src)
{
if (src == null)
{
throw new ArgumentNullException(nameof(src));
}
PixelFormat pf;
switch (src.Channels())
{
case 1:
pf = PixelFormat.Format8bppIndexed; break;
case 3:
pf = PixelFormat.Format24bppRgb; break;
case 4:
pf = PixelFormat.Format32bppArgb; break;
default:
throw new ArgumentException("Number of channels must be 1, 3 or 4.", nameof(src));
}
return ToBitmap(src, pf);
}
根据图片的通道数,最终会调用下面这个方法转换
public static unsafe void ToBitmap(this Mat src, Bitmap dst)
{
if (src == null)
throw new ArgumentNullException(nameof(src));
if (dst == null)
throw new ArgumentNullException(nameof(dst));
if (src.IsDisposed)
throw new ArgumentException("The image is disposed.", nameof(src));
if (src.Depth() != MatType.CV_8U)
throw new ArgumentException("Depth of the image must be CV_8U");
//if (src.IsSubmatrix())
// throw new ArgumentException("Submatrix is not supported");
if (src.Width != dst.Width || src.Height != dst.Height)
throw new ArgumentException("");
PixelFormat pf = dst.PixelFormat;
// 1プレーン用の場合、グレースケールのパレット情報を生成する
if (pf == PixelFormat.Format8bppIndexed)
{
ColorPalette plt = dst.Palette;
for (int x = 0; x
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?