创建另一个图像,复制其中的数据未屏蔽数据,并使用此矩阵执行您的 kmeans。事情是这样的:
[编辑]
以下不起作用,它只是遮罩中的像素,但 tmp 与原始图像具有相同的尺寸。
简历::垫 tmp;
labImage.copyTo(tmp, mask);
您应该预先分配 tmp 矩阵,并在掩码上用循环填充它:
cv::Mat tmp = cv::Mat::zeros(cv::countNonZero(mask), 1, labImage.type());
int counter = 0;
for (int r = 0; r < mask.rows; ++r)
for (int c = 0; c < mask.cols; ++c)
if (!mask.at<unsigned char>(r, c))
// I assume Lab pixels are stored as a vector of floats
tmp.at<cv::Vec3f>(counter++, 0) = labImage.at<cv::Vec3b>(r, c);
[/编辑]
cv::kmeans(tmp, k, labels);
// Now to compute your image of labels
cv::Mat labelsImage = cv::Mat(labImage.size(), CV_32S, k); // initialize pixel values to K, which is the index of your N+1 cluster
// Now loop through your pixel mask and set the correspondance in your labelImage
int counter = 0;
for (int r = 0; r < mask.rows; ++r)
for (int c = 0; c < mask.cols; ++c)
if (!mask.at<unsigned char>(r, c))
labelsImage.at<int>(r, c) = labels.at<int>(counter++, 0);