XAML:
代码语言:javascript复制<Window x:Class="WpfApp6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp6"
mc:Ignorable="d"
Title="MainWindow" Height="500" Width="400" Loaded="Window_Loaded">
<Grid ShowGridLines="True" >
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Row="0" Grid.Column="0" Name="image1" Source="C:UsersadminsourcereposWpfApp6WpfApp6binDebug11.jpg"/>
<Image Grid.Row="0" Grid.Column="1" Name="image2" />
<Image Grid.Row="1" Grid.Column="0" Name="image3" />
<Image Grid.Row="1" Grid.Column="1" Name="image4" />
</Grid>
</Window>
wpf代码:
- 首先要在nuget上安装emgucv
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using System;
using System.Windows;
using System.Drawing;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WpfApp6
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
{
IntPtr hBitmap = bitmap.GetHbitmap();
ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
if (!DeleteObject(hBitmap))
{
throw new System.ComponentModel.Win32Exception();
}
return wpfBitmap;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Rectangle rectangle = new Rectangle(100, 100, 212, 564);//int x, int y, int width, int height
/***加载image类型图片剪裁显示到wpf image控件 ***/
Image<Bgr, byte> Img = new Image<Bgr, byte>(new Bitmap(@"C:UsersadminsourcereposWpfApp6WpfApp6binDebug11.jpg"));//路径声明
Image<Bgr, byte> Sub1 = Img.GetSubRect(rectangle);
image2.Source = ChangeBitmapToImageSource(Sub1.ToBitmap());
/***加载mat类型图片剪裁显示到wpf image控件***/
Mat SCr = new Mat(@"C:UsersadminsourcereposWpfApp6WpfApp6binDebug22.jpg", LoadImageType.AnyColor);
image3.Source = ChangeBitmapToImageSource(SCr.Bitmap);
Image<Bgr, byte> Sub2 = SCr.ToImage<Bgr, byte>().GetSubRect(rectangle);
image4.Source = ChangeBitmapToImageSource(Sub2.ToBitmap());
}
}
}
运行结果: