#include <opencv2/opencv.hpp> 

#include <iostream> 

 using namespace cv; 

using namespace std; 

 int main() 

Mat srcImage = imread("C:/Users/11815/Desktop/ wechat image_20200912152639.jpg ");

if (! srcImage.data)

   { 

printf("could not load image... \n");

       return -1; 

 } 

 VideoCapture capture; 

namedWindow("mouse_pictures.png", 0); 

imshow("mouse_pictures.png", srcImage); 

// Select a random color from the cluster

 Scalar colorTab[] = { 

Scalar (0,0,255),

Scalar (0255, 0),

          Scalar(255,0,0), 

Scalar (0255255).

          Scalar(255,0,255) }; 

int width = srcImage.cols; // Width of image

int height = srcImage.rows; // Height of the image

int channels = srcImage.channels(); // The number of channels in the image

// Initialize some definitions

int sampleCount = width * height; // All pixels

int clusterCount = 3; / / class number

Mat points(sampleCount, channels, CV_32F, Scalar(10)); //points are used to store all data

Mat labels; // Label after clustering

Mat center(clusterCount, 1, points.type()); // Cluster the center of the category

// Transfer the RGB pixels of the image to the sample data

 int index; 

 for (int i = 0; i < srcImage.rows; i++) { 

     for (int j = 0; j < srcImage.cols; j++) { 

       index = i * width + j; 

       Vec3b bgr = srcImage.at<Vec3b>(i, j); 

// Assign data for each channel in the image to the value of points

       points.at<float>(index, 0) = static_cast<int>(bgr[0]); 

       points.at<float>(index, 1) = static_cast<int>(bgr[1]); 

       points.at<float>(index, 2) = static_cast<int>(bgr[2]); 

         } 

              } 

// Run k-means algorithm

//MAX_ITER can also be called COUNT maximum number of iterations, EPS maximum precision,10 represents the maximum number of iterations, TermCriteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1); kmeans(points, clusterCount, labels, criteria, 3, KMEANS_PP_CENTERS, center);

// Display image segmentation results

Mat result = Mat::zeros(srcImage.size(), srcImage.type()); // Create a result graph

 for (int i = 0; i < srcImage.rows; i++) 

 { 

      for (int j = 0; j < srcImage.cols; j++)

      { 

          index = i * width + j; 

int label = labels.at<int>(index); // Which label each pixel belongs to

result.at<Vec3b>(i, j)[0] = colorTab[label][0]; Result. at<Vec3b>(I, j)[1] = colorTab[label][1];

           result.at<Vec3b>(i, j)[2] = colorTab[label][2];

 } 

 } 

 namedWindow("Kmeans", 0); 

 imshow("Kmeans", result); 

 waitKey(0); 

 return 0; 

 }

Effect: