private Mat _sourceMat; //原图对象
///根据路径转换为Mat对象,然后将Mat对象转换为直接数组,最后转换为BitmapImage并显示
private void ReadImage_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (Convert.ToBoolean(ofd.ShowDialog()))
{
string path = ofd.FileName;//获取图像路径
Mat image = Cv2.ImRead(path); //读取图像
byte[] array = image.ToBytes(); //将Mat对象转换为字节数组
BitmapImage bitMapImage = new BitmapImage();
bitMapImage.BeginInit();
bitMapImage.StreamSource = new MemoryStream(array); //字节转换为BitMapImage
bitMapImage.EndInit();
SourceImage.Source = bitMapImage;
_sourceMat = image;
}
}
///通过使用CvtColor函数将彩图转换为灰度图
private void DealImage_Click(object sender, RoutedEventArgs e)
{
Mat aimMat = new Mat(); //初始化一个空的Mat对象
Cv2.CvtColor(_sourceMat, aimMat, ColorConversionCodes.RGB2GRAY) ; //rgb图转换为灰度图
byte[] array = aimMat.ToBytes(); //将Mat对象转换为字节数组
BitmapImage bitMapImage = new BitmapImage();
bitMapImage.BeginInit();
bitMapImage.StreamSource = new MemoryStream(array);
bitMapImage.EndInit();
ConvertImage.Source = bitMapImage;
}
C#使用OpenCV将彩图转换为灰度图
于 2024-03-08 09:39:01 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)