OpenCv截取任意形状 -- 实例

OpenCV实例: 在图中按下鼠标画一个任意形状的区域,右击截取该区域内的图像,其中copyTo函数可根据掩码提取图片内容。

#include "pch.h"
#include<iostream>
#include<opencv2\opencv.hpp>
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;
}

 

posted @ 2019-06-12 00:07  SpaceVision  阅读(63)  评论(0编辑  收藏  举报