mrDarker
2025-08-16 df45966c52bac2eb465cf05c1d6328bf0d00c5ac
EdgeInspector_App/Data/PostProcess.cpp
@@ -1,4 +1,4 @@
#include "StdAfx.h"
#include "StdAfx.h"
#include "PostProcess.h"
#include "Config.h"
#include "FreeImage.h"
@@ -172,58 +172,41 @@
   return TRUE;
}
void CPostProcess::SaveDefectData()
void CPostProcess::SaveMeasureData(CString strGlassID, CString strTime)
{
   CString glass_id;
   glass_id.Format(_T("%s"), g_pBase->m_strHPanelID);
   if (!m_pGlassData) {
      return;
   }
   if (glass_id.IsEmpty() == TRUE)
      glass_id.Format(_T("MANUAL_ID"));
   double dTFTYOff = 0.0;
   double dTFTXOff = 0.0;
   // 获取当前产品加载时间
   CTime tGlassLoading = m_pGlassData->GetLoadingTime();
   auto* pSideA = m_pGlassData->GetSideData(DIMENSION_A);
   auto* pSideB = m_pGlassData->GetSideData(DIMENSION_B);
   if (!pSideA || !pSideB) {
      return;
   }
   CString measure_data;
   CString chip_data;
   CString defect_data;
   CString   strTime = g_pBase->m_strLoadingTime;
   double nPanelSizeCF_X = ((pSideB->m_nGlassEndLine - pSideB->m_nGlassStartLine) * pSideB->m_dPixelSizeY / 1000.0);
   double nPanelSizeCF_Y = ((pSideA->m_nGlassEndLine - pSideA->m_nGlassStartLine) * pSideA->m_dPixelSizeY / 1000.0);
   double nPanelSizeTFT_X = (((pSideB->m_nGlassEndLine - pSideB->m_nGlassStartLine) * pSideB->m_dPixelSizeY - dTFTXOff) / 1000.0);
   double nPanelSizeTFT_Y = (((pSideA->m_nGlassEndLine - pSideA->m_nGlassStartLine) * pSideA->m_dPixelSizeY - dTFTYOff) / 1000.0);
   double dTFTYOff = 0;
   //double dSumTFTYOff = 0;
   //int nCountTFTYOff = 0;
   //for (int nFrameIdx = 0; nFrameIdx < MAX_IMAGE_FRAME; nFrameIdx++)
   //{
   //   if (m_pGlassData->GetSideData(DIMENSION_B)->m_nSide_Electrode_Result_um[nFrameIdx] == -1) continue;
   //   dSumTFTYOff += m_pGlassData->GetSideData(DIMENSION_B)->m_nSide_Electrode_Result_um[nFrameIdx];
   //   nCountTFTYOff++;
   //}
   //if (nCountTFTYOff > 0)
   //   dTFTYOff = dSumTFTYOff / nCountTFTYOff;
   int unitNo = m_pTransData ? m_pTransData->m_nUnitNo : 0;
   int eqpNo = m_pTransData ? m_pTransData->m_nEqpNo : 0;
   int isGrind = m_pTransData ? m_pTransData->m_nisGrind : 0;
   int roughPad = m_pTransData ? m_pTransData->m_nRoughPadLayer : 0;
   double dTFTXOff = 0;
   //double dSumTFTXOff = 0;
   //int nCountTFTXOff = 0;
   //for (int nFrameIdx = 0; nFrameIdx < MAX_IMAGE_FRAME; nFrameIdx++)
   //{
   //   if (m_pGlassData->GetSideData(DIMENSION_A)->m_nSide_Electrode_Result_um[nFrameIdx] == -1) continue;
   //   dSumTFTXOff += m_pGlassData->GetSideData(DIMENSION_A)->m_nSide_Electrode_Result_um[nFrameIdx];
   //   nCountTFTXOff++;
   //}
   //if (nCountTFTXOff > 0)
   //   dTFTXOff = dSumTFTXOff / nCountTFTXOff;
   double nPanelSizeCF_X = ((m_pGlassData->GetSideData(DIMENSION_B)->m_nGlassEndLine - m_pGlassData->GetSideData(DIMENSION_B)->m_nGlassStartLine) * m_pGlassData->GetSideData(DIMENSION_B)->m_dPixelSizeY / 1000.0);
   double nPanelSizeCF_Y = ((m_pGlassData->GetSideData(DIMENSION_A)->m_nGlassEndLine - m_pGlassData->GetSideData(DIMENSION_A)->m_nGlassStartLine) * m_pGlassData->GetSideData(DIMENSION_A)->m_dPixelSizeY / 1000.0);
   double nPanelSizeTFT_X = (((m_pGlassData->GetSideData(DIMENSION_B)->m_nGlassEndLine - m_pGlassData->GetSideData(DIMENSION_B)->m_nGlassStartLine) * m_pGlassData->GetSideData(DIMENSION_B)->m_dPixelSizeY - dTFTXOff) / 1000.0);
   double nPanelSizeTFT_Y = (((m_pGlassData->GetSideData(DIMENSION_A)->m_nGlassEndLine - m_pGlassData->GetSideData(DIMENSION_A)->m_nGlassStartLine) * m_pGlassData->GetSideData(DIMENSION_A)->m_dPixelSizeY - dTFTYOff) / 1000.0);
   measure_data.AppendFormat(_T("%s,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%f,%f,%f,%f,%d,%d,%d,%d,%d,%d,%d,%d"),
   CString strBody;
   strBody.AppendFormat(_T("%s,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,")
      _T("%f,%f,%f,%f,")
      _T("%d,%d,%d,%d,%d,%d,%d,%d\r\n"),
      strTime,
      glass_id,
      m_pTransData->m_nUnitNo,
      m_pTransData->m_nEqpNo,
      m_pTransData->m_nisGrind,
      m_pTransData->m_nRoughPadLayer,
      strGlassID,
      unitNo,
      eqpNo,
      isGrind,
      roughPad,
      MeasrueCutLineResult(DIMENSION_A),
      MeasrueCutLineResult(DIMENSION_B),
      MeasrueCutLineResult(DIMENSION_C),
@@ -245,231 +228,251 @@
      m_pGlassData->GetSideData(DIMENSION_C)->m_nBottomCornerWidth,
      m_pGlassData->GetSideData(DIMENSION_C)->m_nBottomCornerHeight
   );
   measure_data.Append(_T("\r\n"));
   CString measure_file_path;
   if (m_pHardware->m_bSaveResultByHour) {
      // 按小时保存结果
      measure_file_path.Format(_T("%s\\%s_%02d_MeasureData.csv"), m_strResultFolder, g_pBase->m_strLoadingDay, tGlassLoading.GetHour());
   }
   else {
      // 不按小时保存结果
      measure_file_path.Format(_T("%s\\%s_MeasureData.csv"), m_strResultFolder, g_pBase->m_strLoadingDay);
   const CString strPath = MakeResultCsvPath(_T("MeasureData"));
   const CString strHeader =
      _T("Time,Glass ID,Unit_No,Table_No,Slot_No,Panel_count,")
      _T("AT_SizeAVG,BT_SizeAVG,CT_SizeAVG,DT_SizeAVG,")
      _T("AB_SizeAVG,BB_SizeAVG,CB_SizeAVG,DB_SizeAVG,")
      _T("CF_SizeX,CF_SizeY,TFT_SizeX,TFT_SizeY,")
      _T("AT_CorX,AT_CorY,AB_CorX,AB_CorY,CT_CorX,CT_CorY,CB_CorX,CB_CorY\r\n");
   AppendCsvWithHeader(strPath, strHeader, strBody);
}
void CPostProcess::SaveChipData(CString strGlassID, CString strTime)
{
   if (!m_pGlassData || !m_pRecipe) {
      return;
   }
   CheckDirectory(measure_file_path);
   auto IsChip = [&](CDefect* d)->bool {
      if (!d) return false;
      const CString& t = g_strDefectType[d->m_DefectInfo.m_DefectLoc];
      return t == _T("Chip") || t == _T("In_Chip");
   };
   CFile measure_module;
   CFileException measure_exception;
   auto PassMinSize = [&](CDefect* d)->bool {
      const int nSide = d->m_DefectInfo.m_nSideIdx;
      const int nLoc = (int)d->m_DefectInfo.m_DefectLoc;
      const int nMinX = m_pRecipe->m_SideParam[nSide].m_InspectPrm[nLoc].m_nMinSize_Filter_X_um;
      const int nMinY = m_pRecipe->m_SideParam[nSide].m_InspectPrm[nLoc].m_nMinSize_Filter_Y_um;
      return (int)std::round(d->m_dSizeX_um) > nMinX && (int)std::round(d->m_dSizeY_um) > nMinY;
   };
   measure_module.Open(measure_file_path, CFile::modeCreate | CFile::modeWrite | CFile::modeNoTruncate | CFile::shareDenyWrite | CFile::shareDenyRead, &measure_exception);
   auto NowStamp = []()->CString {
      std::time_t now = std::time(nullptr);
      std::tm tm{}; localtime_s(&tm, &now);
      CString s;
      s.Format(_T("%04d%02d%02d%02d%02d%02d"), tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
      return s;
   };
   if (measure_exception.m_cause == CFileException::none)
   {
      if (measure_module.SeekToEnd() == 0L)
      {
         CString defect_title;
         defect_title.Format(_T("Time,Glass ID,Unit_No,Table_No,Slot_No,Panel_count,AT_SizeAVG,BT_SizeAVG,CT_SizeAVG,DT_SizeAVG,AB_SizeAVG,BB_SizeAVG,CB_SizeAVG,DB_SizeAVG,CF_SizeX,CF_SizeY,TFT_SizeX,TFT_SizeY,AT_CorX,AT_CorY,AB_CorX,AB_CorY,CT_CorX,CT_CorY,CB_CorX,CB_CorY\r\n"));
         measure_module.Write(defect_title, defect_title.GetLength() * sizeof(TCHAR));
      }
      measure_module.Write(measure_data, measure_data.GetLength() * sizeof(TCHAR));
      measure_module.Close();
   }
   {
      MapDefectIt it;
      MapDefect* pMapDefect = m_pGlassData->GetMapDefect_OK();
      for (it = pMapDefect->begin(); it != pMapDefect->end(); it++)
      {
         CDefect* pDefect = static_cast<CDefect*>(it->second);
         if (pDefect == NULL)
            continue;
         if (pDefect->m_bJudge_NG == TRUE)
            continue;
         CString strDefectType = g_strDefectType[pDefect->m_DefectInfo.m_DefectLoc];
         if ((strDefectType.Compare(_T("Chip")) == 0 || strDefectType.Compare(_T("In_Chip")) == 0))
         {
            // 获取当前时间
            std::time_t now = std::time(nullptr);
            // 使用localtime_s代替localtime
            std::tm nowTm;
            localtime_s(&nowTm, &now);
            CString strDate;
            strDate.Format(_T("%04d%02d%02d%02d%02d%02d"),
               nowTm.tm_year + 1900, nowTm.tm_mon + 1, nowTm.tm_mday, nowTm.tm_hour, nowTm.tm_min, nowTm.tm_sec);
            CString strCLCS;
            m_pGlassData->DecodeDefectPose(&(pDefect->m_DefectInfo), strCLCS);
   auto GetPosXY = [&](CDefect* d, int& x, int& y) {
#if HALCON_VISION_KEY
            Point2I pos2I = BlVision_GetSoftVisionApp()->getPose(pDefect->m_DefectInfo.m_nSideIdx, pDefect->m_DefectInfo.m_ptDefectPos_pxl.x, pDefect->m_DefectInfo.m_ptDefectPos_pxl.y);
      Point2I p = BlVision_GetSoftVisionApp()->getPose(d->m_DefectInfo.m_nSideIdx, d->m_DefectInfo.m_ptDefectPos_pxl.x, d->m_DefectInfo.m_ptDefectPos_pxl.y);
      x = std::abs(p.x); y = std::abs(p.y);
#else
            CPoint pos2I = m_pGlassData->TransformToGlobal((DimensionDir)pDefect->m_DefectInfo.m_nSideIdx, pDefect->m_DefectInfo.m_ptDefectPos_pxl);
#endif // HALCON_VISION_KEY
      CPoint p = m_pGlassData->TransformToGlobal((DimensionDir)d->m_DefectInfo.m_nSideIdx, d->m_DefectInfo.m_ptDefectPos_pxl);
      x = std::abs(p.x); y = std::abs(p.y);
#endif
   };
   auto MakeRow = [&](CDefect* d, const CString& strGlassID)->CString {
      CString strClcs; m_pGlassData->DecodeDefectPose(&d->m_DefectInfo, strClcs);
      int px = 0, py = 0; GetPosXY(d, px, py);
      CString row;
      row.AppendFormat(_T("%s,%s,%s,%s,%s,%s,%s,%.1f,%.1f,%d,%d\r\n"),
         NowStamp(),
         strGlassID,
         g_pBase->m_strRecipeName,
         g_pBase->m_strSBKLine,
         PANEL_SIDE[d->m_DefectInfo.m_nSideIdx],
         strClcs,
         (d->m_DefectInfo.m_nSideIdx >= 0 && d->m_DefectInfo.m_nSideIdx < 4) ? _T("CF") : _T("TFT"),
         d->m_dSizeY_um,  // Length
         d->m_dSizeX_um,  // Depth
         px, py);
      return row;
   };
   struct Src { MapDefect* map; bool bRequireNG; bool bMinFilter; };
   Src sources[] = {
      { m_pGlassData->GetMapDefect_OK(), false, true  }, // OK:做最小尺寸过滤
      { m_pGlassData->GetMapDefect_NG(), true , false }  // NG:不做最小尺寸过滤
   };
            int nMinSize_X = m_pRecipe->m_SideParam[pDefect->m_DefectInfo.m_nSideIdx].m_InspectPrm[(int)pDefect->m_DefectInfo.m_DefectLoc].m_nMinSize_Filter_X_um;
            int nMinSize_Y = m_pRecipe->m_SideParam[pDefect->m_DefectInfo.m_nSideIdx].m_InspectPrm[(int)pDefect->m_DefectInfo.m_DefectLoc].m_nMinSize_Filter_Y_um;;
            if (static_cast<int>(round(pDefect->m_dSizeX_um)) > nMinSize_X && static_cast<int>(round(pDefect->m_dSizeY_um)) > nMinSize_Y)
            {
               chip_data.AppendFormat(_T("%s,%s,%s,%s,%s,%s,%s,%f,%f,%d,%d"),
                  strDate,
                  glass_id,
                  g_pBase->m_strRecipeName,
                  g_pBase->m_strSBKLine,
                  PANEL_SIDE[pDefect->m_DefectInfo.m_nSideIdx],
                  strCLCS,
                  pDefect->m_DefectInfo.m_nSideIdx >= 0 && pDefect->m_DefectInfo.m_nSideIdx < 4 ? _T("CF") : _T("TFT"),
                  pDefect->m_dSizeY_um,
                  pDefect->m_dSizeX_um,
                  std::abs(pos2I.x),
                  std::abs(pos2I.y));
               chip_data.Append(_T("\r\n"));
            }
         }
   CString strBody;
   for (const auto& s : sources) {
      if (!s.map) continue;
      for (auto it = s.map->begin(); it != s.map->end(); ++it) {
         CDefect* d = static_cast<CDefect*>(it->second);
         if (!d) continue;
         if ((d->m_bJudge_NG ? true : false) != s.bRequireNG) continue;
         if (!IsChip(d)) continue;
         if (s.bMinFilter && !PassMinSize(d)) continue;
         strBody += MakeRow(d, strGlassID);
      }
   }
   {
      MapDefectIt it;
      MapDefect* pMapDefect = m_pGlassData->GetMapDefect_NG();
   const CString strPath = MakeResultCsvPath(_T("ChipData"));
   const CString strHeader = _T("Date,GlassID,Model,SBK Line,Side,C-L/C-S,TFT/CF,Length,Depth,PosX,PosY\r\n");
   AppendCsvWithHeader(strPath, strHeader, strBody);
}
      for (it = pMapDefect->begin(); it != pMapDefect->end(); it++)
      {
void CPostProcess::SaveDefectListData(CString strGlassID, CString strTime)
{
   if (!m_pGlassData) {
      return;
   }
   CString strBody;
   MapDefect* pMapDefect = m_pGlassData->GetMapDefect_NG();
   if (pMapDefect) {
      for (auto it = pMapDefect->begin(); it != pMapDefect->end(); ++it) {
         CDefect* pDefect = static_cast<CDefect*>(it->second);
         if (pDefect == NULL)
         if (!pDefect) {
            continue;
         }
         if (pDefect->m_bJudge_NG == FALSE)
         if (!pDefect->m_bJudge_NG) {
            continue;
         CString strDefectType = g_strDefectType[pDefect->m_DefectInfo.m_DefectLoc];
         }
         CString strEqip, strUnit;
         CTransfer_Data* pTrans = m_pTransData;
         if (pTrans != NULL)
         {
            strEqip.Format(_T("%d"), pTrans->m_nEqpNo);
            strUnit.Format(_T("%d"), pTrans->m_nUnitNo);
         if (m_pTransData) {
            strEqip.Format(_T("%d"), m_pTransData->m_nEqpNo);
            strUnit.Format(_T("%d"), m_pTransData->m_nUnitNo);
         }
         else
         {
            strEqip.Format(_T("%d"), 0);
            strUnit.Format(_T("%d"), 0);
         else {
            strEqip = _T("0"); strUnit = _T("0");
         }
         defect_data.AppendFormat(_T("%s,%s,%s,%s,%s,%s,%f,%f,%s"),
         CString strSideName = PANEL_SIDE[pDefect->m_DefectInfo.m_nSideIdx];
         CString strDefectType = g_strDefectType[pDefect->m_DefectInfo.m_DefectLoc];
         strBody.AppendFormat(_T("%s,%s,%s,%s,%s,%s,%f,%f,%s\r\n"),
            strTime,
            glass_id,
            strGlassID,
            strEqip,
            strUnit,
            PANEL_SIDE[pDefect->m_DefectInfo.m_nSideIdx],
            strSideName,
            strDefectType,
            pDefect->m_dSizeX_um,
            pDefect->m_dSizeY_um,
            pDefect->m_strSaveImagePath);
         defect_data.Append(_T("\r\n"));
      }
   }
         if ((strDefectType.Compare(_T("Chip")) == 0 || strDefectType.Compare(_T("In_Chip")) == 0))
         {
            // 获取当前时间
            std::time_t now = std::time(nullptr);
            // 使用localtime_s代替localtime
            std::tm nowTm;
            localtime_s(&nowTm, &now);
   const CString strPath = MakeResultCsvPath(_T("DefectData"));
   const CString strHeader = _T("TIME,ID,EQP NO,UNIT NO,SIDE,LOCATION,SIZE_X,SIZE_Y,IMAGE_PATH\r\n");
   AppendCsvWithHeader(strPath, strHeader, strBody);
}
            CString strDate;
            strDate.Format(_T("%04d%02d%02d%02d%02d%02d"),
               nowTm.tm_year + 1900, nowTm.tm_mon + 1, nowTm.tm_mday, nowTm.tm_hour, nowTm.tm_min, nowTm.tm_sec);
void CPostProcess::SaveRipSideInspect(CString strGlassID, CString strTime)
{
   if (m_pHardware == nullptr || m_pGlassData == nullptr || m_pRecipe == nullptr) {
      return;
   }
            CString strCLCS;
            m_pGlassData->DecodeDefectPose(&(pDefect->m_DefectInfo), strCLCS);
            CPoint pos2I = m_pGlassData->TransformToGlobal((DimensionDir)pDefect->m_DefectInfo.m_nSideIdx, pDefect->m_DefectInfo.m_ptDefectPos_pxl);
   int nSeq = 1;
   CString strBody;
   const DimensionDir RIP_SIDES[] = { DIMENSION_A_RIP, DIMENSION_B_RIP, DIMENSION_C_RIP, DIMENSION_D_RIP };
            chip_data.AppendFormat(_T("%s,%s,%s,%s,%s,%s,%s,%f,%f,%d,%d"),
               strDate,
               glass_id,
               g_pBase->m_strRecipeName,
               g_pBase->m_strSBKLine,
               PANEL_SIDE[pDefect->m_DefectInfo.m_nSideIdx],
               strCLCS,
               pDefect->m_DefectInfo.m_nSideIdx >= 0 && pDefect->m_DefectInfo.m_nSideIdx < 4 ? _T("CF") : _T("TFT"),
               pDefect->m_dSizeY_um,
               pDefect->m_dSizeX_um,
               std::abs(pos2I.y),
               std::abs(pos2I.x));
            chip_data.Append(_T("\r\n"));
   for (DimensionDir eDim : RIP_SIDES) {
      int nSide = (int)eDim;
      CSide_Data* pSideData = m_pGlassData->GetSideData(eDim);
      CSIDE_PARM* pSideParm = &m_pRecipe->m_SideParam[eDim];
      if (!pSideData || !pSideParm) {
         continue;
      }
      CRIP_THICKNESS_PARM& rip = pSideParm->m_RipThk;
      if (rip.m_bUseInspect != TRUE) {
         continue;
      }
      int nMeasureCount = pSideParm->m_nSideDimensionCount;
      for (int i = 0; i < nMeasureCount; ++i) {
         if (i == MAX_SIDE_DIMENSION_MEASURE_COUNT || i == MAX_RIP_SAMPLE_COUNT) {
            break;
         }
         if (pSideParm->m_bSideDimension_Use[i] != TRUE) {
            continue;
         }
         bool bValid = pSideData->m_nSideRip_Left_Status[i] != 0 || pSideData->m_nSideRip_Right_Status[i] != 0 || pSideData->m_nSideRip_Glass_Status[i] != 0;
         if (!bValid) {
            continue;
         }
         strBody.AppendFormat(_T("%d,%s,%s,%s,%.1f,%.1f,%.1f\r\n"),
            nSeq++, strTime, strGlassID, g_SideName[nSide],
            pSideData->m_dSideRip_Left_um[i],
            pSideData->m_dSideRip_Right_um[i],
            pSideData->m_dSideRip_Glass_um[i]);
      }
   }
   CString Chip_file_path;
   if (m_pHardware->m_bSaveResultByHour) {
      // 按小时保存结果
      Chip_file_path.Format(_T("%s\\%s_%02d_ChipData.csv"), m_strResultFolder, g_pBase->m_strLoadingDay, tGlassLoading.GetHour());
   if (strBody.IsEmpty()) {
      return;
   }
   const CString strPath = MakeResultCsvPath(_T("RipSideInspect"));
   const CString strHeader = _T("Seq,Time,ID,Side,Left Cut Depth (um),Right Cut Depth (um),Total Length (um)\r\n");
   AppendCsvWithHeader(strPath, strHeader, strBody);
}
void CPostProcess::SaveDefectData()
{
   CString strGlassID;
   strGlassID.Format(_T("%s"), g_pBase->m_strHPanelID);
   if (strGlassID.IsEmpty()) {
      strGlassID.Format(_T("MANUAL_ID"));
   }
   CString strTime;
   strTime.Format(_T("%s"), g_pBase->m_strLoadingTime);
   SaveMeasureData(strGlassID, strTime);
   SaveChipData(strGlassID, strTime);
   SaveDefectListData(strGlassID, strTime);
   SaveRipSideInspect(strGlassID, strTime);
}
CString CPostProcess::MakeResultCsvPath(LPCTSTR stem) const
{
   CString strPath;
   if (m_pHardware && m_pHardware->m_bSaveResultByHour) {
      CTime tLoad = m_pGlassData ? m_pGlassData->GetLoadingTime() : CTime::GetCurrentTime();
      strPath.Format(_T("%s\\%s_%02d_%s.csv"), m_strResultFolder, g_pBase->m_strLoadingDay, tLoad.GetHour(), stem);
   }
   else {
      // 不按小时保存结果
      Chip_file_path.Format(_T("%s\\%s_ChipData.csv"), m_strResultFolder, g_pBase->m_strLoadingDay);
      strPath.Format(_T("%s\\%s_%s.csv"), m_strResultFolder, g_pBase->m_strLoadingDay, stem);
   }
   CheckDirectory(Chip_file_path);
   return strPath;
}
   CFile chip_module;
   CFileException chip_exception;
   chip_module.Open(Chip_file_path, CFile::modeCreate | CFile::modeWrite | CFile::modeNoTruncate | CFile::shareDenyWrite | CFile::shareDenyRead, &chip_exception);
   if (chip_exception.m_cause == CFileException::none)
   {
      if (chip_module.SeekToEnd() == 0L)
      {
         CString defect_title;
         defect_title.Format(_T("Date,GlassID,Model,SBK Line,Side,C-L/C-S,TFT/CF,Length,Depth,PosX,PosY\r\n"));
         chip_module.Write(defect_title, defect_title.GetLength() * sizeof(TCHAR));
      }
      chip_module.Write(chip_data, chip_data.GetLength() * sizeof(TCHAR));
      chip_module.Close();
bool CPostProcess::AppendCsvWithHeader(const CString& strFilePath, const CString& strHeader, const CString& strBody)
{
   if (strBody.IsEmpty()) {
      return false;
   }
   CString Defect_file_path;
   if (m_pHardware->m_bSaveResultByHour) {
      // 按小时保存结果
      Defect_file_path.Format(_T("%s\\%s_%02d_DefectData.csv"), m_strResultFolder, g_pBase->m_strLoadingDay, tGlassLoading.GetHour());
   }
   else {
      // 不按小时保存结果
      Defect_file_path.Format(_T("%s\\%s_DefectData.csv"), m_strResultFolder, g_pBase->m_strLoadingDay);
   CheckDirectory(strFilePath);
   CFile f; CFileException ex;
   if (!f.Open(strFilePath, CFile::modeCreate | CFile::modeWrite | CFile::modeNoTruncate | CFile::shareDenyWrite | CFile::shareDenyRead, &ex)) {
      return false;
   }
   CheckDirectory(Defect_file_path);
   CFile defect_module;
   CFileException defect_exception;
   defect_module.Open(Defect_file_path, CFile::modeCreate | CFile::modeWrite | CFile::modeNoTruncate | CFile::shareDenyWrite | CFile::shareDenyRead, &defect_exception);
   if (defect_exception.m_cause == CFileException::none)
   {
      if (defect_module.SeekToEnd() == 0L)
      {
         CString defect_title;
         defect_title.Format(_T("TIME,ID,EQP NO,UNIT NO,SIDE,LOCATION,SIZE_X,SIZE_Y,IMAGE_PATH\r\n"));
         defect_module.Write(defect_title, defect_title.GetLength()*sizeof(TCHAR));
      }
      defect_module.Write(defect_data, defect_data.GetLength()*sizeof(TCHAR));
      defect_module.Close();
   if (f.SeekToEnd() == 0L) {
      f.Write(strHeader, strHeader.GetLength() * sizeof(TCHAR));
   }
   f.Write(strBody, strBody.GetLength() * sizeof(TCHAR));
   f.Close();
   return true;
}
void CPostProcess::JudgementData()
@@ -514,84 +517,126 @@
BOOL CPostProcess::SaveDefectImage(LPBYTE pImage,CSize szImage,CRect rectDefect,CString strFile,DimensionDir emDir)
{
   FIBITMAP               *bitmap = NULL;
   BYTE                  *pBitBuffer;
   if (pImage == NULL || szImage.cx <= 0 || szImage.cy <= 0) {
      g_pLog->DisplayMessage(_T("Invalid image data or size"));
      return FALSE;
   }
   bitmap = FreeImage_Allocate(szImage.cx, szImage.cy,8);
   Lock();
   FIBITMAP* bitmap = FreeImage_Allocate(szImage.cx, szImage.cy, 8);
   if (bitmap == NULL) {
      g_pLog->DisplayMessage(_T("FreeImage_Allocate failed"));
      Unlock();
      return FALSE;
   }
   pBitBuffer = FreeImage_GetBits(bitmap);
   if(pBitBuffer == NULL)
   {
      FreeImage_Unload(bitmap);
   BYTE* pBitBuffer = FreeImage_GetBits(bitmap);
   if(pBitBuffer == NULL) {
      FreeImage_Unload(bitmap);
      Unlock();
      return FALSE;
   }         
   CopyMemory(pBitBuffer,pImage,szImage.cx*szImage.cy);
   CopyMemory(pBitBuffer, pImage, szImage.cx * szImage.cy);
   FIBITMAP *pBit24 = FreeImage_ConvertTo24Bits(bitmap);
   if(pBit24 == NULL)
   if (pBit24 == NULL) {
      Unlock();
      return FALSE;
   }
   char cFilePath[255];
#ifdef _UNICODE
   int      nSize = WideCharToMultiByte(CP_ACP, 0, strFile.GetBuffer(), -1, NULL, 0, NULL,NULL);
   int   nSize = WideCharToMultiByte(CP_ACP, 0, strFile.GetBuffer(), -1, NULL, 0, NULL,NULL);
   WideCharToMultiByte(CP_ACP, 0, strFile.GetBuffer(), -1, cFilePath, nSize, NULL, NULL); 
#else            
   sprintf_s(cFilePath,sizeof(char)*255,_T("%s"),(LPSTR)(LPCTSTR)strFile);   
#endif   
   FreeImage_FlipVertical(pBit24);
   FreeImage_Save(FIF_JPEG, pBit24, cFilePath,JPEG_RATE);   
   FreeImage_Unload(bitmap);
   FreeImage_Unload(pBit24);
   Unlock();
   return TRUE;
}
BOOL CPostProcess::SaveDefectImage2(LPBYTE pImage,CSize szImage,CRect rectDefect,CString strFile)
BOOL CPostProcess::SaveDefectImageModern(LPBYTE pImage,CSize szImage,CRect rectDefect,CString strFile)
{
   IplImage *pImageTmp = cvCreateImage(cvSize(szImage.cx, szImage.cy), 8,1);
   if (!pImage || szImage.cx <= 0 || szImage.cy <= 0) {
      return FALSE;
   }
#if 0
   IplImage* pImageTmp = cvCreateImage(cvSize(szImage.cx, szImage.cy), 8, 1);
   cvZero(pImageTmp);
   // add point to the image
   for (int i = 0; i<szImage.cy; i++)
   {
      for (int j = 0; j<szImage.cx; j++)
      {
         pImageTmp->imageData[i*pImageTmp->widthStep+j] = pImage[i*szImage.cx+j];
   for (int i = 0; i < szImage.cy; i++) {
      for (int j = 0; j < szImage.cx; j++) {
         pImageTmp->imageData[i * pImageTmp->widthStep + j] = pImage[i * szImage.cx + j];
      }
   }
   IplImage *pColorImg = cvCreateImage(cvSize(szImage.cx, szImage.cy), 8, 3);
   IplImage* pColorImg = cvCreateImage(cvSize(szImage.cx, szImage.cy), 8, 3);
   cvZero(pColorImg);
   cvCvtColor(pImageTmp, pColorImg, CV_GRAY2BGR);
   cvRectangle(pColorImg, CvPoint(rectDefect.left, rectDefect.top), CvPoint(rectDefect.left + rectDefect.Width(), rectDefect.top + rectDefect.Height()), cvScalar(0, 0, 255), 1);
   cvRectangle(pColorImg,CvPoint(rectDefect.left,rectDefect.top), CvPoint(rectDefect.left+rectDefect.Width(),rectDefect.top+rectDefect.Height()), cvScalar(0,0,255), 1);
USES_CONVERSION;
   USES_CONVERSION;
   char str_filename[1024];
   sprintf_s(str_filename, "%s", W2A(strFile));
   cvSaveImage(str_filename, pColorImg);
   cvReleaseImage(&pColorImg);
   cvReleaseImage(&pImageTmp);
#else
   Lock();
   cv::Mat grayImg(szImage.cy, szImage.cx, CV_8UC1, pImage);
   cv::Mat colorImg;
   cv::cvtColor(grayImg, colorImg, cv::COLOR_GRAY2BGR);
   cv::rectangle(
      colorImg,
      cv::Rect(rectDefect.left, rectDefect.top, rectDefect.Width(), rectDefect.Height()),
      cv::Scalar(0, 0, 255),
      1
   );
   USES_CONVERSION;
   std::string strFilename = W2A(strFile);
   if (!cv::imwrite(strFilename, colorImg)) {
      Unlock();
      g_pLog->DisplayMessage(_T("Failed to save image to %s"), strFile);
      return FALSE;
   }
   Unlock();
#endif // 0
   return TRUE;
}
BOOL CPostProcess::SaveDefectImage_with_Title(CDefect* pDefect, CSize szImage,CRect rectDefect,CString strFile, CvScalar color)
{
   Lock();
   if (pDefect == NULL || pDefect->m_Image == NULL) {
      g_pLog->DisplayMessage(_T("Invalid defect data or image"));
      return FALSE;
   }
   // 标题文本
   if (szImage.cx <= 0 || szImage.cy <= 0) {
      g_pLog->DisplayMessage(_T("Invalid image size: %d x %d"), szImage.cx, szImage.cy);
      return FALSE;
   }
   BOOL bSuccess = TRUE;
   Lock();
   // 标题文本
   CString strTitle;
   int nSideIdx = (0 <= pDefect->m_DefectInfo.m_nSideIdx && pDefect->m_DefectInfo.m_nSideIdx < MAX_SIDE_COUNT) ? pDefect->m_DefectInfo.m_nSideIdx : MAX_SIDE_COUNT;
   int nCategoryIdx = (0 <= pDefect->m_DefectInfo.m_DefectLoc && pDefect->m_DefectInfo.m_DefectLoc < DefectLoc_None) ? pDefect->m_DefectInfo.m_DefectLoc : DefectLoc_Unknown;
@@ -605,45 +650,32 @@
   }
   Unlock();
   // 成功标志
   BOOL bSuccess = TRUE;
   try {
      // 将 CDefect 的 m_Image 缓冲区复制到 cv::Mat
      Lock();
      cv::Mat imgTmp(szImage.cy, szImage.cx, CV_8UC1, pDefect->m_Image);
      // 创建彩色图像
      cv::Mat colorImg(szImage.cy, szImage.cx, CV_8UC3);
      cv::cvtColor(imgTmp, colorImg, cv::COLOR_GRAY2BGR);
      // 在图像上画矩形
      cv::rectangle(colorImg, cv::Point(rectDefect.left, rectDefect.top),
         cv::Point(rectDefect.right, rectDefect.bottom), color, 1);
      cv::rectangle(colorImg, cv::Point(rectDefect.left, rectDefect.top), cv::Point(rectDefect.right, rectDefect.bottom), color, 1);
      cv::rectangle(colorImg, cv::Point(0, szImage.cy - 40), cv::Point(szImage.cx, szImage.cy), cv::Scalar(0, 0, 0), cv::FILLED);
      // 添加标题
      cv::rectangle(colorImg, cv::Point(0, szImage.cy - 40),
         cv::Point(szImage.cx, szImage.cy), cv::Scalar(0, 0, 0), cv::FILLED);
      // 设置字体
      int fontFace = cv::FONT_HERSHEY_TRIPLEX;
      double fontScale = 0.7;
      int thickness = 1;
      // 将标题文本放到图像上
      CT2CA pszConvertedAnsiTitle(strTitle);
      cv::String strCVTitle(pszConvertedAnsiTitle);
      cv::putText(colorImg, strCVTitle, cv::Point(10, szImage.cy - 10),
         fontFace, fontScale, CV_RGB(255, 255, 255), thickness);
      cv::putText(colorImg, strCVTitle, cv::Point(10, szImage.cy - 10), fontFace, fontScale, CV_RGB(255, 255, 255), thickness);
      // 将图像保存到文件
      CT2CA pszConvertedAnsiFile(strFile);
      cv::String strStdFile(pszConvertedAnsiFile);
      cv::imwrite(strStdFile, colorImg);
   //   cv::imwrite("D:\\Inspection\\Data\\IMG_DEFECT\\20250409\\Manual\\Manual_A_TOP_Chip_0.bmp", colorImg);
      Unlock();
   }
   catch (cv::Exception& e) {
      // OpenCV异常处理
      bSuccess = FALSE;
      Unlock();
      g_pLog->DisplayMessage(_T("OpenCV Exception: %s"), e.what());
   }
   return bSuccess;
@@ -874,7 +906,7 @@
   // 3. Corner
   
   // A 惑何 官蹿
   // A 惑何 官蹿
   vecStrTitle.push_back(_T("CORNER_1_X"));
   strTemp.Format(_T("%d"), m_pGlassData->GetSideData(DIMENSION_A)->m_nBottomCornerWidth);
   vecStrResultData.push_back(strTemp);
@@ -882,7 +914,7 @@
   strTemp.Format(_T("%d"), m_pGlassData->GetSideData(DIMENSION_A)->m_nBottomCornerHeight);
   vecStrResultData.push_back(strTemp);
   // C 惑何 官蹿
   // C 惑何 官蹿
   vecStrTitle.push_back(_T("CORNER_2_X"));
   strTemp.Format(_T("%d"), m_pGlassData->GetSideData(DIMENSION_C)->m_nBottomCornerWidth);
   vecStrResultData.push_back(strTemp);
@@ -890,7 +922,7 @@
   strTemp.Format(_T("%d"), m_pGlassData->GetSideData(DIMENSION_C)->m_nBottomCornerHeight);
   vecStrResultData.push_back(strTemp);
   // C 惑何 啪
   // C 惑何 啪
   vecStrTitle.push_back(_T("CORNER_3_X"));
   strTemp.Format(_T("%d"), m_pGlassData->GetSideData(DIMENSION_C)->m_nTopCornerWidth);
   vecStrResultData.push_back(strTemp);
@@ -898,7 +930,7 @@
   strTemp.Format(_T("%d"), m_pGlassData->GetSideData(DIMENSION_C)->m_nTopCornerHeight);
   vecStrResultData.push_back(strTemp);
   // A 惑何 啪
   // A 惑何 啪
   vecStrTitle.push_back(_T("CORNER_4_X"));
   strTemp.Format(_T("%d"), m_pGlassData->GetSideData(DIMENSION_A)->m_nTopCornerWidth);
   vecStrResultData.push_back(strTemp);
@@ -957,7 +989,7 @@
   CSide_Data* pSideData_UP = NULL;
   CSide_Data* pSideData_DN = NULL;
   // Notch乐绰 搁 茫扁
   // Notch乐绰 搁 茫扁
   for(int nSideIdx=0; nSideIdx<MAX_PANEL_SIDE; nSideIdx++)
   {
      pSideData_UP = m_pGlassData->GetSideData(arryWriteOrder_UP[nSideIdx]);
@@ -969,7 +1001,7 @@
   for(int nNotchIdx=0; nNotchIdx<MAX_SIDE_NOTCH_COUNT; nNotchIdx++)
   {
      // 4-2. Dimension, 酒阀搁栏肺 螟沥
      // 4-2. Dimension, 酒阀搁栏肺 螟沥
      for(int nMeasureIdx = 0; nMeasureIdx < MAX_SIDE_NOTCH_MEASURE_COUNT; nMeasureIdx++)
      {
         strTemp.Format(_T("NOTCH_%d_DIM_%d"), nNotchIdx+1, nMeasureIdx+1);
@@ -1006,7 +1038,7 @@
   // Save Path
   CString strFilePath;
   if (m_pHardware->m_bSaveResultByHour) {
      // 按小时保存,绑定玻璃 Loading Time
      // 按小时保存,绑定玻璃 Loading Time
      strFilePath.Format(_T("D:\\Data\\%s\\%s\\%d\\%02d\\%02d\\%s_%s_%02d.csv"),
         m_pHardware->GetMachineName(),
         m_pHardware->GetLineID(),
@@ -1018,7 +1050,7 @@
         tLoadingTime.GetHour());
   }
   else {
      // 按天保存,绑定玻璃 Loading Time
      // 按天保存,绑定玻璃 Loading Time
      strFilePath.Format(_T("D:\\Data\\%s\\%s\\%d\\%02d\\%02d\\%s_%s.csv"),
         m_pHardware->GetMachineName(),
         m_pHardware->GetLineID(),
@@ -1185,6 +1217,8 @@
      bJudgeUse      = (pSideParam->m_UserDefectPrm[pDefect->m_nUserDefectAreaIdx].m_nJudge_Size_Min_OR_AND == 0) ? FALSE : TRUE;
      break;
   case DefectLoc_Notch_Crack:
   case DefectLoc_Notch_NoGrind:
      nJudgeW_um = pSideParam->m_NotchPrm[pDefect->m_nNotchIdx].m_nNotch_Inspect_Defect_Judge_X_um;
      nJudgeH_um = pSideParam->m_NotchPrm[pDefect->m_nNotchIdx].m_nNotch_Inspect_Defect_Judge_Y_um;
      bAnd = (pSideParam->m_NotchPrm[pDefect->m_nNotchIdx].m_nNotch_Inspect_Defect_Judge_And == 2) ? TRUE : FALSE;
@@ -1748,7 +1782,7 @@
   
   /*
   pDefect->m_nUMOriginX = (int)((double) (pDefect->m_DefectInfo.m_ptDefectPos_pxl.y - nStartLine) * dScanRes);
   pDefect->m_nUMOriginY = (int)((double) (pDefect->m_DefectInfo.m_ptDefectPos_pxl.x * dConvRes));      // 荐沥 鞘夸..
   pDefect->m_nUMOriginY = (int)((double) (pDefect->m_DefectInfo.m_ptDefectPos_pxl.x * dConvRes));      // 荐沥 鞘夸..
   */
   CSIDE_PARM* pSideParam = &pRecipe->m_SideParam[pDefect->m_DefectInfo.m_nSideIdx];
@@ -1991,13 +2025,13 @@
   TCHAR szTemp[MAX_PATH];
   wcscpy_s(szTemp, MAX_PATH, strFolder);
   szTemp[strFolder.GetLength() + 1] = NULL; // NULL巩磊啊 滴俺 甸绢啊具 茄促.
   szTemp[strFolder.GetLength() + 1] = NULL; // NULL巩磊啊 滴俺 甸绢啊具 茄促.
   FileOp.hwnd = NULL;
   FileOp.wFunc = FO_DELETE;
   FileOp.pFrom = NULL;
   FileOp.pTo = NULL;
   FileOp.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI; // 犬牢皋矫瘤啊 救哆档废 汲沥
   FileOp.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI; // 犬牢皋矫瘤啊 救哆档废 汲沥
   FileOp.fAnyOperationsAborted = false;
   FileOp.hNameMappings = NULL;
   FileOp.lpszProgressTitle = NULL;