資源簡介
利用opencv的cvKMeans2進行聚類分析,并給出測試代碼,希望對大家有所幫助
代碼片段和文件信息
//?Knowledge.cpp?:?Defines?the?entry?point?for?the?console?application.
//
#include?“stdafx.h“
BOOL?ImageSegmentByKMeans2(const?IplImage*?pImg?IplImage*?pResult?BOOL?colorFlag?=?FALSE?int?sortFlag?=?0);
BOOL?GrayImageSegmentByKMeans2(const?IplImage*?pImg?IplImage*?pResult?int?sortFlag?=?0);
BOOL?ColorImageSegmentByKMeans2(const?IplImage*?pImg?IplImage*?pResult?int?sortFlag?=?0);
#define?nClusters?3
int?_tmain(int?argc?char**?argv)
{
string?savePath?=?“D:\\“;
string?path?=?“D:\\igandvd\\CharCh\\CharForTrain\\pos\\yellow\\“;
string?imgName?=?“D:\\igandvd\\CharCh\\CharForTrain\\pos\\yellow\\*.png“;
IplImage*?pImg?=?NULL;
//?驗證腐蝕和膨脹
_finddata_t?imgInfo;
memset(&imgInfo?0x0?sizeof(imgInfo));
//?尋找第一個文件
long?handle?=?_findfirst(imgName.c_str()?&imgInfo);
if?(-1L?==?handle)
{
cerr?<“ERROR:?Failed?to?Find?the?First?Image!“?< system(“pause“);
return?0;
}
IplImage*?img?=?NULL?*pGray?=?NULL?*pBin?=?NULL;
do
{
if?((img?=?cvLoadImage((path?+?imgInfo.name).c_str()))?==?NULL)
{
cerr?<“ERROR:?Failed?to?Load?Image?“?< system(“pause“);
return?0;
}
cvNamedWindow(?“原始圖像“?1?);?//創建窗口
cvShowImage(?“原始圖像“?img??);?//顯示圖像
//?cvWaitKey(0);?//等待按鍵
pBin?=?cvCreateImage(cvSize(img->width?img->height)?8?1);
cvSetZero(pBin);
ImageSegmentByKMeans2(img?pBin?FALSE?0);
cvNamedWindow(?“聚類圖像“?1?);?//創建窗口
cvShowImage(?“聚類圖像“?pBin);?//顯示圖像
cvWaitKey(0);?//等待按鍵
cvReleaseImage(&pBin);
cvDestroyAllWindows();
}while?(0?==?_findnext(handle?&imgInfo));
system(“pause“);
return?0;
}
//?int?nClusters?類別數目?BOOL?colorFlag?處理灰度圖像還是彩色圖像,默認為FALSE,灰度圖像聚類分析
//?int?sortFlag?0代表不進行排序?1代表按照升序進行排序?2?代表按照降序進行排序,默認為0不進行排序
BOOL?ImageSegmentByKMeans2(const?IplImage*?pImg?IplImage*?pResult?BOOL?colorFlag?int?sortFlag)
{
//?檢查輸入參數
assert(pImg?!=?NULL?&&?pResult?!=?NULL);
assert(pResult->nChannels?==?1);
if?(colorFlag)
{
assert(pImg->nChannels?==?3);
}
//?復制工作圖像如果存在ROI,則只對ROI進行處理
IplImage*?pClone?=?NULL;
if?(pImg->roi)
{
CvRect?rect?=?cvRect(pImg->roi->xOffset?pImg->roi->yOffset?pImg->roi->width?pImg->roi->height);
pClone?=?cvCreateImage(cvSize(rect.width?rect.height)?pImg->depth?pImg->nChannels);
cvCopyImage(pImg?pClone);
}
else
{
pClone?=?cvCloneImage(pImg);
}
//?聚類分析
if?(!colorFlag)?//?灰度圖像
{
IplImage*?pWork?=?NULL;
if?(pClone->nChannels?==?3)?//?如果是彩色圖像需要進行顏色轉換
{
pWork?=?cvCreateImage(cvSize(pClone->width?pClone->height)?IPL_DEPTH_8U?1);
cvCvtColor(pClone?pWork?CV_BGR2GRAY);
}
else
{
pWork?=?cvCloneImage(pClone);
}
cvReleaseImage(&pClone);
BOOL?grayResult?=?GrayImageSegmentByKMeans2(pWork?pResult?sortFlag);
cvReleaseImage(&pWork);
return?grayResult;
}
else?//?彩色圖像
{
IplImage*?pWork?=?cvCloneImage(pClone);
cvReleaseImage(&pClone);
BOOL?colorResult?=?ColorImageSegmentByKMeans2(pWork?pResult?sor
- 上一篇:詞法分析器c語言實現
- 下一篇:qt c++ 開發的俄羅斯方塊
評論
共有 條評論