Display video in wpf, flash screen of image control, implement using winform control, wpfwinform
C # Calls the mingw dynamic library to implement video recognition software. The program calls opencv through C ++ to open the video and transmits the original image data to the C # End in rgb24 mode, C # create an image object and assign a value to the control to display the image.
Image:
1 while (true) 2 {3 S_IMG simg = Mingw. display (); // call the image fetch function 4 int size = simg. w * simg. h * 3; 5 byte [] data = new byte [size]; 6 Marshal. copy (simg. pbuf, data, 0, size); 7 Dispatcher. invoke (EventHandler) delegate 8 {9 WriteableBitmap bitmap = new WriteableBitmap (simg. w, simg. h, 100,100, PixelFormats. rgb24, null); 10 bitmap. writePixels (new Int32Rect (0, 0, simg. w, simg. h), data, simg. w * 3, 0); 11 img1.Source = bitmap; 12 BitmapEncoder encoder = new encode BitmapEncoder (); 13 encoder. frames. add (BitmapFrame. create (bitmap); 14 encoder. save (new System. IO. fileStream (pics. toString () + ". jpg ", System. IO. fileMode. create); 15 pics ++; 16}, new object [2]); 17}
Img1 is an image control.
When this method is used to display a video, if the frame rate is too high (an AVI file is opened during the test and there is no latency when reading the frame), the image will flash black. I initially suspected that it was a problem of multi-thread synchronization in some C ++ programs. Later I joined 12th ~ After 15 lines of code, save the image received by C #. The result is that the image is completely OK, that is, a black screen is displayed on the image control. After the debugging is invalid, we decided to use the winform image control.
First, reference it in the project:
System. Windows. Froms
WindowsFormsIntegration
Then add:
Xmlns: wfi = "clr-namespace: System. Windows. Forms. Integration; assembly = WindowsFormsIntegration"
Xmlns: wf = "clr-namespace: System. Windows. Forms; assembly = System. Windows. Forms"
Add:
<WindowsFormsHost Name = "windowsFormsHost1" Grid. Row = "1" Grid. Column = "0">
<Wf: PictureBox Name = "picturebox1"/>
</WindowsFormsHost>
Add:
Public System. Windows. Forms. PictureBox picb1;
Add at initialization:
Picb1 = windowsFormsHost1.Child as System. Windows. Forms. PictureBox;
Show Code:
1 while (true) 2 {3 S_IMG simg = Mingw. display (); // call the image fetch function 4 Dispatcher. invoke (EventHandler) delegate5 {6 System. drawing. bitmap bitmap = new Bitmap (simg. w, simg. h, simg. w * 3, System. drawing. imaging. pixelFormat. format24bppRgb, simg. pbuf); 7 picb1.Image = bitmap; 8}, new object [2]); 9}
The code is much refreshed. However, the pixel formats of wpf and winform images are reversed, so we cannot tell which image is RGB or BGR.