c++代码
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
Mat cartoonifyImage(Mat srcColor, Mat result)
{
Mat gray;
cvtColor(srcColor, gray, CV_BGR2GRAY);//灰度化
const int MEDIAN_BLUR_FILTER_SIZE = 7;
medianBlur(gray, gray, MEDIAN_BLUR_FILTER_SIZE);//中值滤波滤除噪音
Mat edges;
const int LAPLACIAN_FILTER_SIZE = 5;
Laplacian(gray, edges, CV_8U, LAPLACIAN_FILTER_SIZE);//Laplacian边缘检测
Mat mask;
const int EDGES_THRESHOLD = 80;
threshold(edges, mask, EDGES_THRESHOLD, 255, THRESH_BINARY_INV);//黑白化
result = mask;
return result;
}
int main()
{
VideoCapture camera(0);
Mat cameraFrame;
//camera.open(cameraNumber);
if (!camera.isOpened())
{
cerr << "ERROR:Could not access the camera or video" << endl;
exit(1);//返回1表示异常中止
}
//分辨率设置为640*480,此台电脑对视频输入的图像不起作用,摄像头可以
camera.set(CV_CAP_PROP_FRAME_WIDTH, 640);
camera.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
while (camera.isOpened())
{
camera >> cameraFrame;
if (cameraFrame.empty())
{
cerr << "ERROR:Could not grab a camera frame" << endl;
exit(1);
}
Mat displayedFrame(cameraFrame.size(), CV_8UC3);
//创建cartoonifier filter
displayedFrame = cartoonifyImage(cameraFrame, displayedFrame);
imshow("素描图", displayedFrame);
if (waitKey(40)==27)//esc键退出
break;
}
return 0;
}
运行结果