输出窗口显示三个图像,而不是一个

Three images are displayed in output window instead of one

本文关键字:一个 三个 窗口 显示 输出 图像      更新时间:2023-10-16

大家好,我尝试使用kmeans聚类对对象进行分组。这样我就可以使用这种聚类方法来检测对象。我得到输出,但问题是它太慢了{我怎么能解决这个??}得到的输出窗口如下面的链接所示。三个输出图像显示,而不是一个,我如何解决这个问题。我不知道错误在哪里。

http://tinypic.com/view.php?pic=30bd7dc& s = 8 # .VgkSIPmqqko

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main(  )
{
  Mat src = imread( "Light.jpg", 0 );
//  imshow("fff",src);
 // cvtColor(src,src,COLOR_BGR2GRAY);
  Mat dst;
 // pyrDown(src,src,Size( src.cols/2, src.rows/2 ),4);
 // src=dst;
  resize(src,src,Size(128,128),0,0,1);
  Mat samples(src.rows * src.cols, 3, CV_32F);
  for( int y = 0; y < src.rows; y++ )
    for( int x = 0; x < src.cols; x++ )
    //  for( int z = 0; z < 3; z++)
        samples.at<float>(y + x*src.rows) = src.at<uchar>(y,x);
    cout<<"aaa"<<endl;
  int clusterCount = 15;
  Mat labels;
  int attempts = 2;
  Mat centers;
    cout<<"aaa"<<endl;
  kmeans(samples, clusterCount, labels, TermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 10000, 0.0001), attempts, KMEANS_PP_CENTERS, centers );
  Mat new_image( src.size(), src.type() );
    cout<<"aaa"<<endl;
  for( int y = 0; y < src.rows; y++ )
    for( int x = 0; x < src.cols; x++ )
    { 
      int cluster_idx = labels.at<int>(y + x*src.rows,0);
      new_image.at<uchar>(y,x) = centers.at<float>(cluster_idx,0);
      //new_image.at<Vec3b>(y,x)[1] = centers.at<float>(cluster_idx, 1);
     // new_image.at<Vec3b>(y,x)[2] = centers.at<float>(cluster_idx, 2);
    }
  imshow( "clustered image", new_image );
  waitKey( 0 );
}

在初始代码中,如果使用灰度图像,则必须将中间介质Mat sample从3通道更改为1通道。

此外,如果您更改内存顺序,它可能会更快(在两个地方都更改为(y*src.cols + x, 0)):

int main(  )
{
  clock_t start = clock();
  Mat src = imread( "Light.jpg", 0 );
  Mat dst;
  resize(src,src,Size(128,128),0,0,1);
  Mat samples(src.rows * src.cols, 1, CV_32F);
  for( int y = 0; y < src.rows; y++ )
    for( int x = 0; x < src.cols; x++ )
        samples.at<float>(y*src.cols + x, 0) = src.at<uchar>(y,x);
  int clusterCount = 15;
  Mat labels;
  int attempts = 2;
  Mat centers;
  kmeans(samples, clusterCount, labels, TermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 10000, 0.0001), attempts, KMEANS_PP_CENTERS, centers );
  Mat new_image( src.size(), src.type() );
  for( int y = 0; y < src.rows; y++ )
    for( int x = 0; x < src.cols; x++ )
    { 
        int cluster_idx = labels.at<int>(y*src.cols + x,0);
        new_image.at<uchar>(y,x) = centers.at<float>(cluster_idx,0);  
    }
  imshow( "clustered image", new_image );
  clock_t end = clock();
  std::cout << "time: " << (end - start)/(float)CLOCKS_PER_SEC << std::endl;
  waitKey( 0 );
}
相关文章: