菜鸟一枚,
这是我的第三个博客,
刚刚入门opencv,
想将自己的学习过程分享给大家!!!
#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp> //Opencv highgui 模块
#include <opencv2/imgproc/imgproc.hpp> //Opencv 图像处理头文件
using namespace cv;
using namespace std;
int main()
{
Mat src = imread("D:/opencv/opencvSRC/dog.jpg");
if (src.empty())
{
printf("could not load image...\n");
return -1;
}
namedWindow("input image", CV_WINDOW_AUTOSIZE);
imshow("input image", src);
int width = src.cols;
int height = src.rows;
int dims = src.channels();
Scalar colorTab[] =
{
Scalar(0,0,255),
Scalar(0,255,0),
Scalar(0,255,255),
Scalar(255,0,255),
};
//初始化定义
int sampleCount = width*height;
int clusterCount = 3;
Mat point(sampleCount, dims, CV_32F, Scalar(10));
Mat labels;
Mat centers(clusterCount, 1, point.type());
//RGB数据转为样本数据
int index = 0;
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
index = row*width + col;
Vec3b bgr = src.at<Vec3b>(row, col);
point.at<float>(index, 0) = static_cast<int>(bgr[0]);
point.at<float>(index, 1) = static_cast<int>(bgr[1]);
point.at<float>(index, 2) = static_cast<int>(bgr[2]);
}
}
//运行K-Means
TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1);
kmeans(point, clusterCount, labels, criteria, 3, KMEANS_PP_CENTERS, centers);
//显示图像分割结果(计算后数据转为RGB)
Mat result = Mat::zeros(src.size(), src.type());
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
index = row*width + col;
int label = labels.at<int>(index, 0);
result.at<Vec3b>(row, col)[0] = colorTab[label][0];
result.at<Vec3b>(row, col)[1] = colorTab[label][1];
result.at<Vec3b>(row, col)[2] = colorTab[label][2];
}
}
imshow("KMeans Dome", result);
waitKey(0);
return 0;
}
程序运行结果:
谢谢同学们的阅读!!!