OpenCV在图像上运行kmeans算法

时间:2011-08-10 18:29:50

标签: c++ c opencv image-processing k-means

我正在尝试在3通道彩色图像上运行kmeans,但每次我尝试运行该功能时,它似乎崩溃并出现以下错误:

OpenCV Error: Assertion failed (data.dims <= 2 && type == CV_32F && K > 0) in unknown function, file ..\..\..\OpenCV-2.3.0\modules\core\src\matrix.cpp, line 2271

我已经在下面添加了一些代码,以帮助指定传入的内容。非常感谢任何帮助。

// Load in an image
// Depth: 8, Channels: 3
IplImage* iplImage = cvLoadImage("C:/TestImages/rainbox_box.jpg");

// Create a matrix to the image
cv::Mat mImage = cv::Mat(iplImage);

// Create a single channel image to create our labels needed
IplImage* iplLabels = cvCreateImage(cvGetSize(iplImage), iplImage->depth, 1);

// Convert the image to grayscale
cvCvtColor(iplImage, iplLabels, CV_RGB2GRAY);

// Create the matrix for the labels
cv::Mat mLabels = cv::Mat(iplLabels);

// Create the labels
int rows = mLabels.total();
int cols = 1;
cv::Mat list(rows, cols, mLabels .type());
uchar* src;
uchar* dest = list.ptr(0);
for(int i=0; i<mLabels.size().height; i++) 
{
    src = mLabels.ptr(i);
    memcpy(dest, src, mLabels.step);
    dest += mLabels.step;
}
list.convertTo(list, CV_32F);

// Run the algorithm
cv::Mat labellist(list.size(), CV_8UC1);
cv::Mat centers(6, 1, mImage.type());
cv::TermCriteria termcrit(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0);
kmeans(mImage, 6, labellist, termcrit, 3, cv::KMEANS_PP_CENTERS, centers);

1 个答案:

答案 0 :(得分:11)

错误说明所有Assertion failed (data.dims <= 2 && type == CV_32F && K > 0)

这些是非常简单的理解规则,该功能仅在以下情况下有效:

  • mImage.depth()CV_32F

  • 如果mImage.dims<= 2

  • 以及K > 0。在这种情况下,您将K定义为 6

根据你在问题上所说的,似乎:

IplImage* iplImage = cvLoadImage("C:/TestImages/rainbox_box.jpg");` 

默认情况下将图片加载为IPL_DEPTH_8U,而不是IPL_DEPTH_32F。这意味着mImage也是IPL_DEPTH_8U,这就是您的代码无效的原因。