API
代码如下所示:
#include
#include
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
Mat src;
src = imread("D:/studytest/pk.bmp");
if (src.empty())
{
printf("could not load image...\n");
return -1;
}
namedWindow("input image", CV_WINDOW_AUTOSIZE);
imshow("input image", src);
//1.change background 将背景转换为黑色
for (int row = 0; row < src.rows; row++)
{
for(int col = 0; col < src.cols; col++)
{
if(src.at(row,col)==Vec3b(255,255,255))
{
src.at(row, col)[0] = 0;
src.at(row, col)[1] = 0;
src.at(row, col)[2] = 0;
}
}
}
namedWindow("black background", CV_WINDOW_AUTOSIZE);
imshow("black background", src);
//2.sharpen锐化提高对比度
Mat kernel = (Mat_(3, 3) << 1, 1, 1, 1, -8, 1, 1, 1, 1);
Mat imgLaplance;
Mat sharpenImg = src;
filter2D(src, imgLaplance, CV_32F, kernel, Point(-1, -1), 0, BORDER_DEFAULT);
src.convertTo(sharpenImg, CV_32F);
Mat resultImg = sharpenImg - imgLaplance;
resultImg.convertTo(resultImg, CV_8UC3);
imgLaplance.convertTo(imgLaplance, CV_8UC3);
imshow("锐化后的图像sharpen_image", resultImg);
//变换为二值图像
Mat binImg;
cvtColor(src, resultImg, CV_BGR2GRAY);
threshold(resultImg, binImg, 40, 255, THRESH_BINARY | THRESH_OTSU);
imshow("锐化后转二值的binImg", binImg);
//距离变换
Mat distImg;
distanceTransform(binImg, distImg, DIST_L1, 3, 5);
normalize(distImg, distImg, 0, 1, NORM_MINMAX);
imshow("距离变换后的distImg", distImg);
//距离变换结果二值化
threshold(distImg, distImg, 0.4, 1, THRESH_BINARY);
imshow("distImgtobin", distImg);
//腐蚀
Mat k1 = Mat::ones(13, 13, CV_8UC1);
erode(distImg, distImg, k1, Point(-1, -1));
imshow("腐蚀后的distImg", distImg);
//markers找轮廓
Mat dist_8u;
distImg.convertTo(dist_8u, CV_8U);
vector> contours;
findContours(dist_8u, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
//create makers 画轮廓markers标记
Mat markers = Mat::zeros(src.size(), CV_32SC1);
for (size_t i = 0; i < contours.size(); i++)
drawContours(markers, contours, static_cast(i), Scalar::all(static_cast(i) + 1),-1);
circle(markers, Point(5, 5), 3, Scalar(255, 255, 255), -1);
//imshow("my markers", markers*1000);
//perform watershed
watershed(src, markers);
Mat mark = Mat::zeros(markers.size(), CV_8UC1);
markers.convertTo(mark, CV_8UC1);
bitwise_not(mark, mark, Mat());
imshow("watershed image", mark);
// 分配不同颜色
vector colors;
for (size_t i = 0; i < contours.size(); i++) {
int r = theRNG().uniform(0, 255);
int g = theRNG().uniform(0, 255);
int b = theRNG().uniform(0, 255);
colors.push_back(Vec3b((uchar)b, (uchar)g, (uchar)r));
}
// 填充颜色
Mat dst = Mat::zeros(markers.size(), CV_8UC3);
for (int row = 0; row < markers.rows; row++) {
for (int col = 0; col < markers.cols; col++) {
int index = markers.at(row, col);
if (index > 0 && index <= static_cast(contours.size())) {
dst.at(row, col) = colors[index - 1];
}
else {
dst.at(row, col) = Vec3b(0, 0, 0);
}
}
}
imshow("Final Result", dst);
waitKey(0);
return 0;
}
结果如下图所示: