OpenCv截取任意形状 -- 实例

网友投稿 208 2022-11-23

OpenCv截取任意形状 -- 实例

OpenCV实例: 在图中按下鼠标画一个任意形状的区域,右击截取该区域内的图像,其中copyTo函数可根据掩码提取图片内容。 #include "pch.h" #include #include using namespace std; using namespace cv; cv::Mat img; cv::Mat imgMask; cv::Mat imgOrg; Point lastPt; Point firstPt; /* double cv::threshold( InputArray src, // src input array (multiple-channel, 8-bit or 32-bit floating point). OutputArray dst, // dst output array of the same size and type and the same number of channels as src. double thresh, // thresh threshold value. double maxval, // maxval maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types. int type // type thresholding type (see ThresholdTypes). ) */ void on_mouse_callback(int event, int x, int y, int flags, void* yybird) { if (!img.data){ printf("image is empty!\n"); return; } Point pt = Point(x, y); if (event == cv::EVENT_LBUTTONUP ) { //|| !(flags & cv::EVENT_FLAG_LBUTTON) line(img, pt, firstPt, Scalar(0, 0, 255), 1, 8, 0); line(imgMask, pt, firstPt, Scalar(255, 255, 255), 1, 8, 0); imshow("image", img); } else if (event == cv::EVENT_LBUTTONDOWN) { firstPt = lastPt = Point(x, y); } else if( (event == cv::EVENT_MOUSEMOVE) && (flags & cv::EVENT_FLAG_LBUTTON) ) { if (lastPt.x < 0) { lastPt = pt; } line(img, lastPt, pt, Scalar(0, 0, 255), 1, 8, 0); // display a red line line(imgMask, lastPt, pt, Scalar(255, 255, 255), 1, 8, 0); imshow("image", img); lastPt = pt; } if (event == cv::EVENT_RBUTTONUP)//右击选择框图 { //fill color floodFill(imgMask, Point(x, y), Scalar(255, 255, 255)); // make a mask Mat grayMask = imgMask.clone(); // the Scalar(255,255,255) will be converted to Scalar(255) gray data cvtColor(imgMask, grayMask, COLOR_BGR2GRAY); // change the value to see what will happen... cv::threshold(grayMask, grayMask, 254, 255, THRESH_BINARY); imshow("grayMask", grayMask); // extract region imgOrg.copyTo(imgMask, grayMask); imshow("Image in Mask", imgMask); } } int main(int argc, char** argv) { string strPath = "C:/Users/Administrator/img_7233.jpg"; imgOrg = cv::imread(strPath.c_str(), 1); img = imgOrg.clone(); imgMask = imgOrg.clone(); // 255 for easy detection imgMask = Scalar::all(0); namedWindow("image", 1); imshow("image", img); cv::setMouseCallback("image", on_mouse_callback, 0); waitKey(0); return 0; }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:可编程网络的发展历史
下一篇:矽海达科技SHD1 COFDM接收地面站主板介绍
相关文章

 发表评论

暂时没有评论,来抢沙发吧~