C# WPF 显示图片和视频显示 EmuguCv、AForge.Net测试
原文:C# WPF 显示图片和视频显示 EmuguCv、AForge.Net测试

WPF 没有用到 PictureBox, 而是用Image代替.

下面我试着加载显示一个图片 。

XAML

<Image x:Name="srcImg"Width="400"Height="300"></Image>

CS Attempt 1:

Image<Bgr,Byte>My_Image=newImage<Bgr,byte>(Openfile.FileName);
srcImg.Source=My_Image.ToBitmap();

Error Message

Cannot implicitly convert type 'System.Drawing.Bitmap'
to 'System.Windows.Media.ImageSource'

CS Attempt 2:

Image<Bgr,Byte>My_Image=newImage<Bgr,byte>(Openfile.FileName);
srcImg.Source=newBitmapImage(My_Image);

Error Message

Error1The best overloaded method match for'System.Windows.Media.Imaging.BitmapImage.BitmapImage(System.Uri)' has some invalid arguments
Error2Argument1: cannot convert from'Emgu.CV.Image<Emgu.CV.Structure.Bgr,byte>' to 'System.Uri'

解决方法:
Image<Bgr, Byte> My_Image = new Image<Bgr, byte>(Openfile.FileName);
srcImg.Source = BitmapSourceConvert.ToBitmapSource(myImage);

public static class BitmapSourceConvert
{[DllImport("gdi32")]private static extern int DeleteObject(IntPtr o);public static BitmapSource ToBitmapSource(IImage image){using (System.Drawing.Bitmap source = image.Bitmap){IntPtr ptr = source.GetHbitmap();BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ptr,IntPtr.Zero,Int32Rect.Empty,System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());DeleteObject(ptr);return bs;}}
}

测试:

 Bitmap bm = (Bitmap)Bitmap.FromFile(@"D:\my_testfiles\Main.png");int count = 10000000;for (int i = 0; i < count; i++){Commons.BitMapToImageSource(bm.Clone() as Bitmap);}

结果:

当循环 1527次,  耗时 00:00:17.8860231后  报错。

ErrorTrace:
 at System.Drawing.Bitmap.GetHbitmap(Color background)at System.Drawing.Bitmap.GetHbitmap()at SimpleClient.Commons.BitMapToImageSource(Bitmap bitmap) in D:\my_svn\universal-project\SimpleClient\Program.cs:line 165

ErrorMessage:

system.OutOfMemoryException: Out of memory.

改进:

写一个视频显示控件,内部实现显示Bitmap转换成BitmapSource。为控件Source开辟一块内存控件,然后一直刷新。首先我们使用EmuguCV里面的Capture。控件继承Image、IDisposable接口并开放一个属性VideoSource。
代码如下:
    public class CapPlayer : Image, IDisposable{private Capture videoSource;public Capture VideoSource{set{if (value != null){this.videoSource = value;this.LaodCapPlayer();}}}private InteropBitmap bitmapSource;private IntPtr map;private IntPtr section;public CapPlayer(){Application.Current.Exit += new ExitEventHandler(Current_Exit);}private void LaodCapPlayer(){videoSource.ImageGrabbed += new Capture.GrabEventHandler(videoSource_ImageGrabbed);videoSource.Start();uint pcount = (uint)(videoSource.Width * videoSource.Height * PixelFormats.Bgr32.BitsPerPixel / 8);section = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, pcount, null);map = MapViewOfFile(section, 0xF001F, 0, 0, pcount);bitmapSource = Imaging.CreateBitmapSourceFromMemorySection(section, (int)videoSource.Width, (int)videoSource.Height, PixelFormats.Bgr32,(int)(videoSource.Width * PixelFormats.Bgr32.BitsPerPixel / 8), 0) as InteropBitmap;this.Source = bitmapSource;}void videoSource_ImageGrabbed(object sender, EventArgs e){Capture camera = sender as Capture;var frame = camera.RetrieveBgrFrame().Bitmap;if (this.Dispatcher != null){this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Render, (SendOrPostCallback)delegate{if (map != IntPtr.Zero){try{System.Drawing.Imaging.BitmapData bmpData = frame.LockBits(new System.Drawing.Rectangle(0, 0, (int)videoSource.Width, (int)videoSource.Height),System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppRgb);/* Get the pointer to the pixels */IntPtr pBmp = bmpData.Scan0;int srcStride = bmpData.Stride;int pSize = srcStride * (int)videoSource.Height;CopyMemory(map, pBmp, pSize);frame.UnlockBits(bmpData);}catch (Exception ex){Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(ex, "Info", 0);}}if (bitmapSource != null){bitmapSource.Invalidate();}}, null);}if (captureLock){try{lock (mutCurrentImg){camera.RetrieveBgrFrame().Save(imageFileName);}}catch (System.Exception ex){Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(ex, "Info", 0);}captureLock = false;}}void Current_Exit(object sender, ExitEventArgs e){this.Dispose();}object mutCurrentImg = new object();bool captureLock = false;string imageFileName = string.Empty;public void ImaggingCapture(string imageFileName){this.imageFileName = imageFileName;this.captureLock = true;}#region IDisposable Memberspublic void Dispose(){if (videoSource != null)videoSource.Stop();Application.Current.Exit -= new ExitEventHandler(Current_Exit);}#endregion[DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory")]private static extern void CopyMemory(IntPtr Destination, IntPtr Source, int Length);[DllImport("kernel32.dll", SetLastError = true)]static extern IntPtr CreateFileMapping(IntPtr hFile, IntPtr lpFileMappingAttributes, uint flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);[DllImport("kernel32.dll", SetLastError = true)]static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);}

测试结果:无异常,但是发现比较占用CPU 10%左右,内存 122M 左右,线程数32.

感觉不太理想CPU占用太多,我们把EmuguCV的Capture改为AForge.NEt的VideoCaptureDevice,代码如下:

    public class CapPlayer : Image, IDisposable{private  VideoCaptureDevice videoSource;private InteropBitmap bitmapSource;private IntPtr map;private IntPtr section;public CapPlayer(){Application.Current.Exit += new ExitEventHandler(Current_Exit);this.Loaded += new RoutedEventHandler(CapPlayer_Loaded);videoSource = new VideoCaptureDevice(@"device:pnp:\\?\usb#vid_0ac8&pid_305b#5&ee85354&0&2#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global");  }void CapPlayer_Loaded(object sender, RoutedEventArgs e){videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);videoSource.Start();uint pcount = (uint)(this.Width * this.Height * PixelFormats.Bgr32.BitsPerPixel / 8);section = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, pcount, null);map = MapViewOfFile(section, 0xF001F, 0, 0, pcount);bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromMemorySection(section, (int)this.Width, (int)this.Height, PixelFormats.Bgr32,(int)(this.Width * PixelFormats.Bgr32.BitsPerPixel / 8), 0) as InteropBitmap;this.Source = bitmapSource;}void Current_Exit(object sender, ExitEventArgs e){this.Dispose();}object mutCurrentImg = new object();bool captureLock = false;string imageFileName = string.Empty;public void ImaggingCapture(string imageFileName){this.imageFileName = imageFileName;this.captureLock = true;}private void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs){//eventArgs.Frame.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);if (this.Dispatcher != null){this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Render, (SendOrPostCallback)delegate{if (map != IntPtr.Zero){System.Drawing.Imaging.BitmapData bmpData = eventArgs.Frame.LockBits(new System.Drawing.Rectangle(0, 0, (int)this.Width, (int)this.Height),System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppRgb);/* Get the pointer to the pixels */IntPtr pBmp = bmpData.Scan0;int srcStride = bmpData.Stride;int pSize = srcStride * (int)this.Height;CopyMemory(map, pBmp, pSize);eventArgs.Frame.UnlockBits(bmpData);}if (bitmapSource != null){bitmapSource.Invalidate();}}, null);}if (captureLock){try{lock (mutCurrentImg){eventArgs.Frame.Save(imageFileName);}}catch (System.Exception ex){}captureLock = false;}}#region IDisposable Memberspublic void Dispose(){if (videoSource != null)videoSource.SignalToStop();}#endregion[DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory")]private static extern void CopyMemory(IntPtr Destination, IntPtr Source, int Length);[DllImport("kernel32.dll", SetLastError = true)]static extern IntPtr CreateFileMapping(IntPtr hFile, IntPtr lpFileMappingAttributes, uint flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);[DllImport("kernel32.dll", SetLastError = true)]static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);}

测试结果:无异常,但是发现占用CPU 1%左右,内存 72M 左右,线程数28. 是不是比较理想呢!!

CPU

内存

线程数

EmuguCV

10%左右

122M左右

32

Aforge.Net

1%左右

72M左右

28

我的电脑配置.

摄像头:FrameRate 30,Width 320 Height 240.

电脑型号 戴尔 Precision WorkStation T3400 Tower
操作系统 Windows 7 旗舰版 32位 SP1 ( DirectX 11 )
处理器 英特尔 酷睿2 双核 E8400 @ 3.00GHz
主板 戴尔 0HY553 (英特尔 X38/X48 Express 芯片组 - ICH9R)
内存 4 GB ( 海力士 DDR2 800MHz / 金士顿 DDR2 667MHz )
主硬盘 西数 WDC WD3200AAKS-75L9A0 ( 320 GB / 7200 转/分 )
显卡 Nvidia Quadro NVS 290 ( 256 MB / Nvidia )
显示器 戴尔 DELA04A DELL E170S ( 17.1 英寸 )
光驱 飞利浦-建兴 DVD-ROM DH-16D5S DVD光驱
声卡 Analog Devices AD1984 @ 英特尔 82801I(ICH9) 高保真音频
网卡 博通 BCM5754 NetXtreme Gigabit Ethernet / 戴尔

gdi32.dll

系统文件gdi32.dll是存放在Windows系统文件夹中的重要文件,通常情况下是在安装操作系统过程中自动创建的,对于系统正常运行来说至关重要。除非用户电脑被木马病毒、或是流氓软件篡改导致出现gdi32.dll丢失、缺失损坏等弹窗现象,否则不建议用户对该类文件(gdi32.dll)进行随意的修改。

gdi32.dll是Windows GDI图形用户界面相关程序,包含的函数用来绘制图像和显示文字。

posted on 2018-10-20 14:36 NET未来之路 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/9821618.html

C# WPF 显示图片和视频显示 EmuguCv、AForge.Net测试相关推荐

  1. wpf image控件循环显示图片 以达到动画效果 问题及解决方案

    1>最初方案: 用wpf的image控件循环显示图片,达到动画效果,其实就是在后台代码动态改变Image.Source的值,关键代码: for (int i = 1; i < 601; i ...

  2. WPF DataGrid显示图片的一种方法

    DataGrid中添加图片列 首先创建一个类,设置属性,表示每一行: public class MyDataObject{public int Number { get; set; }public B ...

  3. WPF显示经常使用的几个显示文字控件TextBox, TextBlock, Lable

    WPF显示经常使用的几个显示文字控件TextBox, TextBlock, Lable TextBox, TextBlock. Lable 当中TextBox 和Lable均继承了Control类 能 ...

  4. WPF 把图片分割成两份自动翻页 WpfFlipPageControl:CtrlBook 书控件

    原文:WPF 把图片分割成两份自动翻页 WpfFlipPageControl:CtrlBook 书控件 版权声明:本文为博主原创文章,需要转载尽管转载. https://blog.csdn.net/z ...

  5. qt 关闭窗口的槽函数_勇哥的VC++应用框架学习之QT(1) 信号槽、按钮控件、opencv读取显示图片...

    前言勇哥对于C语言,C++早些年有一些接触,这个系列贴子就记载一下C++应用框架的学习经验. 在写程序时,UI.基础类库.应用程序框架对于vc来讲,只能依靠MFC和QT了. 勇哥对MFC有很强的抵触, ...

  6. WPF 设置图片的分辨率DPI

    WPF 修改图片的分辨率/DPI 在WPF中,当使用到PNG之类的图片作为背景时.我发现一个问题:图片属性(Windows)的宽.高相同的两张图片在WPF界面上显示却大小不一.如下图所示. 在后台应用 ...

  7. 在DataGrid中显示图片

    兼谈 DadaGrid 模板列的创建 DadaGrid 是 ASP.NET 编程中一个很重要的控件,其优良的可定制功能为提高它的表现力提供了极大的方便.除了与数据源直接绑定以外,我们还可以通过列绑定模 ...

  8. python运行完不能显示图_【已解决】Python中通过Image的open之后,去show结果打不开bmp图片,无法正常显示图片...

    [问题] 在windows的cmd命令行下,使用Python的PIL库打开并显示一个jpg图片:openedImg = Image.open(saveToFile); print "open ...

  9. python opencv 拼接 连接 显示 图片

    python opencv 拼接 显示 图片 代码 import cv2 import numpy as np # 读取图片 img1 = cv2.imread('1.jpg',1) # 读取图片 i ...

最新文章

  1. 一条sql导致数据库整体性能下降的诊断和解决的全过程
  2. 天津海尔扫地机器人维修点_女神好帮手!海尔扫地机器人 让生活化繁为简
  3. 将protobuf文档转换成java代码
  4. php伪静态url运用,再谈 THINKPHP 伪静态url(URL访问模式)的设置
  5. python 除法取模_跟我一起学python | 探究05
  6. 平衡二叉树中需要旋转的情况
  7. 浙大 PAT b1017
  8. Windwos Server 2008 R2 DHCP服务
  9. KinectFusion: Real-time 3D Reconstruction and Interaction Using a Moving Depth Camera
  10. PHP array_diff_assoc
  11. akamai 指纹 和 akamai BMP 移动端sensor 风控分析
  12. 【图像去噪】基于matlab改进非局部均值红外图像混合噪声【含Matlab源码 1640期】
  13. fragstats移动窗口
  14. 钽电容和贴片电容的区别
  15. 九、Redis三种集群模式
  16. 从小米雷军的逆天布局你能读出什么?
  17. 【JAVA今法修真】 第七章 洞天风云起,索引混乱平
  18. 人造的风景 --- 东部华侨城一日游感想与收获
  19. Repeater嵌套总结
  20. c语言中1 3.0,1.4.1 先看Turbo C/C++ 3.0(3)

热门文章

  1. php 表单 同步,Jquery点击按钮 异步和同步提交表单
  2. d3.js和mysql_如何从mysql数据库中提取数据并使用D3.JS进行可视化?
  3. 蓝牙信号强度检测app_基于蓝牙技术的智能插座方案
  4. php mysql刷新表格_php读入mysql数据并以表格形式显示(表单实现无刷新提交)
  5. 乐高ev3搭建图_乐高EV3第一讲,Hello Ev3,搭建机甲战神模型
  6. matlab graphic,Matlab图形系统,Matlab Graphic System,音标,读音,翻译,英文例句,英语词典...
  7. mysql的复制订阅_如何删除发布与复制订阅数据库 'distribuion' 的方法
  8. java writablesheet_jxl加边框,jxl合并单元格,单元格的设置,单元格居中
  9. 无线网桥的特点及应用方案
  10. 局域网工业交换机的种类和选择注意事项!