Эх сурвалжийг харах

重构棋盘格清晰度分析控件及算法服务

全面重构FocusAnalyzer控件,优化UI与交互,支持ROI绘制/调整/旋转,采用MVVM模式。重写ViewModel,支持图像加载、自动棋盘格检测、分析、导出等命令。算法层拆分为ImageAnalysisService和CheckerboardDetectionService,支持多种清晰度算法和自动棋盘格识别。模型与枚举结构优化,移除冗余类,新增RoiModel、ChessboardInfo等。同步更新项目文件,提升可维护性和扩展性。
孝锋 徐 11 сар өмнө
parent
commit
c809834356

+ 372 - 328
TeamAAS-VM/Controls/FocusAnalyzerControl.xaml

@@ -4,6 +4,7 @@
              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
              xmlns:c="clr-namespace:TeamAAS_VP.ValueConverter"
+             xmlns:enums="clr-namespace:TeamAAS_VP.Enums"
              xmlns:local="clr-namespace:TeamAAS_VP.Controls"
              xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
              xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
@@ -12,6 +13,13 @@
              d:DesignHeight="600"
              d:DesignWidth="800">
     <UserControl.Resources>
+        <!-- 转换器 -->
+        <c:ObjectToVisibilityConverter x:Key="NullToVisibilityConverter" />
+        <c:ObjectToVisibilityConverter x:Key="InvertNullToVisibilityConverter"
+                                       Invert="True" />
+        <c:EnumToBooleanConverter x:Key="EnumToBooleanConverter" />
+        <c:RoiToTextConverter x:Key="RoiToTextConverter" />
+
         <!-- 样式 -->
         <Style x:Key="CardStyle"
                TargetType="Border">
@@ -99,74 +107,113 @@
             <Setter Property="Data"
                     Value="M 0,0 L 5,0 L 2.5,5 Z" />
         </Style>
-        <c:EnumToBooleanConverter x:Key="EnumToBooleanConverter" />
     </UserControl.Resources>
 
     <Grid>
-        <Grid.ColumnDefinitions>
-            <ColumnDefinition Width="*" />
-            <ColumnDefinition Width="280" />
-        </Grid.ColumnDefinitions>
-
-        <!-- 左侧:图像显示区 -->
-        <Border Grid.Column="0"
-                Style="{StaticResource CardStyle}"
-                Margin="10">
-            <Grid>
-                <!-- 图像容器 -->
-                <Grid x:Name="ImageContainer">
-                    <!-- 图像显示 -->
-                    <Image x:Name="ImageDisplay"
-                           Source="{Binding CurrentImage}"
-                           Stretch="Uniform" 
-                           MouseLeftButtonDown="ImageDisplay_MouseLeftButtonDown"
-                           MouseLeftButtonUp="ImageDisplay_MouseLeftButtonUp"
-                           MouseMove="ImageDisplay_MouseMove">
-                        <!--<b:Interaction.Triggers>
-                            <b:EventTrigger EventName="MouseLeftButtonDown">
-                                <b:InvokeCommandAction Command="{Binding ImageMouseDownCommand}" />
-                            </b:EventTrigger>
-                            <b:EventTrigger EventName="MouseMove">
-                                <b:InvokeCommandAction Command="{Binding ImageMouseMoveCommand}" />
-                            </b:EventTrigger>
-                            <b:EventTrigger EventName="MouseLeftButtonUp">
-                                <b:InvokeCommandAction Command="{Binding ImageMouseUpCommand}" />
-                            </b:EventTrigger>
-                        </b:Interaction.Triggers>-->
-                    </Image>
-
-                    <!-- ROI绘制层 -->
-                    <Canvas x:Name="RoiCanvas"
-                            IsHitTestVisible="False">
-                        <!-- ROI矩形(带旋转) -->
-                        <Rectangle x:Name="RoiRectangle"
-                                   Visibility="{Binding ShowRoi, Converter={StaticResource BooleanToVisibilityConverter}}">
-                            <Rectangle.Style>
-                                <Style TargetType="Rectangle">
-                                    <Setter Property="Stroke"
-                                            Value="Red" />
-                                    <Setter Property="StrokeThickness"
-                                            Value="2" />
-                                    <Setter Property="StrokeDashArray"
-                                            Value="4,4" />
-                                    <Setter Property="RenderTransformOrigin"
-                                            Value="0.5,0.5" />
-                                    <Style.Triggers>
-                                        <DataTrigger Binding="{Binding RoiMode}"
-                                                     Value="Draw">
-                                            <Setter Property="StrokeDashArray"
-                                                    Value="2,2" />
-                                        </DataTrigger>
-                                    </Style.Triggers>
-                                </Style>
-                            </Rectangle.Style>
-                            <Rectangle.RenderTransform>
-                                <RotateTransform Angle="{Binding CurrentRoi.Angle}" />
-                            </Rectangle.RenderTransform>
-                        </Rectangle>
-
-                        <!-- ROI控制点 -->
-                        <Canvas Visibility="{Binding ShowRoi, Converter={StaticResource BooleanToVisibilityConverter}}">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+        </Grid.RowDefinitions>
+
+        <!-- 工具栏 -->
+        <Border Grid.Row="0"
+                Background="#F5F5F5"
+                BorderBrush="#E0E0E0"
+                BorderThickness="0,0,0,1"
+                Padding="10,8">
+            <StackPanel Orientation="Horizontal">
+                <Button Content="打开图像"
+                        Command="{Binding LoadImageCommand}"
+                        Padding="15,5"
+                        Margin="0,0,8,0" />
+                <Button Content="检测棋盘格"
+                        Command="{Binding DetectChessboardCommand}"
+                        Padding="15,5"
+                        Margin="0,0,8,0" />
+                <Separator Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}"
+                           Margin="8,0" />
+                <TextBlock Text="{Binding StatusText}"
+                           VerticalAlignment="Center"
+                           Foreground="#666"
+                           Margin="8,0,0,0" />
+            </StackPanel>
+        </Border>
+
+        <!-- 主内容区 -->
+        <Grid Grid.Row="1">
+            <Grid.ColumnDefinitions>
+                <ColumnDefinition Width="*" />
+                <ColumnDefinition Width="280" />
+            </Grid.ColumnDefinitions>
+
+            <!-- 左侧:图像显示区 -->
+            <Border Grid.Column="0"
+                    Style="{StaticResource CardStyle}"
+                    Margin="10">
+                <Grid>
+                    <!-- 图像容器 -->
+                    <Grid x:Name="ImageContainer">
+                        <!-- 图像显示 -->
+                        <Image x:Name="ImageDisplay"
+                               Source="{Binding CurrentImage}"
+                               Stretch="Uniform">
+                        </Image>
+
+                        <!-- 无图像提示 -->
+                        <Border Background="#F9F9F9"
+                                BorderBrush="#E0E0E0"
+                                BorderThickness="2"
+                                CornerRadius="8"
+                                Visibility="{Binding CurrentImage, Converter={StaticResource InvertNullToVisibilityConverter}}">
+                            <StackPanel HorizontalAlignment="Center"
+                                        VerticalAlignment="Center">
+                                <TextBlock Text="📷"
+                                           FontSize="48"
+                                           HorizontalAlignment="Center"
+                                           Foreground="#CCC"
+                                           Margin="0,0,0,16" />
+                                <TextBlock Text="点击【打开图像】加载棋盘格图片"
+                                           FontSize="14"
+                                           Foreground="#999"
+                                           HorizontalAlignment="Center" />
+                                <Button Content="打开图像"
+                                        Command="{Binding LoadImageCommand}"
+                                        Margin="0,16,0,0"
+                                        Padding="20,8" />
+                            </StackPanel>
+                        </Border>
+
+                        <!-- ROI绘制层 -->
+                        <Canvas x:Name="RoiCanvas"
+                                Background="Transparent"
+                                IsHitTestVisible="True">
+                            <!-- ROI矩形(带旋转) -->
+                            <Rectangle x:Name="RoiRectangle"
+                                       Fill="Transparent">
+                                <Rectangle.Style>
+                                    <Style TargetType="Rectangle">
+                                        <Setter Property="Stroke"
+                                                Value="Red" />
+                                        <Setter Property="StrokeThickness"
+                                                Value="2" />
+                                        <Setter Property="StrokeDashArray"
+                                                Value="4,4" />
+                                        <Setter Property="RenderTransformOrigin"
+                                                Value="0.5,0.5" />
+                                        <Style.Triggers>
+                                            <DataTrigger Binding="{Binding RoiMode}"
+                                                         Value="Draw">
+                                                <Setter Property="StrokeDashArray"
+                                                        Value="2,2" />
+                                            </DataTrigger>
+                                        </Style.Triggers>
+                                    </Style>
+                                </Rectangle.Style>
+                                <Rectangle.RenderTransform>
+                                    <RotateTransform Angle="{Binding CurrentRoi.Angle}" />
+                                </Rectangle.RenderTransform>
+                            </Rectangle>
+
                             <!-- 角点控制点 -->
                             <Ellipse x:Name="TopLeftHandle"
                                      Style="{StaticResource RoiHandleStyle}" />
@@ -191,279 +238,276 @@
                             <Path x:Name="RotateHandle"
                                   Style="{StaticResource RotateHandleStyle}" />
                         </Canvas>
-                    </Canvas>
-
-                    <!-- 操作提示 -->
-                    <Border Background="#80000000"
-                            CornerRadius="4"
-                            Padding="8"
-                            VerticalAlignment="Bottom"
-                            HorizontalAlignment="Center"
-                            Margin="0,0,0,10">
-                        <StackPanel>
-                            <TextBlock Text="ROI操作提示"
-                                       Foreground="White"
-                                       FontWeight="Bold"
-                                       Margin="0,0,0,4" />
-                            <TextBlock Text="拖动: 移动ROI"
-                                       Foreground="White"
-                                       FontSize="11" />
-                            <TextBlock Text="角点拖动: 调整大小"
-                                       Foreground="White"
-                                       FontSize="11" />
-                            <TextBlock Text="旋转点拖动: 旋转"
-                                       Foreground="White"
-                                       FontSize="11" />
-                        </StackPanel>
-                    </Border>
-                </Grid>
-            </Grid>
-        </Border>
 
-        <!-- 右侧:控制面板 -->
-        <Grid Grid.Column="1"
-              Margin="0,10,10,10">
-            <Grid.RowDefinitions>
-                <RowDefinition Height="Auto" />
-                <RowDefinition Height="Auto" />
-                <RowDefinition Height="Auto" />
-                <RowDefinition Height="Auto" />
-                <RowDefinition Height="*" />
-            </Grid.RowDefinitions>
-
-            <!-- ROI工具栏 -->
-            <Border Grid.Row="0"
-                    Style="{StaticResource CardStyle}">
-                <StackPanel>
-                    <TextBlock Text="ROI工具"
-                               FontWeight="Bold"
-                               Margin="0,0,0,8" />
-
-                    <StackPanel Orientation="Horizontal"
-                                HorizontalAlignment="Center">
-                        <!-- 绘制模式 -->
-                        <RadioButton Content="📐"
-                                     Style="{StaticResource ToolButtonStyle}"
-                                     ToolTip="绘制ROI"
-                                     IsChecked="{Binding RoiMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=Draw}"
-                                     Command="{Binding SetRoiModeCommand}"
-                                     CommandParameter="{x:Static local:RoiOperationMode.Draw}" />
-
-                        <!-- 移动模式 -->
-                        <RadioButton Content="↔"
-                                     Style="{StaticResource ToolButtonStyle}"
-                                     ToolTip="移动ROI"
-                                     IsChecked="{Binding RoiMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=Move}"
-                                     Command="{Binding SetRoiModeCommand}"
-                                     CommandParameter="{x:Static local:RoiOperationMode.Move}" />
-
-                        <!-- 调整大小模式 -->
-                        <RadioButton Content="⤢"
-                                     Style="{StaticResource ToolButtonStyle}"
-                                     ToolTip="调整大小"
-                                     IsChecked="{Binding RoiMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=Resize}"
-                                     Command="{Binding SetRoiModeCommand}"
-                                     CommandParameter="{x:Static local:RoiOperationMode.Resize}" />
-
-                        <!-- 旋转模式 -->
-                        <RadioButton Content="↻"
-                                     Style="{StaticResource ToolButtonStyle}"
-                                     ToolTip="旋转ROI"
-                                     IsChecked="{Binding RoiMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter=Rotate}"
-                                     Command="{Binding SetRoiModeCommand}"
-                                     CommandParameter="{x:Static local:RoiOperationMode.Rotate}" />
-
-                        <!-- 清除ROI -->
-                        <Button Width="30"
-                                Height="30"
-                                Margin="10,0,0,0"
-                                Padding="0"
-                                ToolTip="清除ROI"
-                                Command="{Binding ClearRoiCommand}">
-                            <materialDesign:PackIcon Kind="RemoveCircle"
-                                                     Width="26"
-                                                     Height="26" />
-                        </Button>
-                    </StackPanel>
-
-                    <!-- ROI信息 -->
-                    <Border Background="#F5F5F5"
-                            CornerRadius="3"
-                            Padding="6"
-                            Margin="0,8,0,0">
-                        <StackPanel>
-                            <TextBlock Text="ROI信息"
-                                       FontWeight="SemiBold"
-                                       FontSize="11" />
-                            <TextBlock Text="{Binding CurrentRoi}"
-                                       FontSize="10"
-                                       Foreground="#666"
-                                       TextWrapping="Wrap"
-                                       Margin="0,2,0,0" />
-                        </StackPanel>
-                    </Border>
-                </StackPanel>
-            </Border>
-
-            <!-- 参数设置 -->
-            <Border Grid.Row="1"
-                    Style="{StaticResource CardStyle}"
-                    Margin="0,8,0,0">
-                <StackPanel>
-                    <TextBlock Text="分析参数"
-                               FontWeight="Bold"
-                               Margin="0,0,0,8" />
-
-                    <Grid>
-                        <Grid.RowDefinitions>
-                            <RowDefinition Height="Auto" />
-                            <RowDefinition Height="Auto" />
-                            <RowDefinition Height="Auto" />
-                        </Grid.RowDefinitions>
-                        <Grid.ColumnDefinitions>
-                            <ColumnDefinition Width="80" />
-                            <ColumnDefinition Width="*" />
-                        </Grid.ColumnDefinitions>
-
-                        <TextBlock Grid.Row="0"
-                                   Grid.Column="0"
-                                   Text="算法:"
-                                   VerticalAlignment="Center" />
-                        <ComboBox Grid.Row="0"
-                                  Grid.Column="1"
-                                  ItemsSource="{Binding FocusMethods}"
-                                  SelectedValue="{Binding Parameters.FocusMethod}"
-                                  Margin="0,0,0,4" />
-
-                        <TextBlock Grid.Row="1"
-                                   Grid.Column="0"
-                                   Text="模式:"
-                                   VerticalAlignment="Center" />
-                        <ComboBox Grid.Row="1"
-                                  Grid.Column="1"
-                                  ItemsSource="{Binding AnalysisModes}"
-                                  SelectedValue="{Binding Parameters.AnalysisMode}"
-                                  Margin="0,0,0,4" />
-
-                        <TextBlock Grid.Row="2"
-                                   Grid.Column="0"
-                                   Text="实时分析:"
-                                   VerticalAlignment="Center" />
-                        <CheckBox Grid.Row="2"
-                                  Grid.Column="1"
-                                  IsChecked="{Binding Parameters.EnableRealtimeAnalysis}"
-                                  VerticalAlignment="Center" />
+                        <!-- 操作提示 -->
+                        <Border Background="#80000000"
+                                CornerRadius="4"
+                                Padding="8"
+                                VerticalAlignment="Bottom"
+                                HorizontalAlignment="Center"
+                                Margin="0,0,0,10"
+                                Visibility="{Binding CurrentImage, Converter={StaticResource NullToVisibilityConverter}}">
+                            <StackPanel>
+                                <TextBlock Text="ROI操作提示"
+                                           Foreground="White"
+                                           FontWeight="Bold"
+                                           Margin="0,0,0,4" />
+                                <TextBlock Text="拖动: 移动ROI"
+                                           Foreground="White"
+                                           FontSize="11" />
+                                <TextBlock Text="角点拖动: 调整大小"
+                                           Foreground="White"
+                                           FontSize="11" />
+                                <TextBlock Text="旋转点拖动: 旋转"
+                                           Foreground="White"
+                                           FontSize="11" />
+                            </StackPanel>
+                        </Border>
                     </Grid>
-                </StackPanel>
+                </Grid>
             </Border>
 
-            <!-- 控制按钮 -->
-            <Border Grid.Row="2"
-                    Style="{StaticResource CardStyle}"
-                    Margin="0,8,0,0">
-                <StackPanel>
-                    <StackPanel Orientation="Horizontal"
-                                HorizontalAlignment="Center">
-                        <Button Content="开始分析"
-                                Command="{Binding StartAnalysisCommand}"
-                                Padding="20,8"
-                                Margin="0,0,8,0" />
-                        <Button Content="停止分析"
-                                Command="{Binding StopAnalysisCommand}"
-                                Padding="20,8" />
-                    </StackPanel>
+            <!-- 右侧:控制面板 -->
+            <Grid Grid.Column="1"
+                  Margin="0,10,10,10">
+                <Grid.RowDefinitions>
+                    <RowDefinition Height="Auto" />
+                    <RowDefinition Height="Auto" />
+                    <RowDefinition Height="Auto" />
+                    <RowDefinition Height="Auto" />
+                    <RowDefinition Height="*" />
+                </Grid.RowDefinitions>
+
+                <!-- ROI工具栏 -->
+                <Border Grid.Row="0"
+                        Style="{StaticResource CardStyle}">
+                    <StackPanel>
+                        <TextBlock Text="ROI工具"
+                                   FontWeight="Bold"
+                                   Margin="0,0,0,8" />
+
+                        <StackPanel Orientation="Horizontal"
+                                    HorizontalAlignment="Center">
+                            <!-- 绘制模式 -->
+                            <RadioButton Content="📐"
+                                         Style="{StaticResource ToolButtonStyle}"
+                                         ToolTip="绘制ROI"
+                                         IsChecked="{Binding RoiMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static enums:RoiOperationMode.Draw}}" />
+
+                            <!-- 移动模式 -->
+                            <RadioButton Content="↔"
+                                         Style="{StaticResource ToolButtonStyle}"
+                                         ToolTip="移动ROI"
+                                         IsChecked="{Binding RoiMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static enums:RoiOperationMode.Move}}" />
+
+                            <!-- 调整大小模式 -->
+                            <RadioButton Content="⤢"
+                                         Style="{StaticResource ToolButtonStyle}"
+                                         ToolTip="调整大小"
+                                         IsChecked="{Binding RoiMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static enums:RoiOperationMode.Resize}}" />
+
+                            <!-- 旋转模式 -->
+                            <RadioButton Content="↻"
+                                         Style="{StaticResource ToolButtonStyle}"
+                                         ToolTip="旋转ROI"
+                                         IsChecked="{Binding RoiMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static enums:RoiOperationMode.Rotate}}" />
+
+                            <!-- 清除ROI -->
+                            <Button Width="30"
+                                    Height="30"
+                                    Margin="10,0,0,0"
+                                    Padding="0"
+                                    Content="&#xE14C;"
+                                    ToolTip="清除ROI"
+                                    Command="{Binding ClearRoiCommand}">
+                            </Button>
+                        </StackPanel>
 
-                    <StackPanel Orientation="Horizontal"
-                                HorizontalAlignment="Center"
+                        <!-- ROI信息 -->
+                        <Border Background="#F5F5F5"
+                                CornerRadius="3"
+                                Padding="6"
                                 Margin="0,8,0,0">
-                        <Button Content="重置"
-                                Command="{Binding ResetCommand}"
-                                Padding="15,4"
-                                Margin="0,0,8,0" />
-                        <Button Content="导出报告"
-                                Command="{Binding ExportCommand}"
-                                Padding="15,4" />
+                            <StackPanel>
+                                <TextBlock Text="ROI信息"
+                                           FontWeight="SemiBold"
+                                           FontSize="11" />
+                                <TextBlock>
+                                    <TextBlock.Text>
+                                        <MultiBinding Converter="{StaticResource RoiToTextConverter}">
+                                            <Binding Path="CurrentRoi.X" />
+                                            <Binding Path="CurrentRoi.Y" />
+                                            <Binding Path="CurrentRoi.Width" />
+                                            <Binding Path="CurrentRoi.Height" />
+                                            <Binding Path="CurrentRoi.Angle" />
+                                        </MultiBinding>
+                                    </TextBlock.Text>
+                                </TextBlock>
+                            </StackPanel>
+                        </Border>
                     </StackPanel>
-                </StackPanel>
-            </Border>
-
-            <!-- 实时结果 -->
-            <Border Grid.Row="3"
-                    Style="{StaticResource CardStyle}"
-                    Margin="0,8,0,0">
-                <StackPanel>
-                    <TextBlock Text="实时结果"
-                               FontWeight="Bold"
-                               Margin="0,0,0,8" />
-
-                    <Grid>
-                        <Grid.ColumnDefinitions>
-                            <ColumnDefinition Width="*" />
-                            <ColumnDefinition Width="*" />
-                        </Grid.ColumnDefinitions>
-
-                        <StackPanel Grid.Column="0">
-                            <TextBlock Text="清晰度"
-                                       FontSize="11"
-                                       Foreground="#666" />
-                            <TextBlock Text="{Binding CurrentResult.Sharpness, StringFormat=F2}"
-                                       FontSize="18"
-                                       FontWeight="Bold"
-                                       Foreground="#007ACC" />
-                            <TextBlock Text="{Binding StatusText}"
-                                       FontSize="10"
-                                       Foreground="#666"
-                                       Margin="0,2,0,0" />
-                        </StackPanel>
-
-                        <StackPanel Grid.Column="1">
-                            <TextBlock Text="质量评分"
-                                       FontSize="11"
-                                       Foreground="#666" />
-                            <TextBlock Text="{Binding CurrentResult.QualityScore, StringFormat=F1}"
-                                       FontSize="18"
-                                       FontWeight="Bold"
-                                       Foreground="#4CAF50" />
-                            <TextBlock Text="/100"
-                                       FontSize="11"
-                                       Foreground="#999" />
+                </Border>
+
+                <!-- 参数设置 -->
+                <Border Grid.Row="1"
+                        Style="{StaticResource CardStyle}"
+                        Margin="0,8,0,0">
+                    <StackPanel>
+                        <TextBlock Text="分析参数"
+                                   FontWeight="Bold"
+                                   Margin="0,0,0,8" />
+
+                        <Grid>
+                            <Grid.RowDefinitions>
+                                <RowDefinition Height="Auto" />
+                                <RowDefinition Height="Auto" />
+                                <RowDefinition Height="Auto" />
+                            </Grid.RowDefinitions>
+                            <Grid.ColumnDefinitions>
+                                <ColumnDefinition Width="80" />
+                                <ColumnDefinition Width="*" />
+                            </Grid.ColumnDefinitions>
+
+                            <TextBlock Grid.Row="0"
+                                       Grid.Column="0"
+                                       Text="算法:"
+                                       VerticalAlignment="Center" />
+                            <ComboBox Grid.Row="0"
+                                      Grid.Column="1"
+                                      ItemsSource="{Binding FocusMethods}"
+                                      SelectedValue="{Binding Parameters.FocusMethod}"
+                                      Margin="0,0,0,4" />
+
+                            <TextBlock Grid.Row="1"
+                                       Grid.Column="0"
+                                       Text="模式:"
+                                       VerticalAlignment="Center" />
+                            <ComboBox Grid.Row="1"
+                                      Grid.Column="1"
+                                      ItemsSource="{Binding AnalysisModes}"
+                                      SelectedValue="{Binding Parameters.AnalysisMode}"
+                                      Margin="0,0,0,4" />
+
+                            <TextBlock Grid.Row="2"
+                                       Grid.Column="0"
+                                       Text="实时分析:"
+                                       VerticalAlignment="Center" />
+                            <CheckBox Grid.Row="2"
+                                      Grid.Column="1"
+                                      IsChecked="{Binding Parameters.EnableRealtimeAnalysis}"
+                                      VerticalAlignment="Center" />
+                        </Grid>
+                    </StackPanel>
+                </Border>
+
+                <!-- 控制按钮 -->
+                <Border Grid.Row="2"
+                        Style="{StaticResource CardStyle}"
+                        Margin="0,8,0,0">
+                    <StackPanel>
+                        <StackPanel Orientation="Horizontal"
+                                    HorizontalAlignment="Center">
+                            <Button Content="开始分析"
+                                    Command="{Binding StartAnalysisCommand}"
+                                    Padding="20,8"
+                                    Margin="0,0,8,0" />
+                            <Button Content="停止分析"
+                                    Command="{Binding StopAnalysisCommand}"
+                                    Padding="20,8" />
                         </StackPanel>
-                    </Grid>
 
-                    <ProgressBar Value="{Binding CurrentResult.Sharpness}"
-                                 Maximum="50"
-                                 Height="6"
-                                 Margin="0,8,0,0" />
-
-                    <!-- 最佳值显示 -->
-                    <Border Background="#F8F9FA"
-                            CornerRadius="3"
-                            Padding="6"
-                            Margin="0,8,0,0">
-                        <StackPanel Orientation="Horizontal">
-                            <TextBlock Text="最佳清晰度:"
-                                       FontSize="10"
-                                       Foreground="#666" />
-                            <TextBlock Text="{Binding BestSharpnessText}"
-                                       FontSize="10"
-                                       FontWeight="Bold"
-                                       Margin="5,0,0,0" />
-                            <TextBlock Text="{Binding FrameCountText}"
-                                       FontSize="10"
-                                       Foreground="#666"
-                                       Margin="10,0,0,0" />
+                        <StackPanel Orientation="Horizontal"
+                                    HorizontalAlignment="Center"
+                                    Margin="0,8,0,0">
+                            <Button Content="重置"
+                                    Command="{Binding ResetCommand}"
+                                    Padding="15,4"
+                                    Margin="0,0,8,0" />
+                            <Button Content="导出报告"
+                                    Command="{Binding ExportCommand}"
+                                    Padding="15,4" />
                         </StackPanel>
-                    </Border>
-                </StackPanel>
-            </Border>
-
-            <!-- 图表 -->
-            <Border Grid.Row="4"
-                    Style="{StaticResource CardStyle}"
-                    Margin="0,8,0,0">
-                <oxy:PlotView Model="{Binding PlotModel}"
-                              Height="200" />
-            </Border>
+                    </StackPanel>
+                </Border>
+
+                <!-- 实时结果 -->
+                <Border Grid.Row="3"
+                        Style="{StaticResource CardStyle}"
+                        Margin="0,8,0,0">
+                    <StackPanel>
+                        <TextBlock Text="实时结果"
+                                   FontWeight="Bold"
+                                   Margin="0,0,0,8" />
+
+                        <Grid>
+                            <Grid.ColumnDefinitions>
+                                <ColumnDefinition Width="*" />
+                                <ColumnDefinition Width="*" />
+                            </Grid.ColumnDefinitions>
+
+                            <StackPanel Grid.Column="0">
+                                <TextBlock Text="清晰度"
+                                           FontSize="11"
+                                           Foreground="#666" />
+                                <TextBlock Text="{Binding CurrentResult.Sharpness, StringFormat=F2}"
+                                           FontSize="18"
+                                           FontWeight="Bold"
+                                           Foreground="#007ACC" />
+                                <TextBlock Text="{Binding StatusText}"
+                                           FontSize="10"
+                                           Foreground="#666"
+                                           Margin="0,2,0,0" />
+                            </StackPanel>
+
+                            <StackPanel Grid.Column="1">
+                                <TextBlock Text="质量评分"
+                                           FontSize="11"
+                                           Foreground="#666" />
+                                <TextBlock Text="{Binding CurrentResult.QualityScore, StringFormat=F1}"
+                                           FontSize="18"
+                                           FontWeight="Bold"
+                                           Foreground="#4CAF50" />
+                                <TextBlock Text="/100"
+                                           FontSize="11"
+                                           Foreground="#999" />
+                            </StackPanel>
+                        </Grid>
+
+                        <ProgressBar Value="{Binding CurrentResult.Sharpness}"
+                                     Maximum="50"
+                                     Height="6"
+                                     Margin="0,8,0,0" />
+
+                        <!-- 最佳值显示 -->
+                        <Border Background="#F8F9FA"
+                                CornerRadius="3"
+                                Padding="6"
+                                Margin="0,8,0,0">
+                            <StackPanel Orientation="Horizontal">
+                                <TextBlock Text="最佳清晰度:"
+                                           FontSize="10"
+                                           Foreground="#666" />
+                                <TextBlock Text="{Binding BestSharpnessText}"
+                                           FontSize="10"
+                                           FontWeight="Bold"
+                                           Margin="5,0,0,0" />
+                                <TextBlock Text="{Binding FrameCountText}"
+                                           FontSize="10"
+                                           Foreground="#666"
+                                           Margin="10,0,0,0" />
+                            </StackPanel>
+                        </Border>
+                    </StackPanel>
+                </Border>
+
+                <!-- 图表 -->
+                <Border Grid.Row="4"
+                        Style="{StaticResource CardStyle}"
+                        Margin="0,8,0,0">
+                    <oxy:PlotView Model="{Binding PlotModel}"
+                                  Height="200" />
+                </Border>
+            </Grid>
         </Grid>
     </Grid>
 </UserControl>

+ 432 - 184
TeamAAS-VM/Controls/FocusAnalyzerControl.xaml.cs

@@ -19,293 +19,541 @@ using System.Windows.Controls;
 using System.Windows.Input;
 using System.Windows.Media;
 using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Windows.Threading;
 using TeamAAS_VP.Core;
 using TeamAAS_VP.Enums;
 using TeamAAS_VP.Models;
+using TeamAAS_VP.ViewModels;
 
 namespace TeamAAS_VP.Controls
 {
     public partial class FocusAnalyzerControl : UserControl
     {
-        private FocusAnalyzerViewModel ViewModel;
+        private FocusAnalyzerViewModel ViewModel => DataContext as FocusAnalyzerViewModel;
 
-        // 鼠标状态
-        private bool _isMouseDown = false;
-        private System.Windows.Point _mouseDownPoint;
+        private System.Windows.Point _startPoint;
+        private System.Windows.Point _lastPoint;
+        private bool _isDragging = false;
+        private DragHandleType _currentHandle = DragHandleType.None;
+        private double _originalAngle = 0;
 
         public FocusAnalyzerControl()
         {
             InitializeComponent();
-            Loaded += OnLoaded;
+
+            // 订阅鼠标事件
+            RoiCanvas.MouseLeftButtonDown += RoiCanvas_MouseLeftButtonDown;
+            RoiCanvas.MouseMove += RoiCanvas_MouseMove;
+            RoiCanvas.MouseLeftButtonUp += RoiCanvas_MouseLeftButtonUp;
+
+            // 当Canvas或Image大小变化时,重新映射ROI以保持与图像同步
+            RoiCanvas.SizeChanged += RoiCanvas_SizeChanged;
+            ImageDisplay.SizeChanged += RoiCanvas_SizeChanged;
+            this.SizeChanged += RoiCanvas_SizeChanged;
+
+            // 订阅ViewModel的ROI变化事件
+            Loaded += FocusAnalyzerControl_Loaded;
         }
 
-        private void OnLoaded(object sender, RoutedEventArgs e)
+        private void FocusAnalyzerControl_Loaded(object sender, RoutedEventArgs e)
         {
-            // 初始化ViewModel
-            if (DataContext == null)
-                DataContext = new FocusAnalyzerViewModel();
-            ViewModel=DataContext as FocusAnalyzerViewModel;
-        }
+            if (ViewModel != null)
+            {
+                ViewModel.PropertyChanged += ViewModel_PropertyChanged;
 
-        #region 鼠标事件处理
+                // 设置ROI到图像坐标的转换器
+                ViewModel.RoiToImageRectConverter = ConvertRoiToImageRect;
+            }
+        }
 
-        private void ImageDisplay_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        private void RoiCanvas_SizeChanged(object sender, SizeChangedEventArgs e)
         {
-            if (ViewModel == null) return;
+            // When the canvas or window resizes, remap existing ROI so it stays aligned to the same image area
+            if (ViewModel == null || ViewModel.CurrentRoi == null || !ViewModel.CurrentRoi.IsValid)
+                return;
 
-            _isMouseDown = true;
-            _mouseDownPoint = e.GetPosition(ImageDisplay);
+            if (ViewModel.RoiToImageRectConverter == null)
+                return;
 
-            // 处理ROI操作
-            if (ViewModel.CurrentRoi != null)
-            {
-                // 检查是否点击了ROI
-                if (ViewModel.StartRoiDrag(_mouseDownPoint))
-                {
-                    CaptureMouse();
-                    return;
-                }
-            }
+            var imgRect = ViewModel.RoiToImageRectConverter(ViewModel.CurrentRoi);
+            if (!imgRect.HasValue)
+                return;
 
-            // 开始绘制新ROI
-            if (ViewModel.RoiMode == RoiOperationMode.Draw)
+            // Convert image pixel rect back to canvas coordinates and update CurrentRoi
+            var newRoi = ConvertImageRectToCanvasRoi(imgRect.Value);
+            if (newRoi != null)
             {
-                ViewModel.StartRoiDrawing(_mouseDownPoint);
-                CaptureMouse();
+                // Preserve angle
+                double angle = ViewModel.CurrentRoi.Angle;
+                ViewModel.CurrentRoi.X = newRoi.X;
+                ViewModel.CurrentRoi.Y = newRoi.Y;
+                ViewModel.CurrentRoi.Width = newRoi.Width;
+                ViewModel.CurrentRoi.Height = newRoi.Height;
+                ViewModel.CurrentRoi.Angle = angle;
             }
         }
 
-        private void ImageDisplay_MouseMove(object sender, MouseEventArgs e)
+        private TeamAAS_VP.Models.RoiModel ConvertImageRectToCanvasRoi(OpenCvSharp.Rect imgRect)
         {
-            if (ViewModel == null || !_isMouseDown) return;
+            if (ViewModel?.CurrentImage == null)
+                return null;
+
+            var bmp = ViewModel.CurrentImage as System.Windows.Media.Imaging.BitmapSource;
+            if (bmp == null || bmp.PixelWidth == 0 || bmp.PixelHeight == 0)
+                return null;
+
+            double canvasW = RoiCanvas.ActualWidth;
+            double canvasH = RoiCanvas.ActualHeight;
+            if (canvasW <= 0 || canvasH <= 0)
+                return null;
+
+            double imgPixelW = bmp.PixelWidth;
+            double imgPixelH = bmp.PixelHeight;
 
-            var currentPoint = e.GetPosition(ImageDisplay);
+            double imgRatio = imgPixelW / imgPixelH;
+            double canvasRatio = canvasW / canvasH;
 
-            // 处理ROI拖动
-            if (ViewModel.RoiMode != RoiOperationMode.Draw && ViewModel.CurrentRoi != null)
+            double dispW, dispH;
+            if (canvasRatio > imgRatio)
             {
-                ViewModel.UpdateRoiDrag(currentPoint);
-                UpdateRoiVisual();
+                // canvas wider than image => fit height
+                dispH = canvasH;
+                dispW = dispH * imgRatio;
             }
-            // 处理ROI绘制
-            else if (ViewModel.RoiMode == RoiOperationMode.Draw)
+            else
             {
-                ViewModel.UpdateRoiDrawing(currentPoint);
-                UpdateRoiVisual();
+                // fit width
+                dispW = canvasW;
+                dispH = dispW / imgRatio;
             }
+
+            double offsetX = (canvasW - dispW) / 2.0;
+            double offsetY = (canvasH - dispH) / 2.0;
+
+            double scaleX = imgPixelW / dispW;
+            double scaleY = imgPixelH / dispH;
+
+            double canvasX = offsetX + imgRect.X / scaleX;
+            double canvasY = offsetY + imgRect.Y / scaleY;
+            double canvasWRect = imgRect.Width / scaleX;
+            double canvasHRect = imgRect.Height / scaleY;
+
+            return new TeamAAS_VP.Models.RoiModel
+            {
+                X = canvasX,
+                Y = canvasY,
+                Width = canvasWRect,
+                Height = canvasHRect,
+                Angle = 0
+            };
         }
 
-        private void ImageDisplay_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
+        private OpenCvSharp.Rect? ConvertRoiToImageRect(TeamAAS_VP.Models.RoiModel roi)
         {
-            if (ViewModel == null || !_isMouseDown) return;
+            if (roi == null || !roi.IsValid || ViewModel?.CurrentImage == null)
+                return null;
+
+            try
+            {
+                var bmp = ViewModel.CurrentImage as System.Windows.Media.Imaging.BitmapSource;
+                if (bmp == null || bmp.PixelWidth == 0 || bmp.PixelHeight == 0)
+                    return null;
+
+                double canvasW = RoiCanvas.ActualWidth;
+                double canvasH = RoiCanvas.ActualHeight;
+                if (canvasW <= 0 || canvasH <= 0)
+                    return null;
+
+                double imgPixelW = bmp.PixelWidth;
+                double imgPixelH = bmp.PixelHeight;
+
+                double imgRatio = imgPixelW / imgPixelH;
+                double canvasRatio = canvasW / canvasH;
+
+                double dispW, dispH;
+                if (canvasRatio > imgRatio)
+                {
+                    // canvas wider than image => fit height
+                    dispH = canvasH;
+                    dispW = dispH * imgRatio;
+                }
+                else
+                {
+                    // fit width
+                    dispW = canvasW;
+                    dispH = dispW / imgRatio;
+                }
+
+                double offsetX = (canvasW - dispW) / 2.0;
+                double offsetY = (canvasH - dispH) / 2.0;
+
+                // ROI relative to displayed image area
+                double rx = roi.X - offsetX;
+                double ry = roi.Y - offsetY;
+
+                // clamp to displayed image area
+                if (rx + roi.Width <= 0 || ry + roi.Height <= 0)
+                    return null;
+
+                double clampedX = Math.Max(0, rx);
+                double clampedY = Math.Max(0, ry);
+                double clampedW = Math.Min(roi.Width - (clampedX - rx), dispW - clampedX);
+                double clampedH = Math.Min(roi.Height - (clampedY - ry), dispH - clampedY);
+
+                if (clampedW <= 0 || clampedH <= 0)
+                    return null;
 
-            _isMouseDown = false;
-            ReleaseMouseCapture();
+                double scaleX = imgPixelW / dispW;
+                double scaleY = imgPixelH / dispH;
 
-            if (ViewModel.RoiMode == RoiOperationMode.Draw)
+                int ix = (int)(clampedX * scaleX);
+                int iy = (int)(clampedY * scaleY);
+                int iw = Math.Max(1, (int)(clampedW * scaleX));
+                int ih = Math.Max(1, (int)(clampedH * scaleY));
+
+                // clamp to image bounds
+                ix = Math.Max(0, Math.Min(ix, (int)imgPixelW - 1));
+                iy = Math.Max(0, Math.Min(iy, (int)imgPixelH - 1));
+                iw = Math.Min(iw, (int)imgPixelW - ix);
+                ih = Math.Min(ih, (int)imgPixelH - iy);
+
+                return new OpenCvSharp.Rect(ix, iy, iw, ih);
+            }
+            catch
             {
-                ViewModel.FinishRoiDrawing();
+                return null;
             }
-            else
+        }
+
+        private void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
+        {
+            if (e.PropertyName == nameof(ViewModel.CurrentRoi))
             {
-                ViewModel.FinishRoiDrag();
+                UpdateRoiVisual();
             }
         }
 
-        #endregion
+        private void RoiCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+        {
+            if (ViewModel?.CurrentImage == null)
+                return;
 
-        #region ROI可视化更新
+            _startPoint = e.GetPosition(RoiCanvas);
+            _lastPoint = _startPoint;
+            _isDragging = true;
 
-        private void UpdateRoiVisual()
-        {
-            if (ViewModel?.CurrentRoi == null) return;
+            // 检测点击的是哪个控制点
+            _currentHandle = GetHandleAtPoint(_startPoint);
 
-            // 更新ROI矩形位置和大小
-            Canvas.SetLeft(RoiRectangle, ViewModel.CurrentRoi.X);
-            Canvas.SetTop(RoiRectangle, ViewModel.CurrentRoi.Y);
-            RoiRectangle.Width = ViewModel.CurrentRoi.Width;
-            RoiRectangle.Height = ViewModel.CurrentRoi.Height;
+            if (_currentHandle == DragHandleType.None && ViewModel.RoiMode == RoiOperationMode.Draw)
+            {
+                // 开始绘制新的ROI
+                ViewModel.CurrentRoi.X = _startPoint.X;
+                ViewModel.CurrentRoi.Y = _startPoint.Y;
+                ViewModel.CurrentRoi.Width = 0;
+                ViewModel.CurrentRoi.Height = 0;
+                ViewModel.CurrentRoi.Angle = 0;
+            }
+            else if (_currentHandle == DragHandleType.Rotate)
+            {
+                _originalAngle = ViewModel.CurrentRoi.Angle;
+            }
 
-            // 更新控制点位置
-            UpdateRoiHandles();
+            RoiCanvas.CaptureMouse();
         }
 
-        private void UpdateRoiHandles()
+        private void RoiCanvas_MouseMove(object sender, MouseEventArgs e)
         {
-            if (ViewModel?.CurrentRoi == null) return;
+            if (!_isDragging || ViewModel?.CurrentImage == null)
+                return;
+
+            System.Windows.Point currentPoint = e.GetPosition(RoiCanvas);
+            double deltaX = currentPoint.X - _lastPoint.X;
+            double deltaY = currentPoint.Y - _lastPoint.Y;
 
             var roi = ViewModel.CurrentRoi;
 
-            // 更新角点
-            UpdateHandlePosition(TopLeftHandle, roi.X, roi.Y);
-            UpdateHandlePosition(TopRightHandle, roi.X + roi.Width, roi.Y);
-            UpdateHandlePosition(BottomLeftHandle, roi.X, roi.Y + roi.Height);
-            UpdateHandlePosition(BottomRightHandle, roi.X + roi.Width, roi.Y + roi.Height);
+            switch (ViewModel.RoiMode)
+            {
+                case RoiOperationMode.Draw:
+                    // 绘制模式
+                    if (_currentHandle == DragHandleType.None)
+                    {
+                        roi.Width = Math.Abs(currentPoint.X - _startPoint.X);
+                        roi.Height = Math.Abs(currentPoint.Y - _startPoint.Y);
+                        roi.X = Math.Min(_startPoint.X, currentPoint.X);
+                        roi.Y = Math.Min(_startPoint.Y, currentPoint.Y);
+                    }
+                    break;
+
+                case RoiOperationMode.Move:
+                    // 移动模式
+                    if (IsPointInRoi(_lastPoint))
+                    {
+                        roi.X += deltaX;
+                        roi.Y += deltaY;
+                    }
+                    break;
+
+                case RoiOperationMode.Resize:
+                    // 调整大小模式
+                    HandleResize(currentPoint, deltaX, deltaY);
+                    break;
+
+                case RoiOperationMode.Rotate:
+                    // 旋转模式
+                    if (_currentHandle == DragHandleType.Rotate)
+                    {
+                        HandleRotation(currentPoint);
+                    }
+                    break;
+            }
 
-            // 更新边中点
-            UpdateHandlePosition(TopHandle, roi.X + roi.Width / 2, roi.Y);
-            UpdateHandlePosition(RightHandle, roi.X + roi.Width, roi.Y + roi.Height / 2);
-            UpdateHandlePosition(BottomHandle, roi.X + roi.Width / 2, roi.Y + roi.Height);
-            UpdateHandlePosition(LeftHandle, roi.X, roi.Y + roi.Height / 2);
+            // 通用:如果点击了控制点,执行相应操作
+            if (_currentHandle != DragHandleType.None)
+            {
+                HandleControlPoint(currentPoint, deltaX, deltaY);
+            }
 
-            // 更新旋转控制点
-            UpdateRotateHandlePosition(roi);
+            _lastPoint = currentPoint;
+            UpdateRoiVisual();
         }
 
-        private void UpdateHandlePosition(FrameworkElement handle, double x, double y)
+        private void RoiCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
         {
-            if (handle == null) return;
-
-            Canvas.SetLeft(handle, x - handle.Width / 2);
-            Canvas.SetTop(handle, y - handle.Height / 2);
+            _isDragging = false;
+            _currentHandle = DragHandleType.None;
+            RoiCanvas.ReleaseMouseCapture();
         }
 
-        private void UpdateRotateHandlePosition(RotatedRect roi)
+        private DragHandleType GetHandleAtPoint(System.Windows.Point point)
         {
-            if (RotateHandle == null) return;
+            const double tolerance = 10;
 
-            // 旋转控制点在矩形顶部中心上方
+            if (!ViewModel.CurrentRoi.IsValid)
+                return DragHandleType.None;
+
+            var roi = ViewModel.CurrentRoi;
             double centerX = roi.X + roi.Width / 2;
             double centerY = roi.Y + roi.Height / 2;
 
-            // 计算旋转后的位置
-            double angleRad = roi.Angle * Math.PI / 180;
-            double radius = Math.Max(roi.Width, roi.Height) / 2 + 20; // 距离中心20像素
-
-            double x = centerX + radius * Math.Sin(angleRad);
-            double y = centerY - radius * Math.Cos(angleRad);
-
-            // 设置位置
-            RotateHandle.RenderTransform = new RotateTransform(roi.Angle);
-            Canvas.SetLeft(RotateHandle, x - 5); // 5是三角形宽度的一半
-            Canvas.SetTop(RotateHandle, y - 5); // 5是三角形高度的一半
+            // 检查角点
+            if (IsPointNear(point, new System.Windows.Point(roi.X, roi.Y), tolerance))
+                return DragHandleType.TopLeft;
+            if (IsPointNear(point, new System.Windows.Point(roi.X + roi.Width, roi.Y), tolerance))
+                return DragHandleType.TopRight;
+            if (IsPointNear(point, new System.Windows.Point(roi.X, roi.Y + roi.Height), tolerance))
+                return DragHandleType.BottomLeft;
+            if (IsPointNear(point, new System.Windows.Point(roi.X + roi.Width, roi.Y + roi.Height), tolerance))
+                return DragHandleType.BottomRight;
+
+            // 检查边中点
+            if (IsPointNear(point, new System.Windows.Point(centerX, roi.Y), tolerance))
+                return DragHandleType.Top;
+            if (IsPointNear(point, new System.Windows.Point(roi.X + roi.Width, centerY), tolerance))
+                return DragHandleType.Right;
+            if (IsPointNear(point, new System.Windows.Point(centerX, roi.Y + roi.Height), tolerance))
+                return DragHandleType.Bottom;
+            if (IsPointNear(point, new System.Windows.Point(roi.X, centerY), tolerance))
+                return DragHandleType.Left;
+
+            // 检查旋转控制点(在顶部上方)
+            if (IsPointNear(point, new System.Windows.Point(centerX, roi.Y - 30), tolerance))
+                return DragHandleType.Rotate;
+
+            return DragHandleType.None;
         }
 
-        #endregion
+        private bool IsPointNear(System.Windows.Point p1, System.Windows.Point p2, double tolerance)
+        {
+            double distance = Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2));
+            return distance <= tolerance;
+        }
 
-        #region 依赖属性
+        private bool IsPointInRoi(System.Windows.Point point)
+        {
+            var roi = ViewModel.CurrentRoi;
+            if (!roi.IsValid)
+                return false;
 
-        // CurrentImage依赖属性
-        public static readonly DependencyProperty CurrentImageProperty =
-            DependencyProperty.Register("CurrentImage", typeof(ImageSource), typeof(FocusAnalyzerControl),
-                new PropertyMetadata(null, OnCurrentImageChanged));
+            return point.X >= roi.X && point.X <= roi.X + roi.Width &&
+                   point.Y >= roi.Y && point.Y <= roi.Y + roi.Height;
+        }
 
-        public ImageSource CurrentImage
+        private void HandleResize(System.Windows.Point currentPoint, double deltaX, double deltaY)
         {
-            get => (ImageSource)GetValue(CurrentImageProperty);
-            set => SetValue(CurrentImageProperty, value);
+            // 根据当前控制点调整ROI大小(在HandleControlPoint中处理)
         }
 
-        private static void OnCurrentImageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+        private void HandleRotation(System.Windows.Point currentPoint)
         {
-            var control = d as FocusAnalyzerControl;
-            if (control.ViewModel != null)
-                control.ViewModel.CurrentImage = e.NewValue as ImageSource;
-        }
+            var roi = ViewModel.CurrentRoi;
+            double centerX = roi.X + roi.Width / 2;
+            double centerY = roi.Y + roi.Height / 2;
 
-        // Parameters依赖属性
-        public static readonly DependencyProperty ParametersProperty =
-            DependencyProperty.Register("Parameters", typeof(AnalysisParameters), typeof(FocusAnalyzerControl),
-                new PropertyMetadata(new AnalysisParameters(), OnParametersChanged));
+            // 计算旋转角度
+            double angle1 = Math.Atan2(_startPoint.Y - centerY, _startPoint.X - centerX);
+            double angle2 = Math.Atan2(currentPoint.Y - centerY, currentPoint.X - centerX);
+            double deltaAngle = (angle2 - angle1) * 180 / Math.PI;
 
-        public AnalysisParameters Parameters
-        {
-            get => (AnalysisParameters)GetValue(ParametersProperty);
-            set => SetValue(ParametersProperty, value);
+            roi.Angle = _originalAngle + deltaAngle;
+
+            // 限制角度范围 -180 到 180
+            while (roi.Angle > 180) roi.Angle -= 360;
+            while (roi.Angle < -180) roi.Angle += 360;
         }
 
-        private static void OnParametersChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+        private void HandleControlPoint(System.Windows.Point currentPoint, double deltaX, double deltaY)
         {
-            var control = d as FocusAnalyzerControl;
-            if (control.ViewModel != null)
-                control.ViewModel.Parameters = e.NewValue as AnalysisParameters;
-        }
+            var roi = ViewModel.CurrentRoi;
 
-        // CurrentResult依赖属性
-        public static readonly DependencyProperty CurrentResultProperty =
-            DependencyProperty.Register("CurrentResult", typeof(AnalysisResult), typeof(FocusAnalyzerControl),
-                new PropertyMetadata(new AnalysisResult(), OnCurrentResultChanged));
+            switch (_currentHandle)
+            {
+                case DragHandleType.TopLeft:
+                    roi.Width -= deltaX;
+                    roi.Height -= deltaY;
+                    roi.X += deltaX;
+                    roi.Y += deltaY;
+                    break;
+
+                case DragHandleType.TopRight:
+                    roi.Width += deltaX;
+                    roi.Height -= deltaY;
+                    roi.Y += deltaY;
+                    break;
+
+                case DragHandleType.BottomLeft:
+                    roi.Width -= deltaX;
+                    roi.Height += deltaY;
+                    roi.X += deltaX;
+                    break;
+
+                case DragHandleType.BottomRight:
+                    roi.Width += deltaX;
+                    roi.Height += deltaY;
+                    break;
+
+                case DragHandleType.Top:
+                    roi.Height -= deltaY;
+                    roi.Y += deltaY;
+                    break;
+
+                case DragHandleType.Bottom:
+                    roi.Height += deltaY;
+                    break;
+
+                case DragHandleType.Left:
+                    roi.Width -= deltaX;
+                    roi.X += deltaX;
+                    break;
+
+                case DragHandleType.Right:
+                    roi.Width += deltaX;
+                    break;
+
+                case DragHandleType.Rotate:
+                    HandleRotation(currentPoint);
+                    break;
+            }
 
-        public AnalysisResult CurrentResult
-        {
-            get => (AnalysisResult)GetValue(CurrentResultProperty);
-            set => SetValue(CurrentResultProperty, value);
+            // 确保宽度和高度为正值
+            if (roi.Width < 10)
+            {
+                roi.X -= (10 - roi.Width);
+                roi.Width = 10;
+            }
+            if (roi.Height < 10)
+            {
+                roi.Y -= (10 - roi.Height);
+                roi.Height = 10;
+            }
         }
 
-        private static void OnCurrentResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+        private void UpdateRoiVisual()
         {
-            var control = d as FocusAnalyzerControl;
-            if (control.ViewModel != null)
-                control.ViewModel.CurrentResult = e.NewValue as AnalysisResult;
-        }
+            if (ViewModel?.CurrentRoi == null || !ViewModel.CurrentRoi.IsValid)
+            {
+                RoiRectangle.Visibility = Visibility.Collapsed;
+                HideAllHandles();
+                return;
+            }
 
-        // StartAnalysisCommand依赖属性
-        public static readonly DependencyProperty StartAnalysisCommandProperty =
-            DependencyProperty.Register("StartAnalysisCommand", typeof(ICommand), typeof(FocusAnalyzerControl),
-                new PropertyMetadata(null, OnStartAnalysisCommandChanged));
+            var roi = ViewModel.CurrentRoi;
 
-        public ICommand StartAnalysisCommand
-        {
-            get => (ICommand)GetValue(StartAnalysisCommandProperty);
-            set => SetValue(StartAnalysisCommandProperty, value);
+            // 更新ROI矩形
+            RoiRectangle.Visibility = Visibility.Visible;
+            Canvas.SetLeft(RoiRectangle, roi.X);
+            Canvas.SetTop(RoiRectangle, roi.Y);
+            RoiRectangle.Width = roi.Width;
+            RoiRectangle.Height = roi.Height;
+
+            // 更新控制点位置
+            UpdateHandlePositions(roi);
         }
 
-        private static void OnStartAnalysisCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+        private void UpdateHandlePositions(Models.RoiModel roi)
         {
-            var control = d as FocusAnalyzerControl;
-            if (control.ViewModel != null)
-                control.ViewModel.StartAnalysisCommand = e.NewValue as ICommand;
-        }
+            double centerX = roi.X + roi.Width / 2;
+            double centerY = roi.Y + roi.Height / 2;
 
-        // 其他命令和属性的依赖属性...
+            // 角点
+            SetHandlePosition(TopLeftHandle, roi.X, roi.Y);
+            SetHandlePosition(TopRightHandle, roi.X + roi.Width, roi.Y);
+            SetHandlePosition(BottomLeftHandle, roi.X, roi.Y + roi.Height);
+            SetHandlePosition(BottomRightHandle, roi.X + roi.Width, roi.Y + roi.Height);
 
-        #endregion
+            // 边中点
+            SetHandlePosition(TopHandle, centerX, roi.Y);
+            SetHandlePosition(RightHandle, roi.X + roi.Width, centerY);
+            SetHandlePosition(BottomHandle, centerX, roi.Y + roi.Height);
+            SetHandlePosition(LeftHandle, roi.X, centerY);
 
-        #region 公共方法
+            // 旋转控制点
+            SetHandlePosition(RotateHandle, centerX, roi.Y - 30);
 
-        /// <summary>
-        /// 处理图像帧
-        /// </summary>
-        public async Task ProcessImageFrameAsync(OpenCvSharp.Mat frame)
-        {
-            if (ViewModel != null)
-                await ViewModel.ProcessImageFrameAsync(frame);
+            ShowAllHandles();
         }
 
-        /// <summary>
-        /// 执行单次分析
-        /// </summary>
-        public void PerformAnalysis(OpenCvSharp.Mat frame)
+        private void SetHandlePosition(UIElement handle, double x, double y)
         {
-            ViewModel?.PerformAnalysis(frame);
+            if (handle is Ellipse ellipse)
+            {
+                Canvas.SetLeft(handle, x - ellipse.Width / 2);
+                Canvas.SetTop(handle, y - ellipse.Height / 2);
+            }
+            else if (handle is Path path)
+            {
+                Canvas.SetLeft(handle, x - 5);
+                Canvas.SetTop(handle, y - 5);
+            }
+            handle.Visibility = Visibility.Visible;
         }
 
-        /// <summary>
-        /// 获取当前ROI区域
-        /// </summary>
-        public OpenCvSharp.Rect? GetCurrentRoiRect()
+        private void ShowAllHandles()
         {
-            if (ViewModel?.CurrentRoi == null)
-                return null;
-
-            return new OpenCvSharp.Rect(
-                (int)ViewModel.CurrentRoi.X,
-                (int)ViewModel.CurrentRoi.Y,
-                (int)ViewModel.CurrentRoi.Width,
-                (int)ViewModel.CurrentRoi.Height);
+            TopLeftHandle.Visibility = Visibility.Visible;
+            TopRightHandle.Visibility = Visibility.Visible;
+            BottomLeftHandle.Visibility = Visibility.Visible;
+            BottomRightHandle.Visibility = Visibility.Visible;
+            TopHandle.Visibility = Visibility.Visible;
+            RightHandle.Visibility = Visibility.Visible;
+            BottomHandle.Visibility = Visibility.Visible;
+            LeftHandle.Visibility = Visibility.Visible;
+            RotateHandle.Visibility = Visibility.Visible;
         }
 
-        /// <summary>
-        /// 获取旋转ROI
-        /// </summary>
-        public OpenCvSharp.RotatedRect? GetCurrentRotatedRoi()
+        private void HideAllHandles()
         {
-            if (ViewModel?.CurrentRoi == null)
-                return null;
-
-            return ViewModel.CurrentRoi.ToCvRotatedRect();
+            TopLeftHandle.Visibility = Visibility.Collapsed;
+            TopRightHandle.Visibility = Visibility.Collapsed;
+            BottomLeftHandle.Visibility = Visibility.Collapsed;
+            BottomRightHandle.Visibility = Visibility.Collapsed;
+            TopHandle.Visibility = Visibility.Collapsed;
+            RightHandle.Visibility = Visibility.Collapsed;
+            BottomHandle.Visibility = Visibility.Collapsed;
+            LeftHandle.Visibility = Visibility.Collapsed;
+            RotateHandle.Visibility = Visibility.Collapsed;
         }
-
-        #endregion
     }
 }

+ 305 - 440
TeamAAS-VM/Controls/FocusAnalyzerViewModel.cs

@@ -5,6 +5,7 @@ using OxyPlot.Axes;
 using OxyPlot.Series;
 using Prism.Commands;
 using Prism.Mvvm;
+using SqlSugar;
 using System;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
@@ -13,9 +14,12 @@ using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Input;
 using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Threading;
 using TeamAAS_VP.Core;
 using TeamAAS_VP.Enums;
 using TeamAAS_VP.Models;
+using TeamAAS_VP.Services;
 
 namespace TeamAAS_VP.Controls
 {
@@ -24,588 +28,449 @@ namespace TeamAAS_VP.Controls
     /// </summary>
     public class FocusAnalyzerViewModel : BindableBase
     {
-        #region 可绑定属性
+        private readonly FileDialogService _fileDialogService;
+        private readonly ImageAnalysisService _imageAnalysisService;
+        private readonly CheckerboardDetectionService _checkerboardService;
+        private readonly DispatcherTimer _analysisTimer;
+
+        private string _title = "棋盘格清晰度分析工具";
+        private BitmapSource _currentImage;
+        private Mat _currentMat;
+        private AnalysisParameters _parameters;
+        private AnalysisResult _currentResult;
+        private RoiModel _currentRoi;
+        private ChessboardInfo _chessboardInfo;
+        private RoiOperationMode _roiMode;
+        private string _statusText;
+        private bool _isAnalyzing;
+        private double _bestSharpness;
+        private int _frameCount;
+        private PlotModel _plotModel;
+        private List<AnalysisResult> _resultHistory;
+
+        // function to convert ROI from canvas coords to image pixel Rect (set by view)
+        public Func<RoiModel, OpenCvSharp.Rect?> RoiToImageRectConverter { get; set; }
+
+        public string Title
+        {
+            get => _title;
+            set => SetProperty(ref _title, value);
+        }
 
-        // 图像源
-        private ImageSource _currentImage;
-        public ImageSource CurrentImage
+        public BitmapSource CurrentImage
         {
             get => _currentImage;
             set => SetProperty(ref _currentImage, value);
         }
 
-        // 分析参数
-        private AnalysisParameters _parameters = new AnalysisParameters();
         public AnalysisParameters Parameters
         {
             get => _parameters;
             set => SetProperty(ref _parameters, value);
         }
 
-        // 当前结果
-        private AnalysisResult _currentResult = new AnalysisResult();
         public AnalysisResult CurrentResult
         {
             get => _currentResult;
             set => SetProperty(ref _currentResult, value);
         }
 
-        // 最终报告
-        private AnalysisReport _finalReport = new AnalysisReport();
-        public AnalysisReport FinalReport
-        {
-            get => _finalReport;
-            set => SetProperty(ref _finalReport, value);
-        }
-
-        // 分析状态
-        private bool _isAnalyzing;
-        public bool IsAnalyzing
-        {
-            get => _isAnalyzing;
-            set => SetProperty(ref _isAnalyzing, value);
-        }
-
-        // ROI区域
-        private RotatedRect _currentRoi;
-        public RotatedRect CurrentRoi
+        public RoiModel CurrentRoi
         {
             get => _currentRoi;
             set => SetProperty(ref _currentRoi, value);
         }
 
-        // 是否显示ROI
-        private bool _showRoi = true;
-        public bool ShowRoi
+        public ChessboardInfo ChessboardInfo
         {
-            get => _showRoi;
-            set => SetProperty(ref _showRoi, value);
+            get => _chessboardInfo;
+            set => SetProperty(ref _chessboardInfo, value);
         }
 
-        // ROI操作模式
-        private RoiOperationMode _roiMode = RoiOperationMode.Draw;
         public RoiOperationMode RoiMode
         {
             get => _roiMode;
             set => SetProperty(ref _roiMode, value);
         }
 
-        // 图表模型
-        private PlotModel _plotModel;
-        public PlotModel PlotModel
-        {
-            get => _plotModel;
-            set => SetProperty(ref _plotModel, value);
-        }
-
-        // 状态文本
-        private string _statusText = "就绪";
         public string StatusText
         {
             get => _statusText;
             set => SetProperty(ref _statusText, value);
         }
 
-        // 帧数文本
-        private string _frameCountText = "帧数: 0";
-        public string FrameCountText
+        public bool IsAnalyzing
         {
-            get => _frameCountText;
-            set => SetProperty(ref _frameCountText, value);
+            get => _isAnalyzing;
+            set => SetProperty(ref _isAnalyzing, value);
         }
 
-        // 最佳清晰度文本
-        private string _bestSharpnessText = "最佳: 0.00";
-        public string BestSharpnessText
+        public PlotModel PlotModel
         {
-            get => _bestSharpnessText;
-            set => SetProperty(ref _bestSharpnessText, value);
+            get => _plotModel;
+            set => SetProperty(ref _plotModel, value);
         }
 
-        // 枚举列表
-        public Array FocusMethods => Enum.GetValues(typeof(FocusMethod));
-        public Array AnalysisModes => Enum.GetValues(typeof(AnalysisMode));
-
-        #endregion
-
-        #region 命令
-
-        // 控制命令(绑定到外部)
-        public ICommand StartAnalysisCommand { get; set; }
-        public ICommand StopAnalysisCommand { get; set; }
-        public ICommand ResetCommand { get; set; }
-        public ICommand ExportCommand { get; set; }
-
-        // 内部命令
-        public DelegateCommand<object> SetRoiModeCommand { get; private set; }
-        public DelegateCommand ClearRoiCommand { get; private set; }
-
-        #endregion
-
-        #region 事件
-
-        // 控件事件(供外部订阅)
-        public event EventHandler AnalysisStarted;
-        public event EventHandler AnalysisStopped;
-        public event EventHandler RoiChanged;
-        public event EventHandler<ErrorEventArgs> ErrorOccurred;
+        public string BestSharpnessText => _bestSharpness > 0 ? $"{_bestSharpness:F2}" : "N/A";
+        public string FrameCountText => $"帧数: {_frameCount}";
 
-        #endregion
+        public ObservableCollection<FocusMethod> FocusMethods { get; }
+        public ObservableCollection<AnalysisMode> AnalysisModes { get; }
 
-        #region 私有字段
-
-        private int _frameCounter = 0;
-        private double _bestSharpness = 0;
-        private DateTime _startTime;
-        private ObservableCollection<Models.DataPoint> _historyData = new ObservableCollection<Models.DataPoint>();
-
-        // ROI绘制状态
-        private System.Windows.Point _roiStartPoint;
-        private System.Windows.Point _roiDragStartPoint;
-        private RotatedRect _roiBeforeDrag;
-        private DragHandleType _currentDragHandle = DragHandleType.None;
-
-        #endregion
-
-        #region 构造函数
+        public DelegateCommand LoadImageCommand { get; }
+        public DelegateCommand StartAnalysisCommand { get; }
+        public DelegateCommand StopAnalysisCommand { get; }
+        public DelegateCommand ResetCommand { get; }
+        public DelegateCommand ExportCommand { get; }
+        public DelegateCommand ClearRoiCommand { get; }
+        public DelegateCommand DetectChessboardCommand { get; }
 
         public FocusAnalyzerViewModel()
         {
-            InitializeCommands();
-            InitializeProperties();
-            InitializePlot();
-        }
+            _fileDialogService = new FileDialogService();
+            _imageAnalysisService = new ImageAnalysisService();
+            _checkerboardService = new CheckerboardDetectionService();
 
-        #endregion
+            _parameters = new AnalysisParameters();
+            _currentResult = new AnalysisResult();
+            _currentRoi = new RoiModel();
+            _resultHistory = new List<AnalysisResult>();
+            _roiMode = RoiOperationMode.Draw; // 默认为绘制模式
 
-        #region 初始化
+            FocusMethods = new ObservableCollection<FocusMethod>(Enum.GetValues(typeof(FocusMethod)).Cast<FocusMethod>());
+            AnalysisModes = new ObservableCollection<AnalysisMode>(Enum.GetValues(typeof(AnalysisMode)).Cast<AnalysisMode>());
 
-        private void InitializeCommands()
-        {
-            // ROI模式切换命令
-            SetRoiModeCommand = new DelegateCommand<object>(mode =>
-            {
-                RoiMode = (RoiOperationMode)mode;
-            });
+            LoadImageCommand = new DelegateCommand(OnLoadImage);
+            StartAnalysisCommand = new DelegateCommand(OnStartAnalysis, CanStartAnalysis).ObservesProperty(() => CurrentImage);
+            StopAnalysisCommand = new DelegateCommand(OnStopAnalysis, () => IsAnalyzing).ObservesProperty(() => IsAnalyzing);
+            ResetCommand = new DelegateCommand(OnReset);
+            ExportCommand = new DelegateCommand(OnExport, () => _resultHistory.Count > 0);
+            ClearRoiCommand = new DelegateCommand(OnClearRoi);
+            DetectChessboardCommand = new DelegateCommand(OnDetectChessboard, () => _currentMat != null);
 
-            // 清除ROI命令
-            ClearRoiCommand = new DelegateCommand(() =>
-            {
-                CurrentRoi = null;
-                OnRoiChanged();
-            });
-        }
-
-        private void InitializeProperties()
-        {
-            Parameters = new AnalysisParameters();
-            CurrentResult = new AnalysisResult();
-            FinalReport = new AnalysisReport();
-
-            // 初始化默认ROI
-            CurrentRoi = new RotatedRect(100, 100, 200, 200, 0);
-        }
+            InitializePlot();
 
-        private void InitializePlot()
-        {
-            PlotModel = new PlotModel
+            _analysisTimer = new DispatcherTimer
             {
-                Title = "清晰度变化曲线",
-                TitleFontSize = 12,
-                PlotMargins = new OxyThickness(40, 10, 10, 40)
+                Interval = TimeSpan.FromMilliseconds(100)
             };
+            _analysisTimer.Tick += OnAnalysisTick;
 
-            PlotModel.Axes.Add(new LinearAxis
-            {
-                Position = AxisPosition.Bottom,
-                Title = "帧序列",
-                MajorGridlineStyle = LineStyle.Solid,
-                MinorGridlineStyle = LineStyle.Dot
-            });
+            StatusText = "就绪";
+        }
 
-            PlotModel.Axes.Add(new LinearAxis
+        private void OnLoadImage()
+        {
+            try
             {
-                Position = AxisPosition.Left,
-                Title = "清晰度",
-                MajorGridlineStyle = LineStyle.Solid,
-                MinorGridlineStyle = LineStyle.Dot
-            });
+                string filePath = _fileDialogService.OpenImageFile();
+                if (string.IsNullOrEmpty(filePath))
+                    return;
 
-            PlotModel.Series.Add(new LineSeries
-            {
-                Title = "清晰度",
-                Color = OxyColors.DodgerBlue,
-                StrokeThickness = 2
-            });
-        }
+                // 释放之前的图像
+                _currentMat?.Dispose();
 
-        #endregion
+                // 加载图像
+                _currentMat = Cv2.ImRead(filePath, ImreadModes.Color);
+                if (_currentMat == null || _currentMat.Empty())
+                {
+                    StatusText = "无法加载图像";
+                    return;
+                }
 
-        #region 公共方法
+                // 转换为WPF图像
+                CurrentImage = _currentMat.ToWriteableBitmap();
 
-        /// <summary>
-        /// 处理图像帧
-        /// </summary>
-        public async Task ProcessImageFrameAsync(Mat frame)
-        {
-            if (!IsAnalyzing || frame == null || frame.Empty())
-                return;
+                // 自动检测棋盘格
+                OnDetectChessboard();
 
-            try
-            {
-                // 更新图像
-                await App.Current.Dispatcher.InvokeAsync(() =>
+                // 如果启用了实时分析,立即分析
+                if (Parameters.EnableRealtimeAnalysis)
                 {
-                    CurrentImage = BitmapSourceConverter.ToBitmapSource(frame);
-                });
-
-                // 执行分析
-                await Task.Run(() => PerformAnalysis(frame));
-                _frameCounter++;
+                    AnalyzeCurrentImage();
+                }
 
-                // 更新UI
-                UpdateStatusText();
+                StatusText = $"图像已加载: {_currentMat.Width}x{_currentMat.Height}";
             }
             catch (Exception ex)
             {
-                OnErrorOccurred(new ErrorEventArgs($"处理图像帧失败: {ex.Message}", ex));
+                StatusText = $"加载图像失败: {ex.Message}";
             }
         }
 
-        /// <summary>
-        /// 执行单次分析
-        /// </summary>
-        public void PerformAnalysis(Mat frame)
+        private void OnDetectChessboard()
         {
-            if (frame == null || frame.Empty())
+            if (_currentMat == null || _currentMat.Empty())
                 return;
 
             try
             {
-                // 将RotatedRect转换为Rect(简化处理)
-                Rect? roiRect = null;
-                if (CurrentRoi != null)
+                StatusText = "正在检测棋盘格...";
+
+                Task.Run(() =>
                 {
-                    roiRect = new Rect((int)CurrentRoi.X, (int)CurrentRoi.Y, (int)CurrentRoi.Width, (int)CurrentRoi.Height);
-                }
+                    ChessboardInfo info = null;
 
-                // 计算清晰度
-                double sharpness = FocusAnalysisEngine.CalculateImageSharpness(
-                    frame, Parameters.FocusMethod, roiRect);
+                    if (RoiToImageRectConverter != null && CurrentRoi?.IsValid == true)
+                    {
+                        var imgRoi = RoiToImageRectConverter(CurrentRoi);
+                        if (imgRoi.HasValue)
+                        {
+                            using (var sub = new Mat(_currentMat, imgRoi.Value))
+                            {
+                                info = _checkerboardService.DetectChessboard(sub);
+                            }
+
+                            if (info != null && info.IsDetected)
+                            {
+                                for (int i = 0; i < info.Corners.Length; i++)
+                                {
+                                    info.Corners[i].X += imgRoi.Value.X;
+                                    info.Corners[i].Y += imgRoi.Value.Y;
+                                }
+                                var br = info.BoundingRect;
+                                info.BoundingRect = new OpenCvSharp.Rect(br.X + imgRoi.Value.X, br.Y + imgRoi.Value.Y, br.Width, br.Height);
+                            }
+                        }
+                    }
 
-                // 分析棋盘格
-                CheckerboardResult checkerboard;
-                if (Parameters.AnalysisMode == AnalysisMode.AutoCheckerboard)
-                {
-                    checkerboard = FocusAnalysisEngine.AnalyzeCheckerboardContrast(frame, roiRect);
-                }
-                else
-                {
-                    checkerboard = new CheckerboardResult();
-                }
+                    if (info == null || !info.IsDetected)
+                    {
+                        info = _checkerboardService.DetectChessboard(_currentMat);
+                    }
 
-                // 更新结果
-                App.Current.Dispatcher.Invoke(() =>
-                {
-                    UpdateAnalysisResult(sharpness, checkerboard);
-                    UpdateHistoryData(sharpness, checkerboard);
-                    UpdatePlot();
+                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
+                    {
+                        ChessboardInfo = info;
+
+                        if (info.IsDetected)
+                        {
+                            StatusText = $"检测成功: {info.CornersWidth}x{info.CornersHeight} 角点";
+
+                            // 绘制棋盘格
+                            var displayMat = _currentMat.Clone();
+                            _checkerboardService.DrawChessboard(displayMat, info);
+                            CurrentImage = displayMat.ToWriteableBitmap();
+                            displayMat.Dispose();
+                        }
+                        else
+                        {
+                            StatusText = "未检测到棋盘格";
+                        }
+                    });
                 });
             }
             catch (Exception ex)
             {
-                OnErrorOccurred(new ErrorEventArgs($"图像分析失败: {ex.Message}", ex));
+                StatusText = $"检测失败: {ex.Message}";
             }
         }
 
-        #endregion
-
-        #region ROI绘制方法
-
-        /// <summary>
-        /// 开始ROI绘制
-        /// </summary>
-        public void StartRoiDrawing(System.Windows.Point startPoint)
+        private bool CanStartAnalysis()
         {
-            if (RoiMode != RoiOperationMode.Draw)
-                return;
-
-            _roiStartPoint = startPoint;
-            CurrentRoi = new RotatedRect(startPoint.X, startPoint.Y, 0, 0, 0);
+            return CurrentImage != null && !IsAnalyzing;
         }
 
-        /// <summary>
-        /// 更新ROI绘制
-        /// </summary>
-        public void UpdateRoiDrawing(System.Windows.Point currentPoint)
+        private void OnStartAnalysis()
         {
-            if (RoiMode != RoiOperationMode.Draw || CurrentRoi == null)
-                return;
-
-            double x = Math.Min(_roiStartPoint.X, currentPoint.X);
-            double y = Math.Min(_roiStartPoint.Y, currentPoint.Y);
-            double width = Math.Abs(currentPoint.X - _roiStartPoint.X);
-            double height = Math.Abs(currentPoint.Y - _roiStartPoint.Y);
+            IsAnalyzing = true;
+            _frameCount = 0;
+            _bestSharpness = 0;
+            _resultHistory.Clear();
+            StatusText = "分析中...";
 
-            CurrentRoi.X = x;
-            CurrentRoi.Y = y;
-            CurrentRoi.Width = width;
-            CurrentRoi.Height = height;
-        }
-
-        /// <summary>
-        /// 完成ROI绘制
-        /// </summary>
-        public void FinishRoiDrawing()
-        {
-            OnRoiChanged();
-        }
-
-        /// <summary>
-        /// 开始ROI拖动
-        /// </summary>
-        public bool StartRoiDrag(System.Windows.Point point)
-        {
-            if (CurrentRoi == null || !CurrentRoi.ContainsPoint(point))
-                return false;
-
-            // 检查是否点击了控制点
-            _currentDragHandle = GetDragHandleAtPoint(point);
-
-            if (_currentDragHandle != DragHandleType.None)
+            if (Parameters.EnableRealtimeAnalysis)
             {
-                _roiDragStartPoint = point;
-                _roiBeforeDrag = new RotatedRect(
-                    CurrentRoi.X, CurrentRoi.Y,
-                    CurrentRoi.Width, CurrentRoi.Height,
-                    CurrentRoi.Angle);
-                return true;
+                _analysisTimer.Start();
             }
-
-            return false;
-        }
-
-        /// <summary>
-        /// 更新ROI拖动
-        /// </summary>
-        public void UpdateRoiDrag(System.Windows.Point currentPoint)
-        {
-            if (CurrentRoi == null || _roiBeforeDrag == null)
-                return;
-
-            double deltaX = currentPoint.X - _roiDragStartPoint.X;
-            double deltaY = currentPoint.Y - _roiDragStartPoint.Y;
-
-            switch (_currentDragHandle)
+            else
             {
-                case DragHandleType.TopLeft:
-                    CurrentRoi.X = _roiBeforeDrag.X + deltaX;
-                    CurrentRoi.Y = _roiBeforeDrag.Y + deltaY;
-                    CurrentRoi.Width = _roiBeforeDrag.Width - deltaX;
-                    CurrentRoi.Height = _roiBeforeDrag.Height - deltaY;
-                    break;
-
-                case DragHandleType.TopRight:
-                    CurrentRoi.Y = _roiBeforeDrag.Y + deltaY;
-                    CurrentRoi.Width = _roiBeforeDrag.Width + deltaX;
-                    CurrentRoi.Height = _roiBeforeDrag.Height - deltaY;
-                    break;
-
-                case DragHandleType.BottomLeft:
-                    CurrentRoi.X = _roiBeforeDrag.X + deltaX;
-                    CurrentRoi.Width = _roiBeforeDrag.Width - deltaX;
-                    CurrentRoi.Height = _roiBeforeDrag.Height + deltaY;
-                    break;
-
-                case DragHandleType.BottomRight:
-                    CurrentRoi.Width = _roiBeforeDrag.Width + deltaX;
-                    CurrentRoi.Height = _roiBeforeDrag.Height + deltaY;
-                    break;
-
-                case DragHandleType.Rotate:
-                    // 计算旋转角度
-                    var center = new System.Windows.Point(
-                        _roiBeforeDrag.CenterX,
-                        _roiBeforeDrag.CenterY);
-                    double startAngle = Math.Atan2(
-                        _roiDragStartPoint.Y - center.Y,
-                        _roiDragStartPoint.X - center.X);
-                    double currentAngle = Math.Atan2(
-                        currentPoint.Y - center.Y,
-                        currentPoint.X - center.X);
-                    double angleDelta = (currentAngle - startAngle) * 180 / Math.PI;
-                    CurrentRoi.Angle = (_roiBeforeDrag.Angle + angleDelta) % 360;
-                    break;
-
-                case DragHandleType.None:
-                    // 移动整个ROI
-                    CurrentRoi.X = _roiBeforeDrag.X + deltaX;
-                    CurrentRoi.Y = _roiBeforeDrag.Y + deltaY;
-                    break;
+                AnalyzeCurrentImage();
+                IsAnalyzing = false;
+                StatusText = "分析完成";
             }
         }
 
-        /// <summary>
-        /// 结束ROI拖动
-        /// </summary>
-        public void FinishRoiDrag()
+        private void OnStopAnalysis()
         {
-            _currentDragHandle = DragHandleType.None;
-            _roiBeforeDrag = null;
-            OnRoiChanged();
+            _analysisTimer.Stop();
+            IsAnalyzing = false;
+            StatusText = "已停止";
         }
 
-        /// <summary>
-        /// 获取指定点的控制点类型
-        /// </summary>
-        private DragHandleType GetDragHandleAtPoint(System.Windows.Point point)
+        private void OnAnalysisTick(object sender, EventArgs e)
         {
-            if (CurrentRoi == null) return DragHandleType.None;
-
-            const double handleSize = 8;
-            var center = new System.Windows.Point(CurrentRoi.CenterX, CurrentRoi.CenterY);
+            AnalyzeCurrentImage();
+        }
 
-            // 检查旋转控制点(在矩形顶部中心上方)
-            var rotateHandle = new System.Windows.Point(center.X, CurrentRoi.Y - 20);
-            if (Distance(point, rotateHandle) <= handleSize)
-                return DragHandleType.Rotate;
+        private void AnalyzeCurrentImage()
+        {
+            if (_currentMat == null || _currentMat.Empty())
+                return;
 
-            // 检查角点
-            var corners = new[]
+            try
             {
-                new System.Windows.Point(CurrentRoi.X, CurrentRoi.Y), // 左上
-                new System.Windows.Point(CurrentRoi.X + CurrentRoi.Width, CurrentRoi.Y), // 右上
-                new System.Windows.Point(CurrentRoi.X, CurrentRoi.Y + CurrentRoi.Height), // 左下
-                new System.Windows.Point(CurrentRoi.X + CurrentRoi.Width, CurrentRoi.Y + CurrentRoi.Height) // 右下
-            };
+                Rect? roi = null;
 
-            // 替换 switch 表达式为 switch 语句以兼容 C# 7.3
-            for (int i = 0; i < corners.Length; i++)
-            {
-                if (Distance(point, corners[i]) <= handleSize)
+                // 根据分析模式确定分析区域
+                switch (Parameters.AnalysisMode)
                 {
-                    switch (i)
-                    {
-                        case 0:
-                            return DragHandleType.TopLeft;
-                        case 1:
-                            return DragHandleType.TopRight;
-                        case 2:
-                            return DragHandleType.BottomLeft;
-                        case 3:
-                            return DragHandleType.BottomRight;
-                        default:
-                            return DragHandleType.None;
-                    }
+                    case AnalysisMode.RoiOnly:
+                        if (CurrentRoi.IsValid)
+                        {
+                            if (RoiToImageRectConverter != null)
+                            {
+                                roi = RoiToImageRectConverter(CurrentRoi);
+                            }
+                            else
+                            {
+                                roi = new Rect(
+                                    (int)CurrentRoi.X,
+                                    (int)CurrentRoi.Y,
+                                    (int)CurrentRoi.Width,
+                                    (int)CurrentRoi.Height);
+                            }
+                        }
+                        break;
+
+                    case AnalysisMode.ChessboardOnly:
+                        if (ChessboardInfo?.IsDetected == true)
+                        {
+                            roi = ChessboardInfo.BoundingRect;
+                        }
+                        break;
                 }
-            }
 
-            return DragHandleType.None;
-        }
+                // 执行分析
+                var result = _imageAnalysisService.AnalyzeImage(_currentMat, Parameters.FocusMethod, roi);
 
-        private double Distance(System.Windows.Point p1, System.Windows.Point p2)
-        {
-            return Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));
-        }
+                CurrentResult = result;
+                _resultHistory.Add(result);
+                _frameCount++;
 
-        #endregion
+                // 更新最佳清晰度
+                if (result.Sharpness > _bestSharpness)
+                {
+                    _bestSharpness = result.Sharpness;
+                    RaisePropertyChanged(nameof(BestSharpnessText));
+                }
 
-        #region 私有方法
+                RaisePropertyChanged(nameof(FrameCountText));
 
-        private void UpdateAnalysisResult(double sharpness, CheckerboardResult checkerboard)
-        {
-            double qualityScore = FocusAnalysisEngine.CalculateQualityScore(sharpness, checkerboard);
-            var suggestions = FocusAnalysisEngine.GenerateSuggestions(
-                sharpness, checkerboard,
-                Parameters.SharpnessThreshold,
-                Parameters.ContrastThreshold);
-
-            if (sharpness > _bestSharpness)
-                _bestSharpness = sharpness;
-
-            CurrentResult.Sharpness = sharpness;
-            CurrentResult.Checkerboard = checkerboard;
-            CurrentResult.QualityScore = qualityScore;
-            CurrentResult.FrameCount = _frameCounter + 1;
-            CurrentResult.BestSharpness = _bestSharpness;
-            CurrentResult.AnalysisTime = DateTime.Now;
-            CurrentResult.Suggestions = new ObservableCollection<string>(suggestions);
+                // 更新图表
+                UpdatePlot();
+
+                StatusText = $"清晰度: {result.Sharpness:F2}, 对比度: {result.Contrast:F2}";
+            }
+            catch (Exception ex)
+            {
+                StatusText = $"分析错误: {ex.Message}";
+            }
         }
 
-        private void UpdateHistoryData(double sharpness, CheckerboardResult checkerboard)
+        private void OnReset()
         {
-            var dataPoint = new Models.DataPoint(_frameCounter, sharpness,
-                checkerboard.Detected ? checkerboard.Contrast : 0);
-            _historyData.Add(dataPoint);
-
-            // 添加到最终报告
-            FinalReport.HistoryData.Add(dataPoint);
+            OnStopAnalysis();
+            _frameCount = 0;
+            _bestSharpness = 0;
+            _resultHistory.Clear();
+            CurrentResult = new AnalysisResult();
+            InitializePlot();
+            StatusText = "已重置";
+            RaisePropertyChanged(nameof(BestSharpnessText));
+            RaisePropertyChanged(nameof(FrameCountText));
         }
 
-        private void UpdatePlot()
+        private void OnExport()
         {
-            if (PlotModel.Series[0] is LineSeries series)
+            try
             {
-                series.Points.Clear();
+                string filePath = _fileDialogService.SaveFile(
+                    $"分析报告_{DateTime.Now:yyyyMMdd_HHmmss}.csv",
+                    "CSV文件|*.csv|所有文件|*.*");
 
-                for (int i = 0; i < _historyData.Count; i++)
-                {
-                    series.Points.Add(new OxyPlot.DataPoint(i, _historyData[i].Sharpness));
-                }
+                if (string.IsNullOrEmpty(filePath))
+                    return;
 
-                // 限制显示点数
-                if (series.Points.Count > 200)
+                using (var writer = new System.IO.StreamWriter(filePath))
                 {
-                    series.Points.RemoveRange(0, series.Points.Count - 200);
+                    writer.WriteLine("时间,清晰度,对比度,质量评分");
+                    foreach (var result in _resultHistory)
+                    {
+                        writer.WriteLine($"{result.Timestamp:yyyy-MM-dd HH:mm:ss.fff},{result.Sharpness:F2},{result.Contrast:F2},{result.QualityScore:F2}");
+                    }
                 }
 
-                PlotModel.InvalidatePlot(true);
+                StatusText = $"报告已导出: {filePath}";
+            }
+            catch (Exception ex)
+            {
+                StatusText = $"导出失败: {ex.Message}";
             }
         }
 
-        private void UpdateStatusText()
+        private void OnClearRoi()
         {
-            StatusText = $"分析中... 第 {_frameCounter + 1} 帧";
-            FrameCountText = $"帧数: {_frameCounter + 1}";
-            BestSharpnessText = $"最佳: {_bestSharpness:F2}";
+            CurrentRoi = new RoiModel();
+            StatusText = "ROI已清除";
         }
 
-        #endregion
+        private void InitializePlot()
+        {
+            PlotModel = new PlotModel
+            {
+                Title = "清晰度趋势",
+                Background = OxyColors.White
+            };
 
-        #region 事件触发方法
+            PlotModel.Axes.Add(new LinearAxis
+            {
+                Position = AxisPosition.Bottom,
+                Title = "帧数",
+                MajorGridlineStyle = LineStyle.Solid,
+                MinorGridlineStyle = LineStyle.Dot,
+                MajorGridlineColor = OxyColor.FromRgb(230, 230, 230)
+            });
 
-        protected virtual void OnAnalysisStarted()
-        {
-            AnalysisStarted?.Invoke(this, EventArgs.Empty);
-        }
+            PlotModel.Axes.Add(new LinearAxis
+            {
+                Position = AxisPosition.Left,
+                Title = "清晰度",
+                MajorGridlineStyle = LineStyle.Solid,
+                MinorGridlineStyle = LineStyle.Dot,
+                MajorGridlineColor = OxyColor.FromRgb(230, 230, 230)
+            });
 
-        protected virtual void OnAnalysisStopped()
-        {
-            AnalysisStopped?.Invoke(this, EventArgs.Empty);
-        }
+            var series = new LineSeries
+            {
+                Title = "清晰度",
+                Color = OxyColor.FromRgb(0, 122, 204),
+                StrokeThickness = 2,
+                MarkerType = MarkerType.Circle,
+                MarkerSize = 3,
+                MarkerFill = OxyColor.FromRgb(0, 122, 204)
+            };
 
-        protected virtual void OnRoiChanged()
-        {
-            RoiChanged?.Invoke(this, EventArgs.Empty);
+            PlotModel.Series.Add(series);
         }
 
-        protected virtual void OnErrorOccurred(ErrorEventArgs e)
+        private void UpdatePlot()
         {
-            ErrorOccurred?.Invoke(this, e);
-        }
+            if (PlotModel.Series.Count == 0)
+                return;
 
-        #endregion
-    }
+            var series = PlotModel.Series[0] as LineSeries;
+            if (series == null)
+                return;
 
-    public class ErrorEventArgs : EventArgs
-    {
-        public string Message { get; }
-        public Exception Exception { get; }
+            series.Points.Clear();
 
-        public ErrorEventArgs(string message, Exception exception = null)
-        {
-            Message = message;
-            Exception = exception;
+            for (int i = 0; i < _resultHistory.Count; i++)
+            {
+                series.Points.Add(new OxyPlot.DataPoint(i + 1, _resultHistory[i].Sharpness));
+            }
+
+            PlotModel.InvalidatePlot(true);
         }
     }
 }

+ 0 - 734
TeamAAS-VM/Core/FocusAnalysisEngine.cs

@@ -1,734 +0,0 @@
-using MathNet.Numerics.Statistics;
-using OpenCvSharp;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using TeamAAS_VP.Enums;
-using TeamAAS_VP.Models;
-
-namespace TeamAAS_VP.Core
-{
-    /// <summary>
-    /// 图像清晰度分析引擎
-    /// </summary>
-    public class FocusAnalysisEngine
-    {
-        // 自定义Clamp方法
-        private static double Clamp(double value, double min, double max)
-        {
-            return value < min ? min : (value > max ? max : value);
-        }
-
-        private static int Clamp(int value, int min, int max)
-        {
-            return value < min ? min : (value > max ? max : value);
-        }
-
-        /// <summary>
-        /// 计算图像清晰度
-        /// </summary>
-        public static double CalculateImageSharpness(Mat image, FocusMethod method, Rect? roi = null)
-        {
-            if (image == null || image.Empty())
-                throw new ArgumentException("输入图像无效");
-
-            // 转换为灰度图
-            Mat gray = new Mat();
-            if (image.Channels() == 3)
-                Cv2.CvtColor(image, gray, ColorConversionCodes.BGR2GRAY);
-            else
-                gray = image.Clone();
-
-            // 应用ROI
-            if (roi.HasValue)
-            {
-                gray = new Mat(gray, roi.Value);
-            }
-
-            double sharpness = 0;
-
-            switch (method)
-            {
-                case FocusMethod.Tenengrad:
-                    sharpness = CalculateTenengrad(gray);
-                    break;
-                case FocusMethod.Laplacian:
-                    sharpness = CalculateLaplacianVariance(gray);
-                    break;
-                case FocusMethod.Brenner:
-                    sharpness = CalculateBrenner(gray);
-                    break;
-                case FocusMethod.GrayVariance:
-                    sharpness = CalculateGrayVariance(gray);
-                    break;
-                case FocusMethod.SMD:
-                    sharpness = CalculateSMD(gray);
-                    break;
-            }
-
-            gray.Dispose();
-            return sharpness;
-        }
-
-        private static double CalculateTenengrad(Mat gray)
-        {
-            Mat gradX = new Mat();
-            Mat gradY = new Mat();
-            Mat magnitude = new Mat();
-
-            Cv2.Sobel(gray, gradX, MatType.CV_32F, 1, 0, 3);
-            Cv2.Sobel(gray, gradY, MatType.CV_32F, 0, 1, 3);
-            Cv2.Magnitude(gradX, gradY, magnitude);
-
-            Scalar mean = Cv2.Mean(magnitude);
-
-            gradX.Dispose();
-            gradY.Dispose();
-            magnitude.Dispose();
-
-            return mean.Val0;
-        }
-
-        private static double CalculateLaplacianVariance(Mat gray)
-        {
-            Mat laplacian = new Mat();
-            Cv2.Laplacian(gray, laplacian, MatType.CV_32F);
-
-            Mat mean = new Mat();
-            Mat stdDev = new Mat();
-            Cv2.MeanStdDev(laplacian, mean, stdDev);
-
-            double variance = stdDev.Get<double>(0);
-            variance = variance * variance;
-
-            laplacian.Dispose();
-            mean.Dispose();
-            stdDev.Dispose();
-
-            return variance;
-        }
-
-        private static double CalculateBrenner(Mat gray)
-        {
-            double sum = 0;
-            int width = gray.Cols;
-            int height = gray.Rows;
-
-            for (int y = 0; y < height; y++)
-            {
-                for (int x = 0; x < width - 2; x++)
-                {
-                    int diff = gray.Get<byte>(y, x + 2) - gray.Get<byte>(y, x);
-                    sum += diff * diff;
-                }
-            }
-
-            return sum / (width * height);
-        }
-
-        private static double CalculateGrayVariance(Mat gray)
-        {
-            Mat mean = new Mat();
-            Mat stdDev = new Mat();
-            Cv2.MeanStdDev(gray, mean, stdDev);
-
-            double variance = stdDev.Get<double>(0);
-            variance = variance * variance;
-
-            mean.Dispose();
-            stdDev.Dispose();
-
-            return variance;
-        }
-
-        private static double CalculateSMD(Mat gray)
-        {
-            double sum = 0;
-            int width = gray.Cols;
-            int height = gray.Rows;
-
-            for (int y = 0; y < height; y++)
-            {
-                for (int x = 0; x < width - 1; x++)
-                {
-                    sum += Math.Abs(gray.Get<byte>(y, x + 1) - gray.Get<byte>(y, x));
-                }
-            }
-
-            for (int y = 0; y < height - 1; y++)
-            {
-                for (int x = 0; x < width; x++)
-                {
-                    sum += Math.Abs(gray.Get<byte>(y + 1, x) - gray.Get<byte>(y, x));
-                }
-            }
-
-            return sum / (width * height);
-        }
-
-        /// <summary>
-        /// 分析棋盘格对比度
-        /// </summary>
-        public static CheckerboardResult AnalyzeCheckerboardContrast(Mat image, Rect? roi = null)
-        {
-            var result = new CheckerboardResult();
-
-            try
-            {
-                // 转换为灰度图
-                Mat gray = new Mat();
-                if (image.Channels() == 3)
-                    Cv2.CvtColor(image, gray, ColorConversionCodes.BGR2GRAY);
-                else
-                    gray = image.Clone();
-
-                // 应用ROI
-                if (roi.HasValue)
-                {
-                    gray = new Mat(gray, roi.Value);
-                }
-
-                // 简化版的棋盘格检测
-                bool detected = TryDetectCheckerboard(gray, out double blackMean, out double whiteMean);
-
-                if (detected)
-                {
-                    result.Detected = true;
-                    result.BlackMean = blackMean;
-                    result.WhiteMean = whiteMean;
-                    result.Contrast = Math.Abs(whiteMean - blackMean);
-                    result.OptimalBrightness = CalculateOptimalBrightness(blackMean, whiteMean);
-                }
-
-                gray.Dispose();
-            }
-            catch (Exception ex)
-            {
-                Console.WriteLine($"棋盘格分析出错: {ex.Message}");
-            }
-
-            return result;
-        }
-
-        private static bool TryDetectCheckerboard(Mat gray, out double blackMean, out double whiteMean)
-        {
-            blackMean = 0;
-            whiteMean = 0;
-
-            try
-            {
-                // 使用自适应阈值进行二值化
-                Mat binary = new Mat();
-                Cv2.AdaptiveThreshold(gray, binary, 255,
-                    AdaptiveThresholdTypes.GaussianC,
-                    ThresholdTypes.Binary, 11, 2);
-
-                // 查找轮廓
-                var contours = Cv2.FindContoursAsArray(binary,
-                    RetrievalModes.External,
-                    ContourApproximationModes.ApproxSimple);
-
-                // 寻找近似矩形的轮廓(可能是棋盘格)
-                var rectangles = new List<Rect>();
-                foreach (var contour in contours)
-                {
-                    var poly = Cv2.ApproxPolyDP(contour, 0.02 * Cv2.ArcLength(contour, true), true);
-
-                    if (poly.Length == 4) // 四边形
-                    {
-                        var rect = Cv2.BoundingRect(contour);
-                        if (rect.Width > 50 && rect.Height > 50) // 忽略太小的区域
-                        {
-                            rectangles.Add(rect);
-                        }
-                    }
-                }
-
-                if (rectangles.Count >= 2)
-                {
-                    // 采样黑色和白色区域
-                    blackMean = SampleRegionMean(gray, rectangles[0]);
-                    whiteMean = SampleRegionMean(gray, rectangles.Count > 1 ? rectangles[1] : rectangles[0]);
-
-                    // 确保黑色比白色暗
-                    if (blackMean > whiteMean)
-                    {
-                        double temp = blackMean;
-                        blackMean = whiteMean;
-                        whiteMean = temp;
-                    }
-
-                    return true;
-                }
-
-                binary.Dispose();
-            }
-            catch
-            {
-                // 如果检测失败,返回false
-            }
-
-            return false;
-        }
-
-        private static double SampleRegionMean(Mat gray, Rect region)
-        {
-            var sample = new Mat(gray, region);
-            Scalar mean = Cv2.Mean(sample);
-            sample.Dispose();
-            return mean.Val0;
-        }
-
-        private static int CalculateOptimalBrightness(double blackMean, double whiteMean)
-        {
-            double currentMid = (blackMean + whiteMean) / 2;
-            return (int)Clamp(128 + (128 - currentMid), 30, 225);
-        }
-
-        /// <summary>
-        /// 计算图像质量评分
-        /// </summary>
-        public static double CalculateQualityScore(double sharpness, CheckerboardResult checkerboard)
-        {
-            // 清晰度评分(0-50分)
-            double sharpnessScore = Clamp(sharpness / 0.5, 0, 50);
-
-            // 对比度评分(0-50分)
-            double contrastScore = 0;
-            if (checkerboard.Detected)
-            {
-                contrastScore = Clamp(checkerboard.Contrast / 2, 0, 50);
-            }
-
-            return sharpnessScore + contrastScore;
-        }
-
-        /// <summary>
-        /// 生成建议
-        /// </summary>
-        public static List<string> GenerateSuggestions(double sharpness, CheckerboardResult checkerboard,
-            double sharpnessThreshold, double contrastThreshold)
-        {
-            var suggestions = new List<string>();
-
-            // 清晰度建议
-            if (sharpness < sharpnessThreshold)
-                suggestions.Add("图像模糊,请调整焦距使图像变清晰");
-            else if (sharpness < sharpnessThreshold * 2)
-                suggestions.Add("清晰度一般,可以继续微调焦距");
-            else
-                suggestions.Add("图像清晰度良好");
-
-            // 棋盘格建议
-            if (checkerboard.Detected)
-            {
-                if (checkerboard.Contrast < contrastThreshold)
-                    suggestions.Add("棋盘格对比度过低,建议调整光源");
-                else if (checkerboard.Contrast < contrastThreshold * 2)
-                    suggestions.Add("棋盘格对比度适中");
-                else
-                    suggestions.Add("棋盘格对比度很好");
-
-                suggestions.Add($"建议亮度值: {checkerboard.OptimalBrightness}");
-            }
-            else
-            {
-                suggestions.Add("未检测到棋盘格,请确保棋盘格在视野中");
-            }
-
-            return suggestions;
-        }
-
-        /// <summary>
-        /// 使用MathNet计算统计信息
-        /// </summary>
-        public static StatisticalSummary CalculateStatistics(List<double> data)
-        {
-            if (data == null || data.Count == 0)
-                return new StatisticalSummary();
-
-            // 使用MathNet.Numerics.Statistics计算
-            var stats = MathNet.Numerics.Statistics.Statistics.MeanVariance(data);
-
-            return new StatisticalSummary
-            {
-                Mean = stats.Item1,  // 均值
-                Variance = stats.Item2,  // 方差
-                StdDev = Math.Sqrt(stats.Item2),  // 标准差
-                Min = data.Min(),
-                Max = data.Max(),
-                Count = data.Count
-            };
-        }
-
-        /// <summary>
-        /// 使用MathNet计算更详细的统计信息
-        /// </summary>
-        public static StatisticalSummary CalculateDetailedStatistics(List<double> data)
-        {
-            if (data == null || data.Count == 0)
-                return new StatisticalSummary();
-
-            // 使用DescriptiveStatistics获取更多统计信息
-            var descriptiveStats = new MathNet.Numerics.Statistics.DescriptiveStatistics(data);
-
-            return new StatisticalSummary
-            {
-                Mean = descriptiveStats.Mean,
-                Variance = descriptiveStats.Variance,
-                StdDev = descriptiveStats.StandardDeviation,
-                Min = descriptiveStats.Minimum,
-                Max = descriptiveStats.Maximum,
-                Count = data.Count,
-                // 还可以添加更多统计信息
-                Skewness = descriptiveStats.Skewness,
-                Kurtosis = descriptiveStats.Kurtosis
-            };
-        }
-
-        /// <summary>
-        /// 计算移动平均
-        /// </summary>
-        public static List<double> CalculateMovingAverage(List<double> data, int windowSize)
-        {
-            if (data == null || data.Count == 0 || windowSize <= 0)
-                return new List<double>();
-
-            var result = new List<double>();
-
-            for (int i = 0; i < data.Count; i++)
-            {
-                int start = Math.Max(0, i - windowSize + 1);
-                int count = Math.Min(windowSize, i + 1);
-
-                double sum = 0;
-                for (int j = start; j <= i; j++)
-                {
-                    sum += data[j];
-                }
-                result.Add(sum / count);
-            }
-
-            return result;
-        }
-
-        /// <summary>
-        /// 计算指数移动平均
-        /// </summary>
-        public static List<double> CalculateExponentialMovingAverage(List<double> data, double alpha)
-        {
-            if (data == null || data.Count == 0 || alpha <= 0 || alpha > 1)
-                return new List<double>();
-
-            var result = new List<double> { data[0] };
-
-            for (int i = 1; i < data.Count; i++)
-            {
-                double ema = alpha * data[i] + (1 - alpha) * result[i - 1];
-                result.Add(ema);
-            }
-
-            return result;
-        }
-
-        /// <summary>
-        /// 检测峰值
-        /// </summary>
-        public static List<int> DetectPeaks(List<double> data, double threshold = 0.5)
-        {
-            var peaks = new List<int>();
-
-            if (data == null || data.Count < 3)
-                return peaks;
-
-            var stats = CalculateStatistics(data);
-            double mean = stats.Mean;
-            double stdDev = stats.StdDev;
-
-            for (int i = 1; i < data.Count - 1; i++)
-            {
-                if (data[i] > data[i - 1] && data[i] > data[i + 1])
-                {
-                    // 峰值需要超过阈值
-                    if (data[i] > mean + threshold * stdDev)
-                    {
-                        peaks.Add(i);
-                    }
-                }
-            }
-
-            return peaks;
-        }
-
-        /// <summary>
-        /// 计算趋势线(线性回归)
-        /// </summary>
-        public static (double slope, double intercept) CalculateTrendLine(List<double> data)
-        {
-            if (data == null || data.Count == 0)
-                return (0, 0);
-
-            var xData = Enumerable.Range(0, data.Count).Select(x => (double)x).ToArray();
-            var yData = data.ToArray();
-
-            // 使用MathNet进行线性回归
-            var fit = MathNet.Numerics.Fit.Line(xData, yData);
-
-            return (fit.Item2, fit.Item1);  // slope, intercept
-        }
-
-        /// <summary>
-        /// 计算自相关性
-        /// </summary>
-        public static List<double> CalculateAutocorrelation(List<double> data, int maxLag = 20)
-        {
-            if (data == null || data.Count == 0)
-                return new List<double>();
-
-            var autocorr = new List<double>();
-            var stats = CalculateStatistics(data);
-            double mean = stats.Mean;
-            double variance = stats.Variance;
-
-            if (variance == 0) return autocorr;
-
-            int n = data.Count;
-            maxLag = Math.Min(maxLag, n - 1);
-
-            for (int lag = 0; lag <= maxLag; lag++)
-            {
-                double sum = 0;
-                for (int i = 0; i < n - lag; i++)
-                {
-                    sum += (data[i] - mean) * (data[i + lag] - mean);
-                }
-                autocorr.Add(sum / ((n - lag) * variance));
-            }
-
-            return autocorr;
-        }
-    }
-
-    /// <summary>
-    /// 扩展的统计摘要类
-    /// </summary>
-    public class StatisticalSummary
-    {
-        public double Mean { get; set; }
-        public double Variance { get; set; }
-        public double StdDev { get; set; }
-        public double Min { get; set; }
-        public double Max { get; set; }
-        public int Count { get; set; }
-
-        // 扩展的统计信息
-        public double Skewness { get; set; }  // 偏度
-        public double Kurtosis { get; set; }  // 峰度
-
-        // 分位数(可选)
-        public double Median { get; set; }
-        public double Q1 { get; set; }  // 第一四分位数
-        public double Q3 { get; set; }  // 第三四分位数
-        public double IQR => Q3 - Q1;   // 四分位距
-
-        /// <summary>
-        /// 计算分位数
-        /// </summary>
-        public void CalculateQuantiles(List<double> data)
-        {
-            if (data == null || data.Count == 0)
-                return;
-
-            var sortedData = data.OrderBy(x => x).ToList();
-
-            // 中位数
-            Median = MathNet.Numerics.Statistics.Statistics.Median(sortedData);
-
-            // 四分位数
-            Q1 = MathNet.Numerics.Statistics.Statistics.Quantile(sortedData, 0.25);
-            Q3 = MathNet.Numerics.Statistics.Statistics.Quantile(sortedData, 0.75);
-        }
-
-        /// <summary>
-        /// 生成统计摘要字符串
-        /// </summary>
-        public string ToSummaryString()
-        {
-            return $@"统计摘要:
-样本数量: {Count}
-均值: {Mean:F3}
-标准差: {StdDev:F3}
-最小值: {Min:F3}
-最大值: {Max:F3}
-范围: {Max - Min:F3}
-方差: {Variance:F3}
-偏度: {Skewness:F3}
-峰度: {Kurtosis:F3}";
-        }
-
-        /// <summary>
-        /// 获取详细统计信息(包含分位数)
-        /// </summary>
-        public string ToDetailedString()
-        {
-            return $@"详细统计信息:
-样本数量: {Count}
-均值: {Mean:F3} ± {StdDev:F3}
-中位数: {Median:F3}
-第一四分位数(Q1): {Q1:F3}
-第三四分位数(Q3): {Q3:F3}
-四分位距(IQR): {IQR:F3}
-最小值: {Min:F3}
-最大值: {Max:F3}
-范围: {Max - Min:F3}
-方差: {Variance:F3}
-标准差: {StdDev:F3}
-变异系数: {(StdDev / Mean * 100):F1}%
-偏度: {Skewness:F3}
-峰度: {Kurtosis:F3}";
-        }
-    }
-
-    /// <summary>
-    /// 分析结果增强类
-    /// </summary>
-    public class EnhancedAnalysisResult : AnalysisResult
-    {
-        public StatisticalSummary SharpnessStats { get; set; }
-        public StatisticalSummary ContrastStats { get; set; }
-        public List<int> SharpnessPeaks { get; set; }
-        public double TrendSlope { get; set; }
-        public double TrendIntercept { get; set; }
-        public double AutocorrelationAtLag1 { get; set; }
-
-        public EnhancedAnalysisResult()
-        {
-            SharpnessStats = new StatisticalSummary();
-            ContrastStats = new StatisticalSummary();
-            SharpnessPeaks = new List<int>();
-        }
-    }
-
-    /// <summary>
-    /// 增强的分析引擎
-    /// </summary>
-    public static class EnhancedFocusAnalysisEngine
-    {
-        /// <summary>
-        /// 执行增强分析
-        /// </summary>
-        public static EnhancedAnalysisResult PerformEnhancedAnalysis(
-            List<DataPoint> historyData,
-            AnalysisResult baseResult)
-        {
-            var enhancedResult = new EnhancedAnalysisResult
-            {
-                // 复制基础结果
-                Sharpness = baseResult.Sharpness,
-                Checkerboard = baseResult.Checkerboard,
-                QualityScore = baseResult.QualityScore,
-                FrameCount = baseResult.FrameCount,
-                BestSharpness = baseResult.BestSharpness,
-                AnalysisTime = baseResult.AnalysisTime,
-                Suggestions = baseResult.Suggestions
-            };
-
-            if (historyData == null || historyData.Count == 0)
-                return enhancedResult;
-
-            // 提取清晰度和对比度数据
-            var sharpnessData = historyData.Select(d => d.Sharpness).ToList();
-            var contrastData = historyData
-                .Where(d => d.Contrast > 0)
-                .Select(d => d.Contrast)
-                .ToList();
-
-            // 计算统计信息
-            enhancedResult.SharpnessStats = FocusAnalysisEngine.CalculateDetailedStatistics(sharpnessData);
-            if (contrastData.Count > 0)
-            {
-                enhancedResult.ContrastStats = FocusAnalysisEngine.CalculateDetailedStatistics(contrastData);
-            }
-
-            // 计算分位数
-            enhancedResult.SharpnessStats.CalculateQuantiles(sharpnessData);
-
-            // 检测峰值
-            enhancedResult.SharpnessPeaks = FocusAnalysisEngine.DetectPeaks(sharpnessData, 1.0);
-
-            // 计算趋势线
-            var trend = FocusAnalysisEngine.CalculateTrendLine(sharpnessData);
-            enhancedResult.TrendSlope = trend.slope;
-            enhancedResult.TrendIntercept = trend.intercept;
-
-            // 计算自相关性
-            var autocorr = FocusAnalysisEngine.CalculateAutocorrelation(sharpnessData, 1);
-            if (autocorr.Count > 1)
-            {
-                enhancedResult.AutocorrelationAtLag1 = autocorr[1];
-            }
-
-            return enhancedResult;
-        }
-
-        /// <summary>
-        /// 生成增强分析报告
-        /// </summary>
-        public static string GenerateEnhancedReport(EnhancedAnalysisResult result)
-        {
-            var report = new System.Text.StringBuilder();
-
-            report.AppendLine("=== 增强分析报告 ===");
-            report.AppendLine($"分析时间: {result.AnalysisTime:yyyy-MM-dd HH:mm:ss}");
-            report.AppendLine($"总帧数: {result.FrameCount}");
-            report.AppendLine();
-
-            report.AppendLine("一、清晰度统计分析");
-            report.AppendLine(result.SharpnessStats.ToDetailedString());
-            report.AppendLine();
-
-            report.AppendLine("二、趋势分析");
-            report.AppendLine($"趋势线斜率: {result.TrendSlope:F6}");
-            report.AppendLine($"趋势线截距: {result.TrendIntercept:F3}");
-            report.AppendLine($"自相关性(lag=1): {result.AutocorrelationAtLag1:F3}");
-            report.AppendLine($"检测到峰值数量: {result.SharpnessPeaks.Count}");
-
-            if (result.SharpnessPeaks.Any())
-            {
-                report.Append("峰值位置(帧): ");
-                report.AppendLine(string.Join(", ", result.SharpnessPeaks));
-            }
-            report.AppendLine();
-
-            if (result.ContrastStats.Count > 0)
-            {
-                report.AppendLine("三、对比度统计分析");
-                report.AppendLine(result.ContrastStats.ToSummaryString());
-                report.AppendLine();
-            }
-
-            report.AppendLine("四、分析建议");
-            if (result.SharpnessPeaks.Count > 0)
-            {
-                int lastPeak = result.SharpnessPeaks.Last();
-                report.AppendLine($"发现清晰度峰值,最后峰值在第 {lastPeak + 1} 帧");
-
-                if (result.TrendSlope < -0.01)
-                    report.AppendLine("清晰度呈下降趋势,可能已过最佳对焦点");
-                else if (result.TrendSlope > 0.01)
-                    report.AppendLine("清晰度呈上升趋势,可继续当前方向调整");
-                else
-                    report.AppendLine("清晰度趋势平稳");
-            }
-
-            if (Math.Abs(result.AutocorrelationAtLag1) > 0.5)
-            {
-                report.AppendLine("数据具有较强自相关性,表明调整过程平稳");
-            }
-
-            return report.ToString();
-        }
-    }
-}

+ 8 - 6
TeamAAS-VM/Enums/AnalysisMode.cs

@@ -11,17 +11,19 @@ namespace TeamAAS_VP.Enums
     /// </summary>
     public enum AnalysisMode
     {
-        /// <summary>
-        /// 自动检测棋盘格
-        /// </summary>
-        AutoCheckerboard,
         /// <summary>
         /// 全图分析
         /// </summary>
         FullImage,
+
+        /// <summary>
+        /// ROI区域分析
+        /// </summary>
+        RoiOnly,
+
         /// <summary>
-        /// 自定义ROI
+        /// 棋盘格区域分析
         /// </summary>
-        CustomROI
+        ChessboardOnly
     }
 }

+ 25 - 0
TeamAAS-VM/Enums/DragHandleType.cs

@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Enums
+{
+    /// <summary>
+    /// 拖动控制点类型
+    /// </summary>
+    public enum DragHandleType
+    {
+        None,
+        TopLeft,
+        TopRight,
+        BottomLeft,
+        BottomRight,
+        Top,
+        Right,
+        Bottom,
+        Left,
+        Rotate
+    }
+}

+ 14 - 10
TeamAAS-VM/Enums/FocusMethod.cs

@@ -12,24 +12,28 @@ namespace TeamAAS_VP.Enums
     public enum FocusMethod
     {
         /// <summary>
-        /// Tenengrad梯度法(推荐)
+        /// 拉普拉斯算子
         /// </summary>
-        Tenengrad,
+        Laplacian,
+
         /// <summary>
-        /// 拉普拉斯方差法
+        /// Sobel算子
         /// </summary>
-        Laplacian,
+        Sobel,
+
         /// <summary>
-        /// Brenner梯度法
+        /// 方差
         /// </summary>
-        Brenner,
+        Variance,
+
         /// <summary>
-        /// 灰度方差法
+        /// Tenengrad算子
         /// </summary>
-        GrayVariance,
+        Tenengrad,
+
         /// <summary>
-        /// 灰度差分法
+        /// 频域分析
         /// </summary>
-        SMD
+        FrequencyDomain
     }
 }

+ 39 - 0
TeamAAS-VM/Enums/RoiOperationMode.cs

@@ -0,0 +1,39 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace TeamAAS_VP.Enums
+{
+    /// <summary>
+    /// ROI操作模式
+    /// </summary>
+    public enum RoiOperationMode
+    {
+        /// <summary>
+        /// 无操作
+        /// </summary>
+        None,           // 
+        /// <summary>
+        /// 绘制
+        /// </summary>
+        Draw,           // 
+        /// <summary>
+        /// 移动
+        /// </summary>
+        Move,           // 
+        /// <summary>
+        /// 调整大小
+        /// </summary>
+        Resize,         // 
+        /// <summary>
+        /// 旋转
+        /// </summary>
+        Rotate,         // 
+        /// <summary>
+        /// 角点调整
+        /// </summary>
+        CornerResize    // 
+    }
+}

+ 17 - 71
TeamAAS-VM/Models/AnalysisParameters.cs

@@ -1,96 +1,42 @@
-锘縰sing System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using System.Text;
-using System.Threading.Tasks;
 using TeamAAS_VP.Enums;
+using Prism.Mvvm;
 
 namespace TeamAAS_VP.Models
 {
     /// <summary>
-    /// 杈撳叆鍙傛暟
+    /// 分析参数
     /// </summary>
-    public class AnalysisParameters : INotifyPropertyChanged
+    public class AnalysisParameters : BindableBase
     {
-        private FocusMethod _focusMethod = FocusMethod.Tenengrad;
-        private AnalysisMode _analysisMode = AnalysisMode.AutoCheckerboard;
-        private int _targetBrightness = 128;
-        private double _sharpnessThreshold = 10;
-        private double _contrastThreshold = 50;
+        private FocusMethod _focusMethod = FocusMethod.Laplacian;
+        private AnalysisMode _analysisMode = AnalysisMode.FullImage;
         private bool _enableRealtimeAnalysis = true;
-        private bool _autoAdjustBrightness = true;
 
+        /// <summary>
+        /// 清晰度计算方法
+        /// </summary>
         public FocusMethod FocusMethod
         {
             get => _focusMethod;
-            set => SetField(ref _focusMethod, value);
+            set => SetProperty(ref _focusMethod, value);
         }
 
+        /// <summary>
+        /// 分析模式
+        /// </summary>
         public AnalysisMode AnalysisMode
         {
             get => _analysisMode;
-            set => SetField(ref _analysisMode, value);
-        }
-
-        public int TargetBrightness
-        {
-            get => _targetBrightness;
-            set => SetField(ref _targetBrightness, value);
-        }
-
-        public double SharpnessThreshold
-        {
-            get => _sharpnessThreshold;
-            set => SetField(ref _sharpnessThreshold, value);
-        }
-
-        public double ContrastThreshold
-        {
-            get => _contrastThreshold;
-            set => SetField(ref _contrastThreshold, value);
-        }
-
-        public bool EnableRealtimeAnalysis
-        {
-            get => _enableRealtimeAnalysis;
-            set => SetField(ref _enableRealtimeAnalysis, value);
-        }
-
-        public bool AutoAdjustBrightness
-        {
-            get => _autoAdjustBrightness;
-            set => SetField(ref _autoAdjustBrightness, value);
-        }
-
-        public event PropertyChangedEventHandler PropertyChanged;
-
-        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
-        {
-            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
-        }
-
-        protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
-        {
-            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
-            field = value;
-            OnPropertyChanged(propertyName);
-            return true;
+            set => SetProperty(ref _analysisMode, value);
         }
 
         /// <summary>
-        /// 閲嶇疆涓洪粯璁ゅ€�
+        /// 启用实时分析
         /// </summary>
-        public void ResetToDefaults()
+        public bool EnableRealtimeAnalysis
         {
-            FocusMethod = FocusMethod.Tenengrad;
-            AnalysisMode = AnalysisMode.AutoCheckerboard;
-            TargetBrightness = 128;
-            SharpnessThreshold = 10;
-            ContrastThreshold = 50;
-            EnableRealtimeAnalysis = true;
-            AutoAdjustBrightness = true;
+            get => _enableRealtimeAnalysis;
+            set => SetProperty(ref _enableRealtimeAnalysis, value);
         }
     }
 }

+ 0 - 69
TeamAAS-VM/Models/AnalysisReport.cs

@@ -1,69 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace TeamAAS_VP.Models
-{
-    /// <summary>
-    /// 最终报告
-    /// </summary>
-    public class AnalysisReport
-    {
-        public AnalysisParameters Parameters { get; set; }
-        public AnalysisResult FinalResult { get; set; }
-        public List<DataPoint> HistoryData { get; set; }
-        public DateTime StartTime { get; set; }
-        public DateTime EndTime { get; set; }
-        public TimeSpan Duration => EndTime - StartTime;
-
-        public AnalysisReport()
-        {
-            HistoryData = new List<DataPoint>();
-        }
-
-        public string GenerateTextReport()
-        {
-            return $@"工业相机图像质量分析报告
-生成时间:{EndTime:yyyy-MM-dd HH:mm:ss}
-分析时长:{Duration.TotalSeconds:F1}秒
-
-一、分析参数
------------
-清晰度算法:{Parameters.FocusMethod}
-分析模式:{Parameters.AnalysisMode}
-目标亮度:{Parameters.TargetBrightness}
-实时分析:{Parameters.EnableRealtimeAnalysis}
-
-二、最终结果
------------
-清晰度:{FinalResult.Sharpness:F2}
-最佳清晰度:{FinalResult.BestSharpness:F2}
-质量评分:{FinalResult.QualityScore:F1}/100
-分析帧数:{FinalResult.FrameCount}
-
-三、棋盘格分析
------------
-检测状态:{(FinalResult.Checkerboard.Detected ? "已检测" : "未检测")}
-黑色均值:{FinalResult.Checkerboard.BlackMean:F1}
-白色均值:{FinalResult.Checkerboard.WhiteMean:F1}
-对比度:{FinalResult.Checkerboard.Contrast:F1}
-建议亮度:{FinalResult.Checkerboard.OptimalBrightness}
-
-四、统计信息
------------
-总帧数:{HistoryData.Count}
-平均清晰度:{HistoryData.Average(d => d.Sharpness):F2}
-最大清晰度:{HistoryData.Max(d => d.Sharpness):F2}
-最小清晰度:{HistoryData.Min(d => d.Sharpness):F2}
-
-五、调整建议
------------
-{string.Join("\n", FinalResult.Suggestions)}
-
-------------------------
-报告结束";
-        }
-    }
-}

+ 35 - 50
TeamAAS-VM/Models/AnalysisResult.cs

@@ -1,82 +1,67 @@
-锘縰sing System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.ComponentModel;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using System.Text;
-using System.Threading.Tasks;
+using Prism.Mvvm;
+using System;
 
 namespace TeamAAS_VP.Models
 {
     /// <summary>
-    /// 缁煎悎缁撴灉
+    /// 分析结果
     /// </summary>
-    public class AnalysisResult : INotifyPropertyChanged
+    public class AnalysisResult : BindableBase
     {
         private double _sharpness;
-        private CheckerboardResult _checkerboard = new CheckerboardResult();
+        private double _contrast;
         private double _qualityScore;
-        private int _frameCount;
-        private double _bestSharpness;
-        private DateTime _analysisTime;
-        private ObservableCollection<string> _suggestions = new ObservableCollection<string>();
+        private DateTime _timestamp;
+        private string _message;
 
+        /// <summary>
+        /// 清晰度值
+        /// </summary>
         public double Sharpness
         {
             get => _sharpness;
-            set => SetField(ref _sharpness, value);
+            set => SetProperty(ref _sharpness, value);
         }
 
-        public CheckerboardResult Checkerboard
+        /// <summary>
+        /// 对比度值
+        /// </summary>
+        public double Contrast
         {
-            get => _checkerboard;
-            set => SetField(ref _checkerboard, value);
+            get => _contrast;
+            set => SetProperty(ref _contrast, value);
         }
 
+        /// <summary>
+        /// 质量评分 (0-100)
+        /// </summary>
         public double QualityScore
         {
             get => _qualityScore;
-            set => SetField(ref _qualityScore, value);
+            set => SetProperty(ref _qualityScore, value);
         }
 
-        public int FrameCount
+        /// <summary>
+        /// 时间戳
+        /// </summary>
+        public DateTime Timestamp
         {
-            get => _frameCount;
-            set => SetField(ref _frameCount, value);
+            get => _timestamp;
+            set => SetProperty(ref _timestamp, value);
         }
 
-        public double BestSharpness
+        /// <summary>
+        /// 消息
+        /// </summary>
+        public string Message
         {
-            get => _bestSharpness;
-            set => SetField(ref _bestSharpness, value);
+            get => _message;
+            set => SetProperty(ref _message, value);
         }
 
-        public DateTime AnalysisTime
+        public AnalysisResult()
         {
-            get => _analysisTime;
-            set => SetField(ref _analysisTime, value);
-        }
-
-        public ObservableCollection<string> Suggestions
-        {
-            get => _suggestions;
-            set => SetField(ref _suggestions, value);
-        }
-
-        public event PropertyChangedEventHandler PropertyChanged;
-
-        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
-        {
-            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
-        }
-
-        protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
-        {
-            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
-            field = value;
-            OnPropertyChanged(propertyName);
-            return true;
+            _timestamp = DateTime.Now;
         }
     }
 }

+ 0 - 67
TeamAAS-VM/Models/CheckerboardResult.cs

@@ -1,67 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace TeamAAS_VP.Models
-{
-    /// <summary>
-    /// 棋盘格分析结果
-    /// </summary>
-    public class CheckerboardResult : INotifyPropertyChanged
-    {
-        private bool _detected;
-        private double _blackMean;
-        private double _whiteMean;
-        private double _contrast;
-        private int _optimalBrightness;
-
-        public bool Detected
-        {
-            get => _detected;
-            set => SetField(ref _detected, value);
-        }
-
-        public double BlackMean
-        {
-            get => _blackMean;
-            set => SetField(ref _blackMean, value);
-        }
-
-        public double WhiteMean
-        {
-            get => _whiteMean;
-            set => SetField(ref _whiteMean, value);
-        }
-
-        public double Contrast
-        {
-            get => _contrast;
-            set => SetField(ref _contrast, value);
-        }
-
-        public int OptimalBrightness
-        {
-            get => _optimalBrightness;
-            set => SetField(ref _optimalBrightness, value);
-        }
-
-        public event PropertyChangedEventHandler PropertyChanged;
-
-        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
-        {
-            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
-        }
-
-        protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
-        {
-            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
-            field = value;
-            OnPropertyChanged(propertyName);
-            return true;
-        }
-    }
-}

+ 47 - 0
TeamAAS-VM/Models/ChessboardInfo.cs

@@ -0,0 +1,47 @@
+using OpenCvSharp;
+
+namespace TeamAAS_VP.Models
+{
+    /// <summary>
+    /// 棋盘格信息
+    /// </summary>
+    public class ChessboardInfo
+    {
+        /// <summary>
+        /// 是否检测到棋盘格
+        /// </summary>
+        public bool IsDetected { get; set; }
+
+        /// <summary>
+        /// 棋盘格角点数量(宽)
+        /// </summary>
+        public int CornersWidth { get; set; }
+
+        /// <summary>
+        /// 棋盘格角点数量(高)
+        /// </summary>
+        public int CornersHeight { get; set; }
+
+        /// <summary>
+        /// 检测到的角点
+        /// </summary>
+        public Point2f[] Corners { get; set; }
+
+        /// <summary>
+        /// 棋盘格边界矩形
+        /// </summary>
+        public Rect BoundingRect { get; set; }
+
+        /// <summary>
+        /// 检测置信度
+        /// </summary>
+        public double Confidence { get; set; }
+
+        public override string ToString()
+        {
+            return IsDetected 
+                ? $"检测成功: {CornersWidth}x{CornersHeight} 角点, 置信度: {Confidence:F2}" 
+                : "未检测到棋盘格";
+        }
+    }
+}

+ 73 - 0
TeamAAS-VM/Models/RoiModel.cs

@@ -0,0 +1,73 @@
+using Prism.Mvvm;
+using System.Windows;
+
+namespace TeamAAS_VP.Models
+{
+    /// <summary>
+    /// ROI模型
+    /// </summary>
+    public class RoiModel : BindableBase
+    {
+        private double _x;
+        private double _y;
+        private double _width;
+        private double _height;
+        private double _angle;
+
+        /// <summary>
+        /// X坐标
+        /// </summary>
+        public double X
+        {
+            get => _x;
+            set => SetProperty(ref _x, value);
+        }
+
+        /// <summary>
+        /// Y坐标
+        /// </summary>
+        public double Y
+        {
+            get => _y;
+            set => SetProperty(ref _y, value);
+        }
+
+        /// <summary>
+        /// 宽度
+        /// </summary>
+        public double Width
+        {
+            get => _width;
+            set => SetProperty(ref _width, value);
+        }
+
+        /// <summary>
+        /// 高度
+        /// </summary>
+        public double Height
+        {
+            get => _height;
+            set => SetProperty(ref _height, value);
+        }
+
+        /// <summary>
+        /// 旋转角度
+        /// </summary>
+        public double Angle
+        {
+            get => _angle;
+            set => SetProperty(ref _angle, value);
+        }
+
+        public bool IsValid => Width > 0 && Height > 0;
+
+        public Rect ToRect() => new Rect(X, Y, Width, Height);
+
+        public override string ToString()
+        {
+            return IsValid 
+                ? $"X={X:F0}, Y={Y:F0}, W={Width:F0}, H={Height:F0}, Angle={Angle:F1}°" 
+                : "未设置";
+        }
+    }
+}

+ 350 - 0
TeamAAS-VM/Services/CheckerboardDetectionService.cs

@@ -0,0 +1,350 @@
+using TeamAAS_VP.Models;
+using OpenCvSharp;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace TeamAAS_VP.Services
+{
+    /// <summary>
+    /// 棋盘格自动检测服务
+    /// </summary>
+    public class CheckerboardDetectionService
+    {
+        /// <summary>
+        /// 自动检测棋盘格(整图)
+        /// </summary>
+        /// <param name="image">输入图像</param>
+        /// <returns>棋盘格信息</returns>
+        public ChessboardInfo DetectChessboard(Mat image)
+        {
+            var info = new ChessboardInfo { IsDetected = false };
+
+            if (image == null || image.Empty())
+                return info;
+
+            try
+            {
+                // 转换为灰度图
+                Mat gray = new Mat();
+                if (image.Channels() == 3)
+                {
+                    Cv2.CvtColor(image, gray, ColorConversionCodes.BGR2GRAY);
+                }
+                else
+                {
+                    gray = image.Clone();
+                }
+
+                // 尝试不同的棋盘格尺寸
+                var possibleSizes = GeneratePossibleSizes(3, 15);
+
+                foreach (var size in possibleSizes)
+                {
+                    Point2f[] corners;
+
+                    bool found = Cv2.FindChessboardCornersSB(
+                        gray,
+                        size,
+                        out corners,
+                        ChessboardFlags.None);
+
+                    if (found && corners != null && corners.Length > 0)
+                    {
+                        // 亚像素精度优化
+                        var criteria = new TermCriteria(CriteriaTypes.Eps | CriteriaTypes.MaxIter, 30, 0.001);
+                        Cv2.CornerSubPix(gray, corners, new Size(11, 11), new Size(-1, -1), criteria);
+
+                        // 计算置信度
+                        double confidence = CalculateConfidence(gray, corners, size);
+
+                        // 只接受高置信度的检测结果
+                        if (confidence > 0.7)
+                        {
+                            info.IsDetected = true;
+                            info.CornersWidth = size.Width;
+                            info.CornersHeight = size.Height;
+                            info.Corners = corners;
+                            info.Confidence = confidence;
+                            info.BoundingRect = CalculateBoundingRect(corners);
+                            break;
+                        }
+                    }
+                }
+
+                gray?.Dispose();
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine($"棋盘格检测错误: {ex.Message}");
+            }
+
+            return info;
+        }
+
+        /// <summary>
+        /// 在指定旋转的 ROI 区域中检测棋盘格(支持旋转矩形)
+        /// roi: ROI 的像素矩形(外接矩形)
+        /// angleDegrees: ROI 相对于图像的旋转角度(度)
+        /// </summary>
+        public ChessboardInfo DetectChessboard(Mat image, OpenCvSharp.Rect roi, double angleDegrees)
+        {
+            var info = new ChessboardInfo { IsDetected = false };
+            if (image == null || image.Empty())
+                return info;
+
+            try
+            {
+                // 提取旋转裁剪图像
+                Point2f cropOrigin, rotationCenter;
+                using (var crop = ExtractRotatedRoi(image, roi, angleDegrees, out cropOrigin, out rotationCenter))
+                {
+                    if (crop == null || crop.Empty())
+                        return info;
+
+                    // 在裁剪图像上检测(整图检测函数会尝试多种规格)
+                    var subInfo = DetectChessboard(crop);
+                    if (subInfo == null || !subInfo.IsDetected)
+                        return info;
+
+                    // 将裁剪图像中的角点映射回原图坐标
+                    var mapped = MapCornersFromRotatedToOriginal(subInfo.Corners, cropOrigin, rotationCenter, angleDegrees);
+                    info.IsDetected = true;
+                    info.Corners = mapped;
+                    info.CornersWidth = subInfo.CornersWidth;
+                    info.CornersHeight = subInfo.CornersHeight;
+                    info.Confidence = subInfo.Confidence;
+
+                    // 重新计算边界
+                    info.BoundingRect = CalculateBoundingRect(info.Corners);
+                }
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine($"旋转ROI检测错误: {ex.Message}");
+            }
+
+            return info;
+        }
+
+        /// <summary>
+        /// 从原图中提取旋转后的ROI(将图像绕ROI中心反向旋转后裁剪)
+        /// 返回裁剪图像,并通过out参数返回裁剪在旋转后图像中的原点和旋转中心
+        /// </summary>
+        public Mat ExtractRotatedRoi(Mat src, OpenCvSharp.Rect roi, double angleDegrees, out Point2f cropOrigin, out Point2f rotationCenter)
+        {
+            cropOrigin = new Point2f(0, 0);
+            rotationCenter = new Point2f(0, 0);
+
+            if (src == null || src.Empty())
+                return null;
+
+            if (roi.Width <= 0 || roi.Height <= 0)
+                return null;
+
+            // compute center of ROI in source image coords
+            float cx = roi.X + roi.Width / 2.0f;
+            float cy = roi.Y + roi.Height / 2.0f;
+            rotationCenter = new Point2f(cx, cy);
+
+            // rotate entire image by -angle around center so that the rotated ROI becomes axis-aligned
+            Mat rotated = new Mat();
+            var M = Cv2.GetRotationMatrix2D(new Point2f(cx, cy), (float)-angleDegrees, 1.0);
+            Cv2.WarpAffine(src, rotated, M, new Size(src.Width, src.Height), InterpolationFlags.Linear, BorderTypes.Constant, Scalar.All(0));
+
+            // after rotation the ROI center remains at (cx,cy); crop axis-aligned rectangle with same width/height
+            int x = (int)Math.Round(cx - roi.Width / 2.0);
+            int y = (int)Math.Round(cy - roi.Height / 2.0);
+
+            // clamp
+            x = Math.Max(0, Math.Min(x, rotated.Width - 1));
+            y = Math.Max(0, Math.Min(y, rotated.Height - 1));
+            int w = Math.Min(roi.Width, rotated.Width - x);
+            int h = Math.Min(roi.Height, rotated.Height - y);
+
+            if (w <= 0 || h <= 0)
+            {
+                rotated.Dispose();
+                return null;
+            }
+
+            cropOrigin = new Point2f(x, y);
+            var crop = new Mat(rotated, new OpenCvSharp.Rect(x, y, w, h)).Clone();
+            rotated.Dispose();
+            return crop;
+        }
+
+        /// <summary>
+        /// 将在旋转后裁剪图像中检测到的角点映射回原图像坐标
+        /// </summary>
+        public Point2f[] MapCornersFromRotatedToOriginal(Point2f[] cornersInCrop, Point2f cropOrigin, Point2f rotationCenter, double angleDegrees)
+        {
+            if (cornersInCrop == null || cornersInCrop.Length == 0)
+                return cornersInCrop;
+
+            var mapped = new Point2f[cornersInCrop.Length];
+            double angleRad = angleDegrees * Math.PI / 180.0;
+            double cos = Math.Cos(angleRad);
+            double sin = Math.Sin(angleRad);
+
+            for (int i = 0; i < cornersInCrop.Length; i++)
+            {
+                // position in rotated image (absolute)
+                double rx = cropOrigin.X + cornersInCrop[i].X;
+                double ry = cropOrigin.Y + cornersInCrop[i].Y;
+
+                // translate to rotation center
+                double dx = rx - rotationCenter.X;
+                double dy = ry - rotationCenter.Y;
+
+                // rotate back by +angle to original image coordinates
+                double ox = cos * dx - sin * dy + rotationCenter.X;
+                double oy = sin * dx + cos * dy + rotationCenter.Y;
+
+                mapped[i] = new Point2f((float)ox, (float)oy);
+            }
+
+            return mapped;
+        }
+
+        /// <summary>
+        /// 生成可能的棋盘格尺寸
+        /// </summary>
+        private List<Size> GeneratePossibleSizes(int minSize, int maxSize)
+        {
+            var sizes = new List<Size>();
+
+            // 常见的棋盘格尺寸
+            var commonSizes = new[]
+            {
+                new Size(9, 6),   // 标准标定板
+                new Size(8, 6),
+                new Size(10, 7),
+                new Size(11, 8),
+                new Size(9, 7),
+                new Size(7, 5),
+                new Size(6, 4),
+                new Size(8, 5),
+            };
+
+            sizes.AddRange(commonSizes);
+
+            // 添加其他可能的尺寸
+            for (int w = minSize; w <= maxSize; w++)
+            {
+                for (int h = minSize; h <= maxSize; h++)
+                {
+                    var size = new Size(w, h);
+                    if (!sizes.Any(s => s.Width == w && s.Height == h))
+                    {
+                        sizes.Add(size);
+                    }
+                }
+            }
+
+            return sizes;
+        }
+
+        /// <summary>
+        /// 计算检测置信度
+        /// </summary>
+        private double CalculateConfidence(Mat gray, Point2f[] corners, Size patternSize)
+        {
+            if (corners == null || corners.Length == 0)
+                return 0;
+
+            double confidence = 0;
+
+            try
+            {
+                // 1. 检查角点的规律性 (通过计算角点间距的标准差)
+                var distances = new List<double>();
+                for (int i = 0; i < corners.Length - 1; i++)
+                {
+                    double dist = Math.Sqrt(
+                        Math.Pow(corners[i + 1].X - corners[i].X, 2) +
+                        Math.Pow(corners[i + 1].Y - corners[i].Y, 2));
+                    distances.Add(dist);
+                }
+
+                if (distances.Count > 0)
+                {
+                    double avgDist = distances.Average();
+                    double variance = distances.Sum(d => Math.Pow(d - avgDist, 2)) / distances.Count;
+                    double stdDev = Math.Sqrt(variance);
+                    
+                    // 标准差越小,规律性越好
+                    double regularityScore = Math.Max(0, 1 - (stdDev / avgDist));
+                    confidence += regularityScore * 0.5;
+                }
+
+                // 2. 检查角点数量是否完全匹配
+                int expectedCorners = patternSize.Width * patternSize.Height;
+                if (corners.Length == expectedCorners)
+                {
+                    confidence += 0.3;
+                }
+
+                // 3. 检查角点是否在图像范围内
+                int validCorners = corners.Count(c => 
+                    c.X >= 0 && c.X < gray.Width && 
+                    c.Y >= 0 && c.Y < gray.Height);
+                
+                confidence += (validCorners / (double)corners.Length) * 0.2;
+            }
+            catch
+            {
+                confidence = 0.5; // 默认中等置信度
+            }
+
+            return Math.Min(1.0, confidence);
+        }
+
+        /// <summary>
+        /// 计算边界矩形
+        /// </summary>
+        private OpenCvSharp.Rect CalculateBoundingRect(Point2f[] corners)
+        {
+            if (corners == null || corners.Length == 0)
+                return new OpenCvSharp.Rect();
+
+            float minX = corners.Min(c => c.X);
+            float minY = corners.Min(c => c.Y);
+            float maxX = corners.Max(c => c.X);
+            float maxY = corners.Max(c => c.Y);
+
+            return new OpenCvSharp.Rect(
+                (int)minX,
+                (int)minY,
+                (int)(maxX - minX),
+                (int)(maxY - minY));
+        }
+
+        /// <summary>
+        /// 在图像上绘制棋盘格角点
+        /// </summary>
+        public void DrawChessboard(Mat image, ChessboardInfo info)
+        {
+            if (image == null || !info.IsDetected || info.Corners == null)
+                return;
+
+            try
+            {
+                var patternSize = new Size(info.CornersWidth, info.CornersHeight);
+                Cv2.DrawChessboardCorners(image, patternSize, info.Corners, true);
+
+                // 绘制边界矩形
+                Cv2.Rectangle(image, info.BoundingRect, new Scalar(0, 255, 0), 2);
+
+                // 显示信息
+                string text = $"{info.CornersWidth}x{info.CornersHeight} ({info.Confidence:F2})";
+                Cv2.PutText(image, text, new Point(10, 30), 
+                    HersheyFonts.HersheySimplex, 0.8, new Scalar(0, 255, 0), 2);
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine($"绘制棋盘格错误: {ex.Message}");
+            }
+        }
+    }
+}

+ 60 - 0
TeamAAS-VM/Services/FileDialogService.cs

@@ -0,0 +1,60 @@
+using Microsoft.Win32;
+using System.IO;
+
+namespace TeamAAS_VP.Services
+{
+    /// <summary>
+    /// 文件对话框服务
+    /// </summary>
+    public class FileDialogService
+    {
+        /// <summary>
+        /// 打开图像文件对话框
+        /// </summary>
+        public string OpenImageFile()
+        {
+            var dialog = new OpenFileDialog
+            {
+                Title = "选择图像文件",
+                Filter = "图像文件|*.jpg;*.jpeg;*.png;*.bmp;*.tiff;*.tif|所有文件|*.*",
+                FilterIndex = 1,
+                RestoreDirectory = true
+            };
+
+            if (dialog.ShowDialog() == true)
+            {
+                return dialog.FileName;
+            }
+
+            return null;
+        }
+
+        /// <summary>
+        /// 保存文件对话框
+        /// </summary>
+        public string SaveFile(string defaultFileName, string filter)
+        {
+            var dialog = new SaveFileDialog
+            {
+                FileName = defaultFileName,
+                Filter = filter,
+                RestoreDirectory = true
+            };
+
+            if (dialog.ShowDialog() == true)
+            {
+                return dialog.FileName;
+            }
+
+            return null;
+        }
+
+        /// <summary>
+        /// 验证文件是否存在
+        /// </summary>
+        public bool FileExists(string filePath)
+        {
+            return !string.IsNullOrEmpty(filePath) && File.Exists(filePath);
+        }
+    }
+}

+ 309 - 0
TeamAAS-VM/Services/ImageAnalysisService.cs

@@ -0,0 +1,309 @@
+using TeamAAS_VP.Enums;
+using TeamAAS_VP.Models;
+using OpenCvSharp;
+using System;
+
+namespace TeamAAS_VP.Services
+{
+    /// <summary>
+    /// 图像分析服务
+    /// </summary>
+    public class ImageAnalysisService
+    {
+        /// <summary>
+        /// 分析图像清晰度和对比度
+        /// </summary>
+        public AnalysisResult AnalyzeImage(Mat image, FocusMethod method, Rect? roi = null)
+        {
+            var result = new AnalysisResult { Timestamp = DateTime.Now };
+
+            if (image == null || image.Empty())
+            {
+                result.Message = "图像为空";
+                return result;
+            }
+
+            try
+            {
+                Mat analyzeMat = image;
+
+                // 如果指定了ROI,则裁剪图像
+                if (roi.HasValue && roi.Value.Width > 0 && roi.Value.Height > 0)
+                {
+                    var roiRect = roi.Value;
+                    // 确保ROI在图像范围内
+                    roiRect.X = Math.Max(0, Math.Min(roiRect.X, image.Width - 1));
+                    roiRect.Y = Math.Max(0, Math.Min(roiRect.Y, image.Height - 1));
+                    roiRect.Width = Math.Min(roiRect.Width, image.Width - roiRect.X);
+                    roiRect.Height = Math.Min(roiRect.Height, image.Height - roiRect.Y);
+
+                    if (roiRect.Width > 0 && roiRect.Height > 0)
+                    {
+                        analyzeMat = new Mat(image, roiRect);
+                    }
+                }
+
+                // 转换为灰度图
+                Mat gray = new Mat();
+                if (analyzeMat.Channels() == 3)
+                {
+                    Cv2.CvtColor(analyzeMat, gray, ColorConversionCodes.BGR2GRAY);
+                }
+                else
+                {
+                    gray = analyzeMat.Clone();
+                }
+
+                // 计算清晰度
+                result.Sharpness = CalculateSharpness(gray, method);
+
+                // 计算对比度
+                result.Contrast = CalculateContrast(gray);
+
+                // 计算质量评分 (0-100)
+                result.QualityScore = CalculateQualityScore(result.Sharpness, result.Contrast, method);
+
+                result.Message = "分析完成";
+
+                gray?.Dispose();
+                if (roi.HasValue && analyzeMat != image)
+                {
+                    analyzeMat?.Dispose();
+                }
+            }
+            catch (Exception ex)
+            {
+                result.Message = $"分析错误: {ex.Message}";
+            }
+
+            return result;
+        }
+
+        /// <summary>
+        /// 计算清晰度
+        /// </summary>
+        private double CalculateSharpness(Mat gray, FocusMethod method)
+        {
+            switch (method)
+            {
+                case FocusMethod.Laplacian:
+                    return CalculateLaplacianVariance(gray);
+
+                case FocusMethod.Sobel:
+                    return CalculateSobelVariance(gray);
+
+                case FocusMethod.Variance:
+                    return CalculateImageVariance(gray);
+
+                case FocusMethod.Tenengrad:
+                    return CalculateTenengrad(gray);
+
+                case FocusMethod.FrequencyDomain:
+                    return CalculateFrequencyDomain(gray);
+
+                default:
+                    return CalculateLaplacianVariance(gray);
+            }
+        }
+
+        /// <summary>
+        /// Laplacian方差法
+        /// </summary>
+        private double CalculateLaplacianVariance(Mat gray)
+        {
+            using (var laplacian = new Mat())
+            {
+                Cv2.Laplacian(gray, laplacian, MatType.CV_64F);
+                Cv2.MeanStdDev(laplacian, out _, out Scalar stddev);
+                return stddev.Val0 * stddev.Val0;
+            }
+        }
+
+        /// <summary>
+        /// Sobel方差法
+        /// </summary>
+        private double CalculateSobelVariance(Mat gray)
+        {
+            using (var sobelX = new Mat())
+            using (var sobelY = new Mat())
+            using (var sobel = new Mat())
+            {
+                Cv2.Sobel(gray, sobelX, MatType.CV_64F, 1, 0, 3);
+                Cv2.Sobel(gray, sobelY, MatType.CV_64F, 0, 1, 3);
+                
+                Cv2.Magnitude(sobelX, sobelY, sobel);
+                
+                return Cv2.Mean(sobel).Val0;
+            }
+        }
+
+        /// <summary>
+        /// 图像方差法
+        /// </summary>
+        private double CalculateImageVariance(Mat gray)
+        {
+            Cv2.MeanStdDev(gray, out _, out Scalar stddev);
+            return stddev.Val0 * stddev.Val0;
+        }
+
+        /// <summary>
+        /// Tenengrad算子
+        /// </summary>
+        private double CalculateTenengrad(Mat gray)
+        {
+            using (var sobelX = new Mat())
+            using (var sobelY = new Mat())
+            {
+                Cv2.Sobel(gray, sobelX, MatType.CV_64F, 1, 0, 3);
+                Cv2.Sobel(gray, sobelY, MatType.CV_64F, 0, 1, 3);
+
+                double sum = 0;
+                for (int y = 0; y < gray.Rows; y++)
+                {
+                    for (int x = 0; x < gray.Cols; x++)
+                    {
+                        double gx = sobelX.At<double>(y, x);
+                        double gy = sobelY.At<double>(y, x);
+                        double magnitude = Math.Sqrt(gx * gx + gy * gy);
+                        
+                        // 只计算超过阈值的梯度
+                        if (magnitude > 50)
+                        {
+                            sum += magnitude * magnitude;
+                        }
+                    }
+                }
+
+                return sum / (gray.Rows * gray.Cols);
+            }
+        }
+
+        /// <summary>
+        /// 频域分析法
+        /// </summary>
+        private double CalculateFrequencyDomain(Mat gray)
+        {
+            try
+            {
+                // 转换为浮点型
+                Mat floatMat = new Mat();
+                gray.ConvertTo(floatMat, MatType.CV_32F);
+
+                // 执行DFT
+                Mat dft = new Mat();
+                Cv2.Dft(floatMat, dft, DftFlags.ComplexOutput);
+
+                // 计算幅度谱
+                Mat[] planes = Cv2.Split(dft);
+                Mat magnitude = new Mat();
+                Cv2.Magnitude(planes[0], planes[1], magnitude);
+
+                // 计算高频能量占比
+                int centerX = magnitude.Cols / 2;
+                int centerY = magnitude.Rows / 2;
+                int radius = Math.Min(centerX, centerY) / 3;
+
+                double totalEnergy = Cv2.Sum(magnitude).Val0;
+                
+                // 屏蔽低频区域
+                Cv2.Circle(magnitude, new Point(centerX, centerY), radius, Scalar.All(0), -1);
+                
+                double highFreqEnergy = Cv2.Sum(magnitude).Val0;
+
+                floatMat?.Dispose();
+                dft?.Dispose();
+                foreach (var plane in planes) plane?.Dispose();
+                magnitude?.Dispose();
+
+                return totalEnergy > 0 ? (highFreqEnergy / totalEnergy) * 100 : 0;
+            }
+            catch
+            {
+                return 0;
+            }
+        }
+
+        /// <summary>
+        /// 计算对比度
+        /// </summary>
+        private double CalculateContrast(Mat gray)
+        {
+            try
+            {
+                // 使用标准差作为对比度指标
+                Cv2.MeanStdDev(gray, out Scalar mean, out Scalar stddev);
+                
+                // 归一化对比度 (0-100)
+                double contrast = (stddev.Val0 / 128.0) * 100;
+                
+                return Math.Min(100, contrast);
+            }
+            catch
+            {
+                return 0;
+            }
+        }
+
+        /// <summary>
+        /// 计算质量评分
+        /// </summary>
+        private double CalculateQualityScore(double sharpness, double contrast, FocusMethod method)
+        {
+            // 根据不同的算法,设置不同的归一化参数
+            double normalizedSharpness = 0;
+
+            switch (method)
+            {
+                case FocusMethod.Laplacian:
+                    normalizedSharpness = Math.Min(100, (sharpness / 50.0) * 100);
+                    break;
+                case FocusMethod.Sobel:
+                    normalizedSharpness = Math.Min(100, (sharpness / 30.0) * 100);
+                    break;
+                case FocusMethod.Variance:
+                    normalizedSharpness = Math.Min(100, (sharpness / 5000.0) * 100);
+                    break;
+                case FocusMethod.Tenengrad:
+                    normalizedSharpness = Math.Min(100, (sharpness / 1000.0) * 100);
+                    break;
+                case FocusMethod.FrequencyDomain:
+                    normalizedSharpness = sharpness;
+                    break;
+            }
+
+            // 综合清晰度和对比度
+            double score = (normalizedSharpness * 0.7 + contrast * 0.3);
+            
+            return Math.Min(100, Math.Max(0, score));
+        }
+
+        /// <summary>
+        /// 获取ROI区域图像
+        /// </summary>
+        public Mat GetRoiImage(Mat image, Rect roi)
+        {
+            if (image == null || image.Empty())
+                return null;
+
+            try
+            {
+                // 确保ROI在图像范围内
+                roi.X = Math.Max(0, Math.Min(roi.X, image.Width - 1));
+                roi.Y = Math.Max(0, Math.Min(roi.Y, image.Height - 1));
+                roi.Width = Math.Min(roi.Width, image.Width - roi.X);
+                roi.Height = Math.Min(roi.Height, image.Height - roi.Y);
+
+                if (roi.Width > 0 && roi.Height > 0)
+                {
+                    return new Mat(image, roi).Clone();
+                }
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine($"获取ROI图像错误: {ex.Message}");
+            }
+
+            return null;
+        }
+    }
+}

+ 8 - 3
TeamAAS-VM/TeamAAS-VP.csproj

@@ -558,7 +558,6 @@
     <Compile Include="Core\BgModbusTcpCommunicate.cs" />
     <Compile Include="Core\BraceFoldingStrategy.cs" />
     <Compile Include="Core\Cameras\CameraBase.cs" />
-    <Compile Include="Core\FocusAnalysisEngine.cs" />
     <Compile Include="Core\Lights\ICommunicationProtocol.cs" />
     <Compile Include="Core\Lights\ILightChannel.cs" />
     <Compile Include="Core\Lights\ILightController.cs" />
@@ -575,8 +574,10 @@
     <Compile Include="Data\DatabaseInitializer.cs" />
     <Compile Include="Data\SystemDatabaseService.cs" />
     <Compile Include="Enums\AnalysisMode.cs" />
+    <Compile Include="Enums\DragHandleType.cs" />
     <Compile Include="Enums\FocusMethod.cs" />
     <Compile Include="Enums\OutputPointMode.cs" />
+    <Compile Include="Enums\RoiOperationMode.cs" />
     <Compile Include="Interfaces\ICalibrationService.cs" />
     <Compile Include="Interfaces\ICameraService.cs" />
     <Compile Include="Interfaces\IConfigService.cs" />
@@ -588,9 +589,8 @@
     <Compile Include="Interfaces\ISystemDatabaseService.cs" />
     <Compile Include="Models\AlarmRecord.cs" />
     <Compile Include="Models\AnalysisParameters.cs" />
-    <Compile Include="Models\AnalysisReport.cs" />
     <Compile Include="Models\AnalysisResult.cs" />
-    <Compile Include="Models\CheckerboardResult.cs" />
+    <Compile Include="Models\ChessboardInfo.cs" />
     <Compile Include="Models\DataPoint.cs" />
     <Compile Include="Models\Lights\ChannelConfig.cs" />
     <Compile Include="Models\Lights\LightControllerConfig.cs" />
@@ -598,6 +598,7 @@
     <Compile Include="Models\ProductionStatQuery.cs" />
     <Compile Include="Models\ProductionStatResult.cs" />
     <Compile Include="Models\Product\ProcedureUserDefineParam.cs" />
+    <Compile Include="Models\RoiModel.cs" />
     <Compile Include="Models\SerialPortConfig.cs" />
     <Compile Include="Models\SystemConfiguration.cs" />
     <Compile Include="Models\TcpConfig.cs" />
@@ -613,7 +614,10 @@
     <Compile Include="Core\GalaxyMethod\CWin32Bitmaps.cs" />
     <Compile Include="Core\IniConfigHelper.cs" />
     <Compile Include="Core\PLCs\OpcUaClientPLC.cs" />
+    <Compile Include="Services\CheckerboardDetectionService.cs" />
     <Compile Include="Services\ConfigService.cs" />
+    <Compile Include="Services\FileDialogService.cs" />
+    <Compile Include="Services\ImageAnalysisService.cs" />
     <Compile Include="Services\LightManagerService.cs" />
     <Compile Include="Services\PlcService.cs" />
     <Compile Include="Core\Robots\FanucRobot.cs" />
@@ -751,6 +755,7 @@
     <Compile Include="ValueConverter\RobotBrandToVisibiltyConverter.cs" />
     <Compile Include="ValueConverter\RobotConverter.cs" />
     <Compile Include="ValueConverter\RobotIdToVisibiltyConverter.cs" />
+    <Compile Include="ValueConverter\RoiToTextConverter.cs" />
     <Compile Include="ValueConverter\StringFormatConverter.cs" />
     <Compile Include="ViewModels\DebugMod\LightManualViewModel.cs" />
     <Compile Include="ViewModels\Setting\AddLightControllerViewModel.cs" />

+ 56 - 0
TeamAAS-VM/ValueConverter/RoiToTextConverter.cs

@@ -0,0 +1,56 @@
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+
+namespace TeamAAS_VP.ValueConverter
+{
+    public class RoiToTextConverter : IMultiValueConverter
+    {
+        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+        {
+            try
+            {
+                if (values == null || values.Length < 5)
+                    return "δÉèÖÃ";
+
+                // Helper to get numeric value from different value types
+                double GetDouble(object v)
+                {
+                    if (v == null) return double.NaN;
+                    if (v is double d) return d;
+                    if (v is float f) return f;
+                    if (v is int i) return i;
+                    if (v is long l) return l;
+                    if (v is short s) return s;
+                    if (v is string s2 && double.TryParse(s2, out var p)) return p;
+                    if (v == DependencyProperty.UnsetValue) return double.NaN;
+                    return double.NaN;
+                }
+
+                double x = GetDouble(values[0]);
+                double y = GetDouble(values[1]);
+                double w = GetDouble(values[2]);
+                double h = GetDouble(values[3]);
+                double angle = GetDouble(values[4]);
+
+                if (double.IsNaN(x) || double.IsNaN(y) || double.IsNaN(w) || double.IsNaN(h) || double.IsNaN(angle))
+                    return "δÉèÖÃ";
+
+                if (w <= 0 || h <= 0)
+                    return "δÉèÖÃ";
+
+                return $"X={x:F0}, Y={y:F0}, W={w:F0}, H={h:F0}, Angle={angle:F1}¡ã";
+            }
+            catch
+            {
+                return "δÉèÖÃ";
+            }
+        }
+
+        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+        {
+            throw new NotImplementedException();
+        }
+    }
+}