正文之前
虽然三天后就是毕业答辩的日子了。但是我仍然在这个时候保持着优秀的作死精神!!居然今天花了起码三个小时看OpenCV。。。。。而且居然还看出了不少东西。。下面放放我今天学的东西
正文
//##########################打开摄像头##########################
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
VideoCapture cap(0);
if(!cap.isOpened()){
return -1;
}
Mat frame;
Mat edges;
bool stoped = false;
while (!stoped){
cap>>frame;
cvtColor(frame, edges, CV_BGR2GRAY);
// GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
// Canny(edges, edges, 0, 30 ,0);
imshow("The Video Now!", frame);
if(waitKey(10) >=0 ){
stoped = true;
}
}
return 0;
}
//##########################打开摄像头##########################
这个是打开摄像头的~ ,效果如图
人脸识别这个有点问题。。而且还要两个很长的辅助文件。。大家伙自己去玩吧。。。我就不奉陪了。。
//##########################人脸识别##########################
//#include "opencv2/objdetect.hpp"
//#include "opencv2/highgui.hpp"
//#include "opencv2/imgproc.hpp"
//
//#include <stdio.h>
//
//using namespace std;
//using namespace cv;
//
///** Function Headers */
//void detectAndDisplay( Mat frame );
//
///** Global variables */
//String face_cascade_name, eyes_cascade_name;
//CascadeClassifier face_cascade;
//CascadeClassifier eyes_cascade;
//String window_name = "Capture - Face detection";
//
///** @function main */
//int main( int argc, const char** argv )
//{
// CommandLineParser parser(argc, argv,
// "{help h||}"
// "{face_cascade|haarcascade_frontalface_alt.xml|}"
// "{eyes_cascade|haarcascade_eye_tree_eyeglasses.xml|}");
//
// parser.about( "\nThis program demonstrates using the cv::CascadeClassifier class to detect objects (Face + eyes) in a video stream.\n"
// "You can use Haar or LBP features.\n\n" );
// parser.printMessage();
//
// face_cascade_name = parser.get<String>("face_cascade");
// eyes_cascade_name = parser.get<String>("eyes_cascade");
// VideoCapture capture;
// Mat frame;
//
// //-- 1. Load the cascades
// if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading face cascade\n"); return -1; };
// if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading eyes cascade\n"); return -1; };
//
// //-- 2. Read the video stream
// capture.open( 0 );
// if ( ! capture.isOpened() ) { printf("--(!)Error opening video capture\n"); return -1; }
//
// while ( capture.read(frame) )
// {
// if( frame.empty() )
// {
// printf(" --(!) No captured frame -- Break!");
// break;
// }
//
// //-- 3. Apply the classifier to the frame
// detectAndDisplay( frame );
//
// if( waitKey(10) == 27 ) { break; } // escape
// }
// return 0;
//}
//
///** @function detectAndDisplay */
//void detectAndDisplay( Mat frame )
//{
// std::vector<Rect> faces;
// Mat frame_gray;
//
// cvtColor( frame, frame_gray, COLOR_BGR2GRAY );
// equalizeHist( frame_gray, frame_gray );
//
// //-- Detect faces
// face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CASCADE_SCALE_IMAGE, Size(60, 60) );
//
// for ( size_t i = 0; i < faces.size(); i++ )
// {
// Point center( faces[i].x + faces[i].width/2, faces[i].y + faces[i].height/2 );
// ellipse( frame, center, Size( faces[i].width/2, faces[i].height/2 ), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
//
// Mat faceROI = frame_gray( faces[i] );
// std::vector<Rect> eyes;
//
// //-- In each face, detect eyes
// eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CASCADE_SCALE_IMAGE, Size(30, 30) );
//
// for ( size_t j = 0; j < eyes.size(); j++ )
// {
// Point eye_center( faces[i].x + eyes[j].x + eyes[j].width/2, faces[i].y + eyes[j].y + eyes[j].height/2 );
// int radius = cvRound( (eyes[j].width + eyes[j].height)*0.25 );
// circle( frame, eye_center, radius, Scalar( 255, 0, 0 ), 4, 8, 0 );
// }
// }
// //-- Show what you got
// imshow( window_name, frame );
//}
//##########################打开摄像头##########################
//##########################追踪点##########################
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
#include <ctype.h>
using namespace cv;
using namespace std;
static void help()
{
// print a welcome message, and the OpenCV version
cout << "\nThis is a demo of Lukas-Kanade optical flow lkdemo(),\n"
"Using OpenCV version " << CV_VERSION << endl;
cout << "\nIt uses camera by default, but you can provide a path to video as an argument.\n";
cout << "\nHot keys: \n"
"\tESC - quit the program\n"
"\tr - auto-initialize tracking\n"
"\tc - delete all the points\n"
"\tn - switch the \"night\" mode on/off\n"
"To add/remove a feature point click it\n" << endl;
}
Point2f point;
bool addRemovePt = false;
static void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ )
{
if( event == EVENT_LBUTTONDOWN )
{
point = Point2f((float)x, (float)y);
addRemovePt = true;
}
}
int main( int argc, char** argv )
{
VideoCapture cap;
TermCriteria termcrit(TermCriteria::COUNT|TermCriteria::EPS,20,0.03);
Size subPixWinSize(10,10), winSize(31,31);
const int MAX_COUNT = 500;
bool needToInit = false;
bool nightMode = false;
help();
cv::CommandLineParser parser(argc, argv, "{@input|0|}");
string input = parser.get<string>("@input");
if( input.size() == 1 && isdigit(input[0]) )
cap.open(input[0] - '0');
else
cap.open(input);
if( !cap.isOpened() )
{
cout << "Could not initialize capturing...\n";
return 0;
}
namedWindow( "LK Demo", 1 );
setMouseCallback( "LK Demo", onMouse, 0 );
Mat gray, prevGray, image, frame;
vector<Point2f> points[2];
for(;;)
{
cap >> frame;
if( frame.empty() )
break;
frame.copyTo(image);
cvtColor(image, gray, COLOR_BGR2GRAY);
if( nightMode )
image = Scalar::all(0);
if( needToInit )
{
// automatic initialization
goodFeaturesToTrack(gray, points[1], MAX_COUNT, 0.01, 10, Mat(), 3, 3, 0, 0.04);
cornerSubPix(gray, points[1], subPixWinSize, Size(-1,-1), termcrit);
addRemovePt = false;
}
else if( !points[0].empty() )
{
vector<uchar> status;
vector<float> err;
if(prevGray.empty())
gray.copyTo(prevGray);
calcOpticalFlowPyrLK(prevGray, gray, points[0], points[1], status, err, winSize,
3, termcrit, 0, 0.001);
size_t i, k;
for( i = k = 0; i < points[1].size(); i++ )
{
if( addRemovePt )
{
if( norm(point - points[1][i]) <= 5 )
{
addRemovePt = false;
continue;
}
}
if( !status[i] )
continue;
points[1][k++] = points[1][i];
circle( image, points[1][i], 3, Scalar(0,255,0), -1, 8);
}
points[1].resize(k);
}
if( addRemovePt && points[1].size() < (size_t)MAX_COUNT )
{
vector<Point2f> tmp;
tmp.push_back(point);
cornerSubPix( gray, tmp, winSize, Size(-1,-1), termcrit);
points[1].push_back(tmp[0]);
addRemovePt = false;
}
needToInit = false;
imshow("LK Demo", image);
char c = (char)waitKey(10);
if( c == 27 )
break;
switch( c )
{
case 'r':
needToInit = true;
break;
case 'c':
points[0].clear();
points[1].clear();
break;
case 'n':
nightMode = !nightMode;
break;
}
std::swap(points[1], points[0]);
cv::swap(prevGray, gray);
}
return 0;
}
//##########################追踪点##########################
算了。怕卵子哦。。男生没什么好扭扭捏捏的。。。我就长这样。。。
#include <opencv2/core/utility.hpp>
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
#include <ctype.h>
using namespace cv;
using namespace std;
Mat image;
bool backprojMode = false;
bool selectObject = false;
int trackObject = 0;
bool showHist = true;
Point origin;
Rect selection;
int vmin = 10, vmax = 256, smin = 30;
// User draws box around object to track. This triggers CAMShift to start tracking
static void onMouse( int event, int x, int y, int, void* )
{
if( selectObject )
{
selection.x = MIN(x, origin.x);
selection.y = MIN(y, origin.y);
selection.width = std::abs(x - origin.x);
selection.height = std::abs(y - origin.y);
selection &= Rect(0, 0, image.cols, image.rows);
}
switch( event )
{
case EVENT_LBUTTONDOWN:
origin = Point(x,y);
selection = Rect(x,y,0,0);
selectObject = true;
break;
case EVENT_LBUTTONUP:
selectObject = false;
if( selection.width > 0 && selection.height > 0 )
trackObject = -1; // Set up CAMShift properties in main() loop
break;
}
}
string hot_keys =
"\n\nHot keys: \n"
"\tESC - quit the program\n"
"\tc - stop the tracking\n"
"\tb - switch to/from backprojection view\n"
"\th - show/hide object histogram\n"
"\tp - pause video\n"
"To initialize tracking, select the object with mouse\n";
static void help()
{
cout << "\nThis is a demo that shows mean-shift based tracking\n"
"You select a color objects such as your face and it tracks it.\n"
"This reads from video camera (0 by default, or the camera number the user enters\n"
"Usage: \n"
" ./camshiftdemo [camera number]\n";
cout << hot_keys;
}
const char* keys =
{
"{help h | | show help message}{@camera_number| 0 | camera number}"
};
int main( int argc, const char** argv )
{
VideoCapture cap;
Rect trackWindow;
int hsize = 16;
float hranges[] = {0,180};
const float* phranges = hranges;
CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
help();
return 0;
}
int camNum = parser.get<int>(0);
cap.open(camNum);
if( !cap.isOpened() )
{
help();
cout << "***Could not initialize capturing...***\n";
cout << "Current parameter's value: \n";
parser.printMessage();
return -1;
}
cout << hot_keys;
namedWindow( "Histogram", 0 );
namedWindow( "CamShift Demo", 0 );
setMouseCallback( "CamShift Demo", onMouse, 0 );
createTrackbar( "Vmin", "CamShift Demo", &vmin, 256, 0 );
createTrackbar( "Vmax", "CamShift Demo", &vmax, 256, 0 );
createTrackbar( "Smin", "CamShift Demo", &smin, 256, 0 );
Mat frame, hsv, hue, mask, hist, histimg = Mat::zeros(200, 320, CV_8UC3), backproj;
bool paused = false;
for(;;)
{
if( !paused )
{
cap >> frame;
if( frame.empty() )
break;
}
frame.copyTo(image);
if( !paused )
{
cvtColor(image, hsv, COLOR_BGR2HSV);
if( trackObject )
{
int _vmin = vmin, _vmax = vmax;
inRange(hsv, Scalar(0, smin, MIN(_vmin,_vmax)),
Scalar(180, 256, MAX(_vmin, _vmax)), mask);
int ch[] = {0, 0};
hue.create(hsv.size(), hsv.depth());
mixChannels(&hsv, 1, &hue, 1, ch, 1);
if( trackObject < 0 )
{
// Object has been selected by user, set up CAMShift search properties once
Mat roi(hue, selection), maskroi(mask, selection);
calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges);
normalize(hist, hist, 0, 255, NORM_MINMAX);
trackWindow = selection;
trackObject = 1; // Don't set up again, unless user selects new ROI
histimg = Scalar::all(0);
int binW = histimg.cols / hsize;
Mat buf(1, hsize, CV_8UC3);
for( int i = 0; i < hsize; i++ )
buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180./hsize), 255, 255);
cvtColor(buf, buf, COLOR_HSV2BGR);
for( int i = 0; i < hsize; i++ )
{
int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows/255);
rectangle( histimg, Point(i*binW,histimg.rows),
Point((i+1)*binW,histimg.rows - val),
Scalar(buf.at<Vec3b>(i)), -1, 8 );
}
}
// Perform CAMShift
calcBackProject(&hue, 1, 0, hist, backproj, &phranges);
backproj &= mask;
RotatedRect trackBox = CamShift(backproj, trackWindow,
TermCriteria( TermCriteria::EPS | TermCriteria::COUNT, 10, 1 ));
if( trackWindow.area() <= 1 )
{
int cols = backproj.cols, rows = backproj.rows, r = (MIN(cols, rows) + 5)/6;
trackWindow = Rect(trackWindow.x - r, trackWindow.y - r,
trackWindow.x + r, trackWindow.y + r) &
Rect(0, 0, cols, rows);
}
if( backprojMode )
cvtColor( backproj, image, COLOR_GRAY2BGR );
ellipse( image, trackBox, Scalar(0,0,255), 3, LINE_AA );
}
}
else if( trackObject < 0 )
paused = false;
if( selectObject && selection.width > 0 && selection.height > 0 )
{
Mat roi(image, selection);
bitwise_not(roi, roi);
}
imshow( "CamShift Demo", image );
imshow( "Histogram", histimg );
char c = (char)waitKey(10);
if( c == 27 )
break;
switch(c)
{
case 'b':
backprojMode = !backprojMode;
break;
case 'c':
trackObject = 0;
histimg = Scalar::all(0);
break;
case 'h':
showHist = !showHist;
if( !showHist )
destroyWindow( "Histogram" );
else
namedWindow( "Histogram", 1 );
break;
case 'p':
paused = !paused;
break;
default:
;
}
}
return 0;
}
物体追踪。。这个比较蠢。。
//##########################图片混合##########################
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
Mat image = imread("/Users/zhangzhaobo/CLionProjects/CDB/kate.jpg");
Mat logo = imread("/Users/zhangzhaobo/CLionProjects/CDB/miaomiao.jpg");
Mat imageROI;
imageROI = image(Range(350,350+logo.rows), Range(600,600+logo.cols));
addWeighted(imageROI, 0.3, logo, 1, 0, imageROI);
namedWindow("[3] Mix");
imshow("[3] Mix", image);
Vec3f intensity=image.at<Vec3f>(100,20);
cout<<intensity[0]<<"->"<<intensity[1]<<"->"<<intensity[2]<<endl;
imwrite("/Users/zhangzhaobo/CLionProjects/CDB/Mix.jpg", image);
waitKey();
return 0;
}
//##########################图片混合##########################
下面是图片混合。。。还蛮好用的。。
//##########################反色处理##########################
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main(int argc, char** args)
{
Mat image = imread("/Users/zhangzhaobo/CLionProjects/CDB/miaomiao.jpg");
if (image.empty())
{
cout << "不能加载图像..." << std::endl;
return -1;
}
Mat dst;
cvtColor(image, dst, CV_BGR2GRAY);
int height = image.rows;
int width = image.cols;
int channels = image.channels();
printf("height=%d,width=%d channels=%d",height,width,channels);
for (int row = 0; row < height;row++)
{
for (int col = 0; col < width;col++)
{
if (channels==3)
{
// image.at<Vec3b>(row, col)[0] = 0;//blue 通道
// image.at<Vec3b>(row, col)[1] = 0;//green 通道
// image.at<Vec3b>(row, col)[2] = 255 - image.at<Vec3b>(row, col)[2];// red 通道
// image.at<Vec3b>(row, col)[0] = 255 - image.at<Vec3b>(row, col)[0];//blue 通道
// image.at<Vec3b>(row, col)[1] = 255 - image.at<Vec3b>(row, col)[1];//green 通道
// image.at<Vec3b>(row, col)[2] = 255 - image.at<Vec3b>(row, col)[2];// red 通道
// image.at<Vec3b>(row, col)[0] = 0;//blue 通道
// image.at<Vec3b>(row, col)[1] = 255 - image.at<Vec3b>(row, col)[1];//green 通道
// image.at<Vec3b>(row, col)[2] = 0;// red 通道
image.at<Vec3b>(row, col)[0] = 255 - image.at<Vec3b>(row, col)[0];//blue 通道
image.at<Vec3b>(row, col)[1] = 0;//green 通道
image.at<Vec3b>(row, col)[2] = 0;// red 通道
}
//else if (channels==1)
//{
// dst.at<uchar>(row, col) = 255 - dst.at<uchar>(row, col);
//}
}
}
namedWindow("输出图像-2", CV_WINDOW_AUTOSIZE);
imshow("输出图像-2", image);
waitKey(0);
return 0;
}
//##########################反色处理##########################
这个是通道。也可以用来反相。随便你设置吧。
#include <iostream>
#include <opencv2/opencv.hpp>
#define WINDOW_NAME "【程序窗口】"
using namespace cv;
using namespace std;
void on_MouseHandle(int event, int x, int y, int flags, void * param);
void DrawRectangle(Mat & img, Rect box);
void ShowHelpText();
Rect g_rectangle;
bool g_bDrawingBox = false;
RNG g_rng(12345);
int main(int argc, char ** argv)
{
Rect g_rectangle = Rect(-1,-1,0,0);
Mat srcImage(600,800,CV_8UC3),tempIamge;
srcImage.copyTo(tempIamge);
g_rectangle = Rect(-1,-1,0,0);
srcImage = Scalar::all(0);
namedWindow(WINDOW_NAME);
setMouseCallback(WINDOW_NAME,on_MouseHandle,(void *) &srcImage);
while(true)
{
srcImage.copyTo(tempIamge);
if (g_bDrawingBox)
{
DrawRectangle(tempIamge,g_rectangle);
}
imshow(WINDOW_NAME, tempIamge);
if (waitKey(10)==27) break;
}
return 0;
}
void on_MouseHandle(int event, int x, int y, int flags, void * param)
{
Mat & image = *(Mat *)param;
switch(event)
{
case EVENT_MOUSEMOVE:
{
if (g_bDrawingBox)
{
g_rectangle.width = x - g_rectangle.x;
g_rectangle.height = y - g_rectangle.y;
}
break;
}
case EVENT_LBUTTONDOWN:
{
g_bDrawingBox =true;
g_rectangle = Rect(x,y,0,0);
break;
}
case EVENT_LBUTTONUP:
{
g_bDrawingBox = false;
if (g_rectangle.width < 0)
{
g_rectangle.x += g_rectangle.width;
g_rectangle.width *= -1;
}
if (g_rectangle.height < 0)
{
g_rectangle.y += g_rectangle.height;
g_rectangle.height *= -1;
}
DrawRectangle(image, g_rectangle);
break;
}
}
}
void DrawRectangle(Mat & img, Rect box)
{
rectangle(img, box.tl(), box.br(),Scalar(g_rng.uniform(0,255),g_rng.uniform(0,255),g_rng.uniform(0,255)));
}
最后是鼠标追踪。。。这个很好玩。。基本可实现画矩形的需求。。。当然,后续可以开发一个画图软件。。。不过。。。算了。不干了。。重复性工作。。
正文之后
OK!写完跑步去咯~ 对了今天还做了一个python的画图的动画。。给你看看~