OpenCV图像分割Grabcut算法
生活随笔
收集整理的這篇文章主要介紹了
OpenCV图像分割Grabcut算法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前言
1.OpenCV圖像分割Grabcut算法主要功能是分割和摳圖,就是把框著的目標(biāo)摳出來,比如要分割出一個(gè)證件照的人的圖像,只需要在目標(biāo)外面畫一個(gè)框,把目標(biāo)框住,它就可以完成良好的分割。
2.算法運(yùn)行的效果如下,如果想
代碼
#include <iostream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp>bool mouse_down = false, mouse_up = false; cv::Point corner1, corner2; cv::Rect rect; cv::Mat src;static void mouseCallback(int event, int x, int y, int, void*) {cv::Mat bg_model, fg_model, mask;if (event == cv::EVENT_LBUTTONDOWN){mouse_down = true;corner1.x = x;corner1.y = y;}if (event == cv::EVENT_LBUTTONUP){if (abs(x - corner1.x) > 10 && abs(y - corner1.y) > 10){mouse_up = true;mouse_down = false;corner2.x = x;corner2.y = y;}else{mouse_down = false;}}if (mouse_down == true && mouse_up == false){cv::Point pt;pt.x = x;pt.y = y;cv::Mat local_img = src.clone();rectangle(local_img, corner1, pt, cv::Scalar(0, 0, 255), 3);imshow("Cropping app", local_img);}if (mouse_down == false && mouse_up == true){rect.width = abs(corner1.x - corner2.x);rect.height = abs(corner1.y - corner2.y);rect.x = std::min(corner1.x, corner2.x);rect.y = std::min(corner1.y, corner2.y);grabCut(src, mask, rect, bg_model, fg_model, 5, cv::GC_INIT_WITH_RECT);compare(mask, cv::GC_PR_FGD, mask, cv::CMP_EQ);cv::namedWindow("crop",0);cv::Mat image_roi;image_roi.create(src.size(), src.type());image_roi.setTo(cv::Scalar(255, 255, 255));src.copyTo(image_roi, mask);cv::Mat crop(image_roi, rect);cv::imshow("crop", crop);mouse_down = false;mouse_up = false;} } int main() {src = cv::imread("12.jpg");cv::namedWindow("cropping",0);cv::imshow("cropping", src);cv::setMouseCallback("cropping", mouseCallback);cvWaitKey(0);return 0; } 《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的OpenCV图像分割Grabcut算法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt与OpenCV编程:在子线程打开摄像
- 下一篇: OpenCV黑白图像增强——灰度级切片