直接貼代碼了。在寫的時候借鑒了網上的一些代碼,可是忘記保留鏈接了,所以此處向可能的貢獻者致謝。
- #include <cv.h>
- #include <highgui.h>
- #include <vector>
- #include <algorithm>
- using namespace std;
-
- #pragma comment( lib, "cv.lib" )
- #pragma comment( lib, "cxcore.lib" )
- #pragma comment( lib, "highgui.lib" )
-
- int main()
- {
- IplImage *src = cvLoadImage("lena.jpg", CV_LOAD_IMAGE_COLOR);
- cvNamedWindow("原始圖像");
- cvShowImage("原始圖像", src);
-
- IplImage* dst=cvCreateImage(cvSize(src->width,src->height),IPL_DEPTH_8U,1);
- cvCvtColor(src,dst,CV_BGR2GRAY);
- cvNamedWindow("灰度圖像");
- cvShowImage("灰度圖像", src);
-
- cvThreshold(dst, dst, 0.0, 255.0, CV_THRESH_BINARY | CV_THRESH_OTSU);//OTSU二值化
- IplConvKernel *element = cvCreateStructuringElementEx(5, 5, 0, 0, CV_SHAPE_ELLIPSE);
- cvMorphologyEx(dst, dst, NULL, element, CV_MOP_OPEN);//開運算,去除比結構元素小的點
- cvReleaseStructuringElement(&element);
- cvNamedWindow("二值圖像");
- cvShowImage("二值圖像", dst);
-
- int w,h;
- CvSize sz = cvGetSize(dst);
-
- int color = 254;//不對0計數,不可能為255,所以254
- for (w=0; w<sz.width; w++)
- {
- for (h=0; h<sz.height; h++)
- {
- if (color > 0)
- {
- if (CV_IMAGE_ELEM(dst, unsigned char, h, w) == 255)
- {
- //把連通域標記上顏色
- cvFloodFill(dst, cvPoint(w,h), CV_RGB( color,color,color));
- color--;
- }
- }
- }
- }
- cvNamedWindow("標記顏色後的圖像");
- cvShowImage("標記顏色後的圖像", dst);
-
- int colorsum[255] = {0};
- for (w=0; w<sz.width; w++)
- {
- for (h=0; h<sz.height; h++)
- {
- if (CV_IMAGE_ELEM(dst, unsigned char, h, w) > 0)
- {
- colorsum[CV_IMAGE_ELEM(dst, unsigned char, h, w)]++;//統計每種顏色的數量
- }
- }
- }
- vector<int> v1(colorsum, colorsum+255);//用數組初始化vector
- //求出最多數量的染色,注意max_element的使用方法
- int maxcolorsum = max_element(v1.begin(), v1.end()) - v1.begin();
- printf("%d\n",maxcolorsum);
-
- for (w=0; w<sz.width; w++)
- {
- for (h=0; h<sz.height; h++)
- {
- if (CV_IMAGE_ELEM(dst, unsigned char, h, w) == maxcolorsum)
- {
- CV_IMAGE_ELEM(dst, unsigned char, h, w) = 255;
- }
- else
- {
- CV_IMAGE_ELEM(dst, unsigned char, h, w) = 0;
- }
- }
- }
- cvNamedWindow("最大連通域圖");
- cvShowImage("最大連通域圖", dst);
-
- cvWaitKey(0);
- cvDestroyAllWindows();
- cvReleaseImage(&src);
- cvReleaseImage(&dst);
-
- return 0;
- }
測試圖像采用標准的Lena圖像,測試結果為: