首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

OpenCV 實戰:番茄葉片面積計算完整流程(上)— 圖片載入、縮放顯示、MFC 界面搭建

     編輯:關於C語言

專案背景

計算番茄葉片面積:灰度變換 → 輪廓提取 → 像素計數。手寫圖像處理類涉及調色板、DIB 操作極其繁瑣。引入 OpenCV 跨平台視覺庫,算法即調用。

環境配置

  • 安裝 OpenCV(含 cv.lib cvaux.lib highgui.lib cvcam.lib cxcore.lib)
  • VC6.0:Tools→Options→Directories 添加 Include/Lib/Source 路徑
  • Project→Settings→Link 添加上述 .lib

MFC 界面設計

  • Picture Control (IDC_ShowImg) — 圖片顯示
  • Button「載入圖片」— 觸發載入
  • Button「計算面積」— 觸發算法
  • Combo Box — 選擇過濾閾值 (1000~6000)
  • Edit Control ×3 — 顯示最大/次大/參考面積

核心工具函數

1. 圖片縮放至 256×256 區域居中

void ResizeImage(IplImage* img) {
    int w = img->width, h = img->height;
    int max = (w > h) ? w : h;
    float scale = (float)max / 256.0f;
    int nw = cvRound(w / scale), nh = cvRound(h / scale);
    int tlx = (nw > nh) ? 0 : (256 - nw) / 2;
    int tly = (nw > nh) ? (256 - nh) / 2 : 0;
    cvSetImageROI(TheImage, cvRect(tlx, tly, nw, nh));
    cvResize(img, TheImage);
    cvResetImageROI(TheImage);
}

2. 將 IplImage 繪製到 Picture Control

void ShowImage(IplImage* img, UINT ID) {
    CDC* pDC = GetDlgItem(ID)->GetDC();
    HDC hDC = pDC->GetSafeHdc();
    CRect rect; GetDlgItem(ID)->GetClientRect(&rect);
    int tx = (rect.Width() - img->width) / 2;
    int ty = (rect.Height() - img->height) / 2;
    SetRect(rect, tx, ty, tx + img->width, ty + img->height);
    CvvImage cimg; cimg.CopyOf(img);
    cimg.DrawToHDC(hDC, &rect);
    ReleaseDC(pDC);
}

載入按鈕響應

void OnButtonLoad() {
    CFileDialog dlg(TRUE, _T("bmp"), NULL, OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY,
        _T("Image Files (*.bmp;*.jpg)|*.bmp;*.jpg|All Files|*.*||"), NULL);
    dlg.m_ofn.lpstrTitle = _T("Open Image");
    if (dlg.DoModal() != IDOK) return;
    
    CString path = dlg.GetPathName();
    IplImage* ipl = cvLoadImage(path, 1);  // 彩色
    IplImage* gray = cvLoadImage(path, 0); // 灰度
    if (!ipl) return;
    
    cvZero(TheImage);  // 清空上一幀
    ResizeImage(ipl);
    ShowImage(TheImage, IDC_ShowImg);
    // 後續算法處理見下篇
}

下篇預告

大津法自適應閾值 → 二值化 → 輪廓檢測 → 面積過濾填充 → 像素計算 → 硬幣參考物標定 → 實際面積換算。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved