MainWindow.xaml
<Window x:Class="Splash.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="OpenCVの灰度变换" SizeToContent="WidthAndHeight" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Icon="OpenCV.ico">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Grid.Column="0" Margin="4" Padding="16,4" Content="选择图像…" Name="ButtonSelect" Click="ButtonSelect_Click"/>
<Label Grid.Row="1" Grid.Column="0" Margin="4" Background="LightGreen" Content="源图像" HorizontalContentAlignment="Center"/>
<Label Grid.Row="1" Grid.Column="1" Margin="4" Background="LightGreen" Content="灰度图像" HorizontalContentAlignment="Center"/>
<Border Grid.Row="2" Grid.Column="0" Margin="4" BorderBrush="Green" BorderThickness="1">
<Image Width="240" Height="320" Name="ImageRaw"/>
</Border>
<Border Grid.Row="2" Grid.Column="1" Margin="4" BorderBrush="Green" BorderThickness="1">
<Image Width="240" Height="320" Name="ImageTarget"/>
</Border>
</Grid>
</Window>
MainWindow.xaml.cs
/* ----------------------------------------------------------
* 文件名称:MainWindow.xaml.cs
*
* 作者:秦建辉
*
* 微信:splashcn
*
* 博客:http://www.firstsolver.com/wordpress/
*
* 开发环境:
* Visual Studio V2017
* .NET Framework 4.7.2
* OpenCvSharp 4.0.30319
*
* 版本历史:
* V1.0 2018年12月27日
* OpenCVの灰度变换
* ---------------------------------------------------------- */
using Com.FirstSolver.Splash;
using OpenCvSharp.Extensions;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
namespace Splash
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ButtonSelect_Click(object sender, RoutedEventArgs e)
{
try
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog
{
Filter = "Image|*.jpg;*.bmp;*.png;*.tif;*.tga;*.ras;*.jp2;*.j2k;*.jpe",
DereferenceLinks = true
};
this.CenterChild();
if (dlg.ShowDialog(Owner).Value == true)
{
using (FileStream fs = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{ // 读取图像内容
byte[] data = new byte[fs.Length];
fs.Read(data, 0, (int)fs.Length);
// 显示源图像
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(data);
bi.EndInit();
ImageRaw.Source = bi;
// 显示灰度图像
OpenCvSharp.Mat GrayMat = OpenCvSharp.Cv2.ImDecode(data, OpenCvSharp.ImreadModes.Grayscale);
ImageTarget.Source = GrayMat.ToBitmapSource();
}
}
}
catch (System.Exception exception)
{
MessageBoxPlus.Show(this, exception.Message, "图像文件异常", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
运行结果
