OpenCV C++ 简单小技巧 - 分水岭分割 (19

watershed()

Mat frame;
Mat f1,f2,f3,f4,f5;
Mat kernal = Mat::ones(3, 3, CV_8U);
UIImage* img1 = [UIImage imageNamed:@"p15"];
UIImageToMat(img1, frame);
resize(frame, frame, {512, 512});
cvtColor(frame, frame, COLOR_BGRA2BGR);
cvtColor(frame, f1, COLOR_BGR2GRAY);
morphologyEx(f1, f2, MORPH_OPEN, kernal);
dilate(f2, f2, kernal,{-1,-1},3);

Mat fTmp1,fTmp2,fTmp3;
threshold(f2, f4, 0, 255, THRESH_BINARY_INV+THRESH_OTSU);
distanceTransform(f4, fTmp1, DIST_L1, 0);
double minVal,maxVal;
minMaxLoc(fTmp1, &minVal,&maxVal);
threshold(fTmp1, fTmp2, 1.0* maxVal, 255, THRESH_BINARY);
fTmp2.assignTo(fTmp2,CV_8U);
subtract(f2, fTmp2, f5);

GaussianBlur(f2, f3, {5,5}, 2);
Canny(f3, f3, 80, 150);

vector> contours;
vector hierarchy;
GaussianBlur(f1,f1,cv::Size(5,5),2);
Canny(f1,f1,80,255);
findContours(f1, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE,{0,0});
Mat imageContours = Mat::zeros(frame.rows, frame.cols, CV_8UC1);
Mat marks(frame.rows,frame.cols,CV_32S);
marks = Scalar::all(0);

int index =0;
int compCount = 0;
for (; index>=0; index = hierarchy[index][0],compCount++) {
    drawContours(marks, contours, index, Scalar::all(compCount+1),1,8,hierarchy);
    drawContours(imageContours, contours, index, Scalar(255),1,8,hierarchy);
}

Mat marksShows;
convertScaleAbs(marks, marksShows);
watershed(frame, marks);

Mat afterWaterShed;
convertScaleAbs(marks, afterWaterShed);
Mat perspectiveImage = Mat::zeros(frame.rows, frame.cols, CV_8UC3);
for (int i=0; i(i,j);
        if (index==-1) {
            perspectiveImage.at(i,j)=Vec3b(255,255,255);
        }else{
            int val = index%255;
            RNG rng;
            perspectiveImage.at(i,j)= Vec3b(rng.uniform(0, val),rng.uniform(0, val),rng.uniform(0, val));
        }
    }
}
addWeighted(frame, .4, perspectiveImage, .6, 0, f3);
OpenCV C++ 简单小技巧 - 分水岭分割 (19_第1张图片
image.png

右侧两个色块就是分水岭效果。黑底是独立的,灰底是原图合并的。

你可能感兴趣的:(OpenCV C++ 简单小技巧 - 分水岭分割 (19)