using MvvmScaffoldFrame48.DLL.ImageAlgorithm; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using System.Windows.Media.Imaging; using System.Xml.Linq; using VisionDesigner.MVDCNNDetect; namespace MvvmScaffoldFrame48.ViewModel.ViewModel { public class DeepObjectDetectClass : BaseViewModel { #region 界面绑定属性 private BitmapImage _showImage; public BitmapImage ShowImage { get { return _showImage; } set { if (_showImage != value) { _showImage = value; OnPropertyChanged(nameof(ShowImage)); } } } #endregion #region 界面绑定事件 public ICommand TestCommand{ get; set; } #endregion #region 属性 private CPUDeepObjectDetectClass cPUDeepObject = new CPUDeepObjectDetectClass(); #endregion #region 绑定用Action方法 public void Test(object obj) { // 创建一个 Bitmap 对象 Bitmap bitmap = new Bitmap("D:\\work\\MvvmScaffoldFrame48\\MvvmScaffoldFrame48\\MvvmScaffoldFrame48\\testfile\\testimage\\2025-08-04-13-28-45-807.jpg"); cPUDeepObject.LoadImage(bitmap); cPUDeepObject.LoadDeepModel("D:\\work\\MvvmScaffoldFrame48\\MvvmScaffoldFrame48\\MvvmScaffoldFrame48\\testfile\\model\\Detect_20250818T1328175385.bin"); var result = cPUDeepObject.RunDetect(); PrintRectToBitmap(result, ref bitmap); // 将 Bitmap 转换为 BitmapImage BitmapImage bitmapImage = ConvertToBitmapImage(bitmap); ShowImage = bitmapImage; } #endregion #region 绑定用Predicate方法 private bool CanTrue(object obj) { return true; } private bool CanFalse(object obj) { return false; } #endregion #region 其他方法 public DeepObjectDetectClass() { TestCommand = new RelayCommand(Test, CanTrue); } // Bitmap 转 BitmapImage 的辅助方法 private BitmapImage ConvertToBitmapImage(Bitmap bitmap) { using (MemoryStream memory = new MemoryStream()) { bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png); memory.Position = 0; var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.DecodePixelWidth = 1440; // 设置目标分辨率宽度 bitmapImage.DecodePixelHeight = 1080; // 保持宽高比 bitmapImage.StreamSource = memory; bitmapImage.EndInit(); return bitmapImage; } } public void PrintRectToBitmap(List RectData , ref Bitmap bitmap) { using (Graphics g = Graphics.FromImage(bitmap)) { var redPen = new Pen(Color.Red, 2); var GreenPen = new Pen(Color.SeaGreen, 2); foreach (var item in RectData) { int roix = Convert.ToInt32(item.Box.CenterX - (item.Box.Width/2)); int roiy = Convert.ToInt32(item.Box.CenterY - (item.Box.Height/2)); g.DrawRectangle(item.LabelName== "A坏药"?redPen:GreenPen, new Rectangle(roix, roiy, (int)item.Box.Width, (int)item.Box.Height)); } } } #endregion } }