本文整理汇总了C++中VideoWriter类的典型用法代码示例。如果您正苦于以下问题:C++ VideoWriter类的具体用法?C++ VideoWriter怎么用?C++ VideoWriter使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VideoWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
int main( int argc, char* argv[] )
{
VideoCapture cap;
TermCriteria termcrit(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03);
Size winSize(10,10);
bool needToInit =true;
bool nightMode = false;
bool reSift=true;
if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0])))
cap.open(argc == 2 ? argv[1][0] - '0' : 0);
else if( argc == 2 )
cap.open(argv[1]);
if( !cap.isOpened() )
{
cout << "Could not initialize capturing...\n";
return 0;
}
Mat gray, prevGray, image;
vector<Point2f> points[2];
VideoWriter wri;
siftCorner cornerFinder;
if(!cornerFinder.Init("track.config"))
{
cout<<"Can not Init cornerFinder"<<endl;
return 0;
}
const string backGroundFilename="background.jpg";
const float alpha=0.85;
Mat backGround;
backGround=imread(backGroundFilename,CV_LOAD_IMAGE_GRAYSCALE);
backGroundModel bgModel;
bgModel.Init(alpha,backGround);
namedWindow("Track",1);
const int step=1;
reSiftValidate validator;
Tracker *tracker=NULL;
Object curObj;
tracker=new LKTracker;
//validator.init();
//
DECLARE_TIMING(myTimer);
START_TIMING(myTimer);
DECLARE_TIMING(siftTimer);
for(;;)
{
Mat frame;
for(int ii(0);ii<step;++ii)
cap >> frame;
if( frame.empty() )
break;
frame.copyTo(image);
cvtColor(image, gray, CV_BGR2GRAY);
if( nightMode )
image = Scalar::all(0);
medianBlur(gray,gray,3);
bgModel.renewModel(gray);
if( needToInit )
{
char fileNameBuffer[30];
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
sprintf(fileNameBuffer
,"output/%d_%d_%d_%d_%d_%d.avi"
,timeinfo->tm_year+1900,timeinfo->tm_mon,timeinfo->tm_mday,timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
wri.open(fileNameBuffer,CV_FOURCC('X','V','I','D'),50,image.size(),true);
if(!wri.isOpened())
{
cout<<"can not init the writer"<<endl;
return 0;
}
needToInit = false;
tracker->Init(gray);
}
if(reSift)
{
START_TIMING(siftTimer);
cout<<"reSift"<<endl;
Mat Mask;
//.........这里部分代码省略.........
示例2: main
void main(int argc,char *argv[])
{
string file_in,file_out;
int threshold;
if(argc!=1){
file_in = argv[1];
string str = argv[2];
threshold = atoi(str.c_str());;
file_out = argv[3];
}else{
cout<<"Please input the input file:";
cin>>file_in;
cout<<"Please input the threshold:";
cin>>threshold;
cout<<"Please input the output file:";
cin>>file_out;
}
/** 打开输入视频文件 */
cv::VideoCapture vc;
vc.open(file_in);
if ( vc.isOpened() )
{
/** 打开输出视频文件 */
VideoWriter vw;
vw.open(file_out, // 输出视频文件名
(int)vc.get( CV_CAP_PROP_FOURCC ),
(double)vc.get( CV_CAP_PROP_FPS ),
cv::Size( (int)vc.get( CV_CAP_PROP_FRAME_WIDTH ), (int)vc.get( CV_CAP_PROP_FRAME_HEIGHT ) ), // 视频大小
false ); // 是否输出彩色视频
/** 如果成功打开输出视频文件 */
if ( vw.isOpened() )
{
while ( true )
{
/** 读取当前视频帧 */
cv::Mat in;
vc >> in;
/** 若视频读取完毕,跳出循环 */
if ( in.empty() )
{
break;
}
IplImage s = in;//原图
IplImage *color = &s;
cvShowImage(file_in.c_str(), color );//显示原图
char c = cvWaitKey(30);//等待
//转为灰度图
IplImage *gray = cvCreateImage(cvGetSize(color), 8,1);
cvCvtColor(color,gray,CV_BGR2GRAY);
//转为二值图
IplImage *binary = cvCreateImage(cvGetSize(gray), 8,1);//二值图
cvThreshold(gray,binary,threshold,255,CV_THRESH_BINARY);
//插入文字
CvFont font;
double hscale = 0.5;
double vscale = 0.5;
int linewidth = 1;
cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX | CV_FONT_ITALIC,hscale,vscale,0,linewidth);
CvScalar textColor =cvScalar(255,255,255);
CvPoint textPos =cvPoint(0,15);
cvPutText(binary,"Wang Zhefeng 3110000026", textPos, &font,textColor);
//显示输出图像
cvShowImage(file_out.c_str(), binary );
/** 将视频写入文件 */
Mat out(binary);
vw << out;
}
}
}
示例3: main
int main( int argc, char *argv[] ){
int max_offset = 280;
int cmp_width;
char *name1 = argv[1];
VideoCapture cap;
VideoWriter out;
cap.open(name1);
int ex = static_cast<int>(cap.get(CV_CAP_PROP_FOURCC));
out.open("out1.avi",
ex,
60,
Size(1280, 960),
false);
char s[5];
s[4] = 0;
memcpy(s, &ex, 4);
printf("%s\n", s);
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat mat;
int nframes = cap.get(CV_CAP_PROP_FRAME_COUNT);
for (int i = 0; i < 5; i++) {
mat = GetFrame(cap);
}
int sy, sx;
sy = mat.size().height;
sx = mat.size().width;
cmp_width = sx/4;
Mat m0 = mat(Rect(300, 300, sx-600, sy-600)).clone();
Mat sum = mat.clone();
sum = Scalar(0);
double t = clock();
int cnt = 0;
for (int i = 0; i < nframes - 5; i++) {
mat = GetFrame(cap);
m0 = mat(Rect(300, 300, sx-600, sy-600)).clone();
Point loc1 = match(m0, mat);
//cout << loc1;
int dx = loc1.x;
int dy = loc1.y;
char skip = 0;
if (abs(dx) > max_offset || abs(dy) > max_offset) {
skip = 1;
}
if (dx <= -max_offset) dx = -max_offset;
if (dy <= -max_offset) dy = -max_offset;
if (dx >= max_offset) dx = max_offset;
if (dy >= max_offset) dy = max_offset;
copyMakeBorder(mat, mat,
abs(dy),
abs(dy),
abs(dx),
abs(dx),
BORDER_CONSTANT, Scalar::all(0.0));
Mat mx = mat(Rect(abs(dx) + dx,
abs(dy) + dy,
sx, sy));
normalize(mx, mx, 0, 1, NORM_MINMAX, CV_32F);
cvWaitKey(1);
if (skip == 0) {
sum = sum + mx;
}
cnt++;
printf("%d\n", i);
if (cnt == 25) {
normalize(sum, sum, 0, 1, NORM_MINMAX, CV_32F);
//m0 = sum(Rect(300, 300, sx-600, sy-600)).clone();
imshow("m0", sum);
cnt = 0;
Mat tmp;
normalize(sum, tmp, 0, 255, NORM_MINMAX, CV_32F);
tmp.convertTo(tmp, CV_8U);
//.........这里部分代码省略.........
示例4: main
int main(int argc, char** argv)
{
Options o;
parse_command_line(argc, argv, o);
bool use_camera;
VideoCapture cap;
VideoWriter writer;
// Use filename if given, else use default camera
if( !o.infile.empty() )
{
cap.open(o.infile);
use_camera = false;
}
else
{
cap.open(0);
use_camera = true;
}
if( !cap.isOpened() )
{
cerr << "Failed to open capture device" << endl;
exit(2);
}
if( !o.outfile.empty() )
{
int fps = cap.get(CV_CAP_PROP_FPS);
int width = cap.get(CV_CAP_PROP_FRAME_WIDTH);
int height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
writer.open(o.outfile, CV_FOURCC('j', 'p', 'e', 'g'), fps, Size(width, height));
if( !writer.isOpened() )
{
cerr << "Could not open '" << o.outfile << "'" << endl;
exit(1);
}
use_camera = false;
}
// Open window and start capture
namedWindow(WINDOW, CV_WINDOW_FREERATIO | CV_GUI_NORMAL);
StateData d(o.num_particles, o.use_lbp);
State state = state_start;
Mat frame, gray;
lbp_init();
// Main loop
for(;;)
{
// Start timing the loop
// Capture frame
if( !d.paused)
{
cap >> frame;
if(frame.empty())
{
cerr << "Error reading frame" << endl;
break;
}
}
if( use_camera )
{
flip(frame, d.image, 1);
}
else
{
frame.copyTo(d.image);
}
// Set up all the image formats we'll need
if(d.use_lbp)
{
cvtColor(d.image, gray, CV_BGR2GRAY);
lbp_from_gray(gray, d.lbp);
}
else
{
if( d.lbp.empty() )
d.lbp = Mat::zeros(d.image.rows, d.image.cols, CV_8UC1);
}
// Handle keyboard input
char c = (char)waitKey(10);
if( c == 27 )
break;
switch(c)
{
case 'p':
d.paused = !d.paused;
break;
//.........这里部分代码省略.........
示例5: main
int main(int argc, char* argv[]){
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()){ // check if we succeeded
return -1;
}
VideoWriter VOut;
VOut.open("Detectors.avi", CV_FOURCC('M', 'P', 'E', 'G'), 30, Size(640, 480), 1);
Mat edges;
namedWindow("Screen",1);
//namedWindow("original", 1);
char setting = 'z'; // Canny default
Mat frame;
Mat gray;
Mat last_frame;
cout << "Help: \n" << "t -- threshold\n" << "c -- canny\n" << "x -- corners\n" << "d -- diff\n" << "Any other key -- lines\n" << endl;
for(;;){ // Loop through, getting new images from the camera.
Mat thresh_out;
Mat canny_out;
Mat corner_out;
Mat out;
//cout << "Setting " << setting + 'a' << endl;
cap >> frame; // get a new frame from camera
if (last_frame.empty()){
cvtColor(frame, last_frame, CV_BGR2GRAY);
}else{
last_frame = gray.clone(); // Which was the last gray frame, before I update it.
}
cvtColor(frame, gray, CV_BGR2GRAY);
if (setting == 't'){
// Threshold
threshold(gray, out, 100, 255, THRESH_BINARY); // Threshold: 100. White value: 255
}else if (setting == 'c'){
// Canny
GaussianBlur(gray, edges, Size(7,7), 1.5, 1.5);
Canny(edges, out, 5, 30, 3);
}else if (setting == 'x'){
// Corners
vector<Point2f> corners;
double qualityLevel = 0.04;
double minDistance = 30;
int blockSize = 5;
bool useHarrisDetector = false;
double k = 0.04;
int maxCorners = 100;
corner_out = gray.clone();
goodFeaturesToTrack( gray, corners, maxCorners, qualityLevel,
minDistance, Mat(), blockSize, useHarrisDetector, k );
int r = 4;
Size winSize = Size( 5, 5 );
Size zeroZone = Size( -1, -1 );
TermCriteria criteria = TermCriteria( CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 40, 0.001 );
/// Calculate the refined corner locations
cornerSubPix( gray, corners, winSize, zeroZone, criteria );
for( int i = 0; i < corners.size(); i++ )
{ circle( corner_out, corners[i], r, Scalar(255, 255, 255), -1, 8, 0 ); }
out = corner_out;
}else if (setting == 'd'){
// Diff
absdiff(gray, last_frame, out);
}
else{
// Lines
GaussianBlur(gray, edges, Size(7,7), 1.5, 1.5);
Canny(edges, canny_out, 7, 30, 3);
vector<Vec4i> lines;
HoughLinesP(canny_out, lines, 1, CV_PI/180, 50, 50, 10 );
for( size_t i = 0; i < lines.size(); i++ )
{
Vec4i l = lines[i];
line( edges, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
}
out = edges;
}
char key = waitKey(30);
if (key != 0 && key != -1){
//cout << "setting is " << key + 0<< endl;
setting = key;
key = 0;
}
imshow("Screen", out); // Show the image on the screen
VOut << out;
//imshow("original", gray);
//if(waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
//.........这里部分代码省略.........
示例6: main
int main (int argc, char **argv) {
cout << "Début\n";
// Capture de la source
ifstream sourceFile;
string source;
sourceFile.open(SOURCE_FILE);
if(sourceFile.is_open()) {
getline(sourceFile, source);
sourceFile.close();
}
else { source = "0"; }
VideoCapture video;
switch (source[0]) {
case 'v':
video.open(source.substr(2));
break;
default:
video.open(0);
break;
}
// Gestion des erreurs si la capture est vide
if (! video.isOpened()) {
cout << "Problème source\n";
return -1;
}
// Création des fenêtres
namedWindow("trace", CV_WINDOW_NORMAL);
namedWindow("panel", CV_WINDOW_NORMAL);
namedWindow("transformed", CV_WINDOW_NORMAL);
namedWindow("base", CV_WINDOW_NORMAL);
resizeWindow("base", 500, 375);
resizeWindow("transformed", 500, 375);
resizeWindow("panel", 500, 750);
resizeWindow("trace", 500, 375);
moveWindow("base", 0, 0);
moveWindow("transformed", 0, 375);
moveWindow("panel", 500, 0);
moveWindow("trace", 1000, 0);
// Déclaration des variables utilisées
int blur = BLUR,
tracer = 1,
norma = 1,
inverseRed = 1,
hue = HUE_BASE,
saturation = SATURATION_BASE,
hueCustom = HUE_TOLERANCE,
saturationCustom = SATURATION_TOLERANCE,
hueInverse = HUE_BASE_INVERSE,
hueToleranceInverse = HUE_TOLERANCE_INVERSE,
saturationInverse = SATURATION_BASE_INVERSE,
saturationToleranceInverse = SATURATION_TOLERANCE_INVERSE,
compteurErreurs = 0,
key = 0,
videoHeight = video.get(CV_CAP_PROP_FRAME_HEIGHT),
videoWidth = video.get(CV_CAP_PROP_FRAME_WIDTH),
rayon = max(videoWidth, videoHeight),
erodeSize = ERODE_SIZE,
dilateSize = DILATE_SIZE;
float angle = 0.0,
newAngle = 0.0,
distance = 0.0,
newDistance = 0.0,
Rg = 0.0,
Rd = 0.0;
bool continuer = true,
pause = false,
registerVideo = OUTPUT_VIDEO,
registerValeurs = OUTPUT_VALEURS;
Mat frameOrigine,
frameCouleurs,
frameHSV,
frameDetection,
frameDetectionInverseRed,
frameTrace(videoHeight, videoWidth, CV_8UC3),
frameContours,
frameOutput(videoHeight, videoWidth * 3, CV_8UC3),
element;
Point center((int)(videoWidth / 2) , (int)(videoHeight / 2));
vector<Mat> channels, outputFrames(3);
vector<vector<Point> > contours;
VideoWriter outputVideo;
outputVideo.open(
//.........这里部分代码省略.........
示例7: main
int main(int argc, char** argv)
{
if(argc >= 3)
{
VideoCapture inputVideo(argv[1]); // open the default camera
if(!inputVideo.isOpened()) // check if we succeeded
return -1;
// Initialize
VideoWriter outputVideo; // Open the output
const string source = argv[2]; // the source file name
const string NAME = source + ".mp4"; // Form the new name with container
int ex = inputVideo.get(CV_CAP_PROP_FOURCC); // Get Codec Type- Int form
std::cout << ex << "\n" << (int)inputVideo.get(CV_CAP_PROP_FOURCC) << "\n";
Size S = Size((int) inputVideo.get(CV_CAP_PROP_FRAME_WIDTH), //Acquire input size
(int) inputVideo.get(CV_CAP_PROP_FRAME_HEIGHT));
outputVideo.open(NAME, ex, inputVideo.get(CV_CAP_PROP_FPS), S, false);
char EXT[] = {(char)(ex & 0XFF) , (char)((ex & 0XFF00) >> 8),(char)((ex & 0XFF0000) >> 16),(char)((ex & 0XFF000000) >> 24), 0};
cout << "Input codec type: " << EXT << endl;
if (!outputVideo.isOpened())
{
cout << "Could not open the output video for write \n";
return -1;
}
// Basketball Color
int iLowH = 180;
int iHighH = 16;
int iLowS = 95;
int iHighS = 200;
int iLowV = 75;
int iHighV = 140;
// court Color
int courtLowH = 0;
int courtHighH = 20;
int courtLowS = 50;
int courtHighS = 150;
int courtLowV = 160;
int courtHighV = 255;
namedWindow("Result Window", 1);
//namedWindow("Court Window", 1);
// Mat declaration
Mat prev_frame, prev_gray, cur_frame, cur_gray;
Mat frame_blurred, frameHSV, frameGray;
// take the first frame
inputVideo >> prev_frame;
/* manual ball selection */
MouseParams mp;
prev_frame.copyTo( mp.ori );
prev_frame.copyTo( mp.img );
setMouseCallback("Result Window", BallSelectFunc, &mp );
int enterkey = 0;
while(enterkey != 32 && enterkey != 113)
{
enterkey = waitKey(30) & 0xFF;
imshow("Result Window", mp.img);
}
Rect lastBallBox;
Point lastBallCenter;
Point lastMotion;
/* Kalman Filter Initialization */
KalmanFilter KF(4, 2, 0);
float transMatrixData[16] = {1,0,1,0, 0,1,0,1, 0,0,1,0, 0,0,0,1};
KF.transitionMatrix = Mat(4, 4, CV_32F, transMatrixData);
Mat_<float> measurement(2,1);
measurement.setTo(Scalar(0));
KF.statePre.at<float>(0) = mp.pt.x;
KF.statePre.at<float>(1) = mp.pt.y;
KF.statePre.at<float>(2) = 0;
KF.statePre.at<float>(3) = 0;
setIdentity(KF.measurementMatrix);
setIdentity(KF.processNoiseCov, Scalar::all(1e-4));
setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1));
setIdentity(KF.errorCovPost, Scalar::all(.1));
int pre_status_7=0;
/* start tracking */
setMouseCallback("Result Window", CallBackFunc, &frameHSV);
for(int frame_num=1; frame_num < inputVideo.get(CAP_PROP_FRAME_COUNT); ++frame_num)
{
int cur_status_7=pre_status_7;
inputVideo >> cur_frame; // get a new frame
// Blur & convert frame to HSV color space
cv::GaussianBlur(prev_frame, frame_blurred, cv::Size(5, 5), 3.0, 3.0);
cvtColor(frame_blurred, frameHSV, COLOR_BGR2HSV);
//.........这里部分代码省略.........
示例8: main
int main( int argc, char **argv ) {
string fn, output_fn;
int box_size, horizon_crop;
int start_frame;
float scale_factor;
int end_frame;
int ransac_max_iters;
float ransac_good_ratio;
try
{
po::options_description desc("Options");
desc.add_options()
("help,h", "Print help messages")
("boxsize,b", po::value<int>(&box_size)->default_value(20), "The size of the box that you search for the best point to track in")
("hcrop,c", po::value<int>(&horizon_crop)->default_value(30), "Horizontal Border Crop, crops the border to reduce the black borders from stabilization being too noticeable.")
("manualframe,m", po::value<int>(&start_frame)->default_value(0), "Frame to do manual capturing on.")
("endframe,e", po::value<int>(&end_frame)->default_value(0), "Frame to stop stabilization at.")
("scalefactor,s", po::value<float>(&scale_factor)->default_value(0.25), "Scaling Factor for manual marking.")
("ransac_max_iters,i", po::value<int>(&ransac_max_iters)->default_value(500), "Maximum number of iterations for RANSAC.")
("ransac_good_ratio,g", po::value<float>(&ransac_good_ratio)->default_value(0.9), "Inlier Ratio used for RANSAC.")
//A higher inlier ratio will force model to only estimate the affine transform using that percentage of inlier points.
("footage,f", po::value<string>(&fn)->required(), "footage file")
("output,o", po::value<string>(&output_fn)->default_value("output.avi"), "output file");
po::positional_options_description positionalOptions;
positionalOptions.add("footage", 1);
po::variables_map vm;
// Parse command line arguments
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(positionalOptions).run(), vm);
if ( vm.count( "help" ) )
{
cout << "This is the stabilization software for the gopro camera. " << endl << endl;
cout << "Usage: " << argv[0] << " [options] <footage>" << endl << endl << desc << endl;
return 0;
}
po::notify(vm);
}
catch ( po::error& e )
{
cerr << "ERROR: " << e.what() << endl << endl;
cerr << desc << endl;
return 1;
}
if (end_frame > 0 && end_frame < start_frame)
{
throw invalid_argument( "selected end frame is before start frame");
}
VideoCapture capturefirst(fn);
VideoWriter writer;
writer.open(output_fn, CV_FOURCC('m','p','4','v'), capturefirst.get(CV_CAP_PROP_FPS), Size((int) capturefirst.get(CV_CAP_PROP_FRAME_WIDTH), (int) capturefirst.get(CV_CAP_PROP_FRAME_HEIGHT)), true);
Mat curr, curr_grey;
Mat first, first_grey, first_grey_disp;
int max_frames = capturefirst.get(CV_CAP_PROP_FRAME_COUNT);
printf("Number of frames in video: %d\n",max_frames);
if ( start_frame > max_frames )
{
throw invalid_argument( "start_frame larger than max frames" );
}
if (end_frame == 0)
{
end_frame = max_frames;
}
capturefirst.set(CV_CAP_PROP_POS_FRAMES, start_frame);
do
{
capturefirst >> first;
}
while ( first.data == NULL );
cvtColor(first, first_grey, COLOR_BGR2GRAY);
resize(first_grey, first_grey_disp, Size(), scale_factor, scale_factor);
vector <Point2f> first_corners, first_corners2;
struct UserData ud(first_grey_disp, &first_corners, box_size, scale_factor);
namedWindow("first", CV_WINDOW_AUTOSIZE);
setMouseCallback("first", select_features_callback, &ud);
imshow("first", first_grey_disp);
waitKey(0);
cout << first_corners.size() << " corners detected." << endl;
destroyAllWindows();
writer << first;
Mat last_T;
capturefirst.release();
VideoCapture capture(fn);
cout << "Analyzing" << endl;
int k = 0;
while ( k < max_frames - 1 )
{
capture >> curr;
if ( curr.data == NULL )
{
//.........这里部分代码省略.........
示例9: run
void visionNode::run(){
//run initial calibration. If that fails, this node will shut down.
if(!calibrate()) ros::shutdown();
VideoWriter outputVideo;
Size S = cv::Size(cam->get_img_width(),cam->get_img_height());
outputVideo.open("/home/lcv/output.avi" , CV_FOURCC('M','P','2','V'), 30, S, true);
//main loop
while(ros::ok()){
//if calibration was manualy invoked by call on the service
if(invokeCalibration) {
invokeCalibration = false;
calibrate();
}
//grab frame from camera
cam->get_frame(&camFrame);
//correct the lens distortion
rectifier->rectify(camFrame, rectifiedCamFrame);
//create a duplicate grayscale frame
cv::Mat gray;
cv::cvtColor(rectifiedCamFrame, gray, CV_BGR2GRAY);
//draw the calibration points
for(point2f::point2fvector::iterator it=markers.begin(); it!=markers.end(); ++it)
cv::circle(rectifiedCamFrame, cv::Point(cv::saturate_cast<int>(it->x), cv::saturate_cast<int>(it->y)), 1, cv::Scalar(0, 0, 255), 2);
//detect crates
std::vector<Crate> crates;
qrDetector->detectCrates(gray, crates);
//transform crate coordinates
for(std::vector<Crate>::iterator it=crates.begin(); it!=crates.end(); ++it)
{
it->draw(rectifiedCamFrame);
std::vector<cv::Point2f> points;
for(int n = 0; n <3; n++){
point2f result = cordTransformer->to_rc(point2f(it->getPoints()[n].x, it->getPoints()[n].y));
points.push_back(cv::Point2f(result.x, result.y));
}
it->setPoints(points);
}
//inform the crate tracker about the seen crates
std::vector<CrateEvent> events = crateTracker->update(crates);
//publish events
for(std::vector<CrateEvent>::iterator it = events.begin(); it != events.end(); ++it)
{
vision::CrateEventMsg msg;
msg.event = it->type;
msg.crate.name = it->name;
msg.crate.x = it->x;
msg.crate.y = it->y;
msg.crate.angle = it->angle;
ROS_INFO(it->toString().c_str());
crateEventPublisher.publish(msg);
}
//update GUI
outputVideo.write(rectifiedCamFrame);
imshow("image",rectifiedCamFrame);
waitKey(1000/30);
//let ROS do it's magical things
ros::spinOnce();
}
}
示例10: main
int main(int argc, char **argv)
{
if (argc < 2) {
cout << "./VideoStab [video.avi]" << endl;
return 0;
}
// For further analysis
ofstream out_transform("prev_to_cur_transformation.txt");
ofstream out_trajectory("trajectory.txt");
ofstream out_smoothed_trajectory("smoothed_trajectory.txt");
ofstream out_new_transform("new_prev_to_cur_transformation.txt");
VideoCapture cap(argv[1]);
assert(cap.isOpened());
Mat cur, cur_grey;
Mat prev, prev_grey;
cap >> prev;//get the first frame.ch
cvtColor(prev, prev_grey, COLOR_BGR2GRAY);
// Step 1 - Get previous to current frame transformation (dx, dy, da) for all frames
vector <TransformParam> prev_to_cur_transform; // previous to current
// Accumulated frame to frame transform
double a = 0;
double x = 0;
double y = 0;
// Step 2 - Accumulate the transformations to get the image trajectory
vector <Trajectory> trajectory; // trajectory at all frames
//
// Step 3 - Smooth out the trajectory using an averaging window
vector <Trajectory> smoothed_trajectory; // trajectory at all frames
Trajectory X;//posteriori state estimate
Trajectory X_;//priori estimate
Trajectory P;// posteriori estimate error covariance
Trajectory P_;// priori estimate error covariance
Trajectory K;//gain
Trajectory z;//actual measurement
double pstd = 4e-3;//can be changed
double cstd = 0.25;//can be changed
Trajectory Q(pstd, pstd, pstd);// process noise covariance
Trajectory R(cstd, cstd, cstd);// measurement noise covariance
// Step 4 - Generate new set of previous to current transform, such that the trajectory ends up being the same as the smoothed trajectory
vector <TransformParam> new_prev_to_cur_transform;
//
// Step 5 - Apply the new transformation to the video
//cap.set(CV_CAP_PROP_POS_FRAMES, 0);
Mat T(2, 3, CV_64F);
int vert_border = HORIZONTAL_BORDER_CROP * prev.rows / prev.cols; // get the aspect ratio correct
VideoWriter outputVideo;
outputVideo.open("compare.avi", CV_FOURCC('X', 'V', 'I', 'D'), 24, cvSize(cur.rows, cur.cols * 2 + 10), true);
//
int k = 1;
int max_frames = cap.get(CV_CAP_PROP_FRAME_COUNT);
Mat last_T;
Mat prev_grey_, cur_grey_;
while (true) {
cap >> cur;
if (cur.data == NULL) {
break;
}
cvtColor(cur, cur_grey, COLOR_BGR2GRAY);
// vector from prev to cur
vector <Point2f> prev_corner, cur_corner;
vector <Point2f> prev_corner2, cur_corner2;
vector <uchar> status;
vector <float> err;
goodFeaturesToTrack(prev_grey, prev_corner, 200, 0.01, 30);
calcOpticalFlowPyrLK(prev_grey, cur_grey, prev_corner, cur_corner, status, err);
// weed out bad matches
for (size_t i = 0; i < status.size(); i++) {
if (status[i]) {
prev_corner2.push_back(prev_corner[i]);
cur_corner2.push_back(cur_corner[i]);
}
}
// translation + rotation only
Mat T = estimateRigidTransform(prev_corner2, cur_corner2, false); // false = rigid transform, no scaling/shearing
// in rare cases no transform is found. We'll just use the last known good transform.
if (T.data == NULL) {
last_T.copyTo(T);
}
T.copyTo(last_T);
// decompose T
double dx = T.at<double>(0, 2);
double dy = T.at<double>(1, 2);
double da = atan2(T.at<double>(1, 0), T.at<double>(0, 0));
//
//prev_to_cur_transform.push_back(TransformParam(dx, dy, da));
//.........这里部分代码省略.........
示例11: main
int main(int, char**)
{
string filename = "HorizontalView.3gp";
VideoCapture cap(filename); // open the file.
if(!cap.isOpened()) // check if we succeeded
return -1;
cap.set(CV_CAP_PROP_POS_FRAMES, 0);
const string fileOutName = "HorizontalViewOut2.mp4";
Size s = Size((int)cap.get(CV_CAP_PROP_FRAME_WIDTH), (int)cap.get(CV_CAP_PROP_FRAME_HEIGHT));
VideoWriter outputVideo;
outputVideo.open(fileOutName,CV_FOURCC('M', 'J', 'P', 'G'),30,s,true);
if(!outputVideo.isOpened())
return -1;
//Initialize variables.
Mat hsv,blur,thresholded, mser, rthresh;
//Create a MSER feature detector
Ptr<FeatureDetector> defaultDetector;
Ptr<FeatureDetector> blobDetector;
defaultDetector = FeatureDetector::create("MSER");
blobDetector = FeatureDetector::create("SimpleBlob");
int min_area = 700;
int rmin,gmin,bmin,rmax,gmax,bmax = 0;
int huemin,satmin,valmin,huemin2,satmin2,valmin2 = 0;
int huemax,satmax,valmax,huemax2,satmax2,valmax2 = 256;
valmin = 230;
int colr = 0;
namedWindow("hsv",1);
namedWindow("normal",2);
namedWindow("blur",3);
//namedWindow("thresh",4);
createTrackbar("huemin", "blur", &huemin, 256);
createTrackbar("satmin", "blur", &satmin, 256);
createTrackbar("valmin", "blur", &valmin, 256);
createTrackbar("huemax", "blur", &huemax, 256);
createTrackbar("satmax", "blur", &satmax, 256);
createTrackbar("valmax", "blur", &valmax, 256);
/*createTrackbar("rmin", "thresh", &rmin, 256);
createTrackbar("gmin", "thresh", &gmin, 256);
createTrackbar("bmin", "thresh", &bmin, 256);
createTrackbar("rmax", "thresh", &rmax, 256);
createTrackbar("gmax", "thresh", &gmax, 256);
createTrackbar("bmax", "thresh", &bmax, 256);*/
huemin = 123;
satmin = 32;
valmin = 218;
huemax = 188;
satmax = 256;
valmax = 256;
huemin2 = 60;
satmin2 = 30;
valmin2 = 134;
huemax2 = 89;
satmax2 = 150;
valmax2 = 256;
int frame_count = 0;
for(;;) {
defaultDetector->set("minArea",min_area);
//Read in a frame from video data.
Mat frame,frameBot,frameTop;
cap >> frame;
//frameTop = frame.rowRange(Range(0,(int)(frame.rows/2));
frameBot = frame.rowRange(Range((int)(frame.rows/2),frame.rows));
//Convert to HSV color space.
cvtColor(frameBot, hsv, CV_BGR2HSV);
//Threshold the image to only look for bright red + green spots.
inRange(hsv, Scalar(huemin,satmin,valmin), Scalar(huemax,satmax,valmax), thresholded);
inRange(hsv, Scalar(huemin2,satmin2,valmin2), Scalar(huemax2,satmax2,valmax2), rthresh);
bitwise_or(thresholded,rthresh,thresholded);
//Blur the image to make detections more robust.
GaussianBlur(thresholded, blur, Size(9,9), 3, 3);
//Apply the MSER detector to the blurred image.
vector<KeyPoint> keypoints;
defaultDetector->detect(blur,keypoints);
//Display the maximal keypoints over the original image.
for(size_t i = 0; i < keypoints.size(); i++){
if(!supress(keypoints,keypoints[i])){
Point center = keypoints[i].pt;
int radius = cvRound(keypoints[i].size/2);
Point topLeft = center;
topLeft.x -= radius;
if(topLeft.x < 0)
topLeft.x = 0;
topLeft.y -= radius;
if(topLeft.y < 0)
topLeft.y = 0;
Point botRight = center;
botRight.y += radius;
if(botRight.y >= frameBot.rows)
botRight.y = frameBot.rows-1;
botRight.x += radius;
if(botRight.x >= frameBot.cols)
botRight.x = frameBot.cols-1;
int width = botRight.x - topLeft.x;
int height = botRight.y - topLeft.y;
//Bounding box of a maximal detection.
Rect r(topLeft.x,topLeft.y,width,height);
//Draw the rectangle to the output
rectangle(frameBot,r,Scalar(256,0,0),1,CV_AA);
char c[50];
//.........这里部分代码省略.........
示例12: main
//.........这里部分代码省略.........
#if MEDIAN_BGS
bgs.AddMedianSample(pyr[iLevels]);
#else
bgs.AddMeanSample(pyr[iLevels]);
#endif
bgs.Show(bgs.outP, WAN, WBN, WLN );
// load frame
cont += step;
if (cont >= lastBGF) break;
sprintf(fileName, "%s%d.jpg", baseName, cont);
frame = imread(fileName, 1);
if (!frame.data) {
printf("Could not open file %s.\n", fileName);
return (-1);
}
buildPyramid(frame, pyr, iLevels);
imshow(WIN, pyr[iLevels]);
if (waitKey(30) >= 0)
continua = false;
}
#if MEDIAN_BGS
bgs.ComputeMedianBG();
#else
bgs.ComputeMeanBG();
#endif
bgs.Show(bgs.luvP, WAN, WBN, WLN );
imshow(WIN, bgs.bgBGRImg);
printf("Press q to quit or c to continue.\n");
char k = waitKey();
if (k == 'q' || k == 'Q')
return 0;
///////////////////////////////////////////////////////////////////////
////
//// Process the video
////
///////////////////////////////////////////////////////////////////////
// loop parameters
Mat binImg;
binImg = Mat (pyr[iLevels].size(), CV_8UC1);
namedWindow(WBG, CV_WINDOW_AUTOSIZE );
int notEnd = 1;
char keyPressed;
/// Video
VideoWriter vw;
vw.open("movie.mpeg", CV_FOURCC('P','I','M','1'), 25, pyr[iLevels].size());
continua = true;
for (cont = firstF; continua && cont<lastF; cont+= stepF) {
// load image
sprintf(fileName, "%s%d.jpg", baseName, cont);
frame = imread(fileName, 1);
if (!frame.data) {
printf("Could not open file %s.\n", fileName);
return (-1);
}
buildPyramid(frame, pyr, iLevels);
imshow(WIN, pyr[iLevels]);
#if MEDIAN_BGS
bgs.BGSeg(pyr[iLevels], binImg);
imshow(WBG, binImg);
imshow(WAN, bgs.hiImg);
imshow(WBN, bgs.loImg);
#else
bgs.Subtract(pyr[iLevels], binImg);
imshow(WBG, binImg);
#endif
Mat vid;
cvtColor(binImg, vid, CV_GRAY2BGR);
sprintf(fileName, "out/%d.jpg", cont);
imwrite(fileName, vid);
vw << vid;
keyPressed = waitKey(10);
switch (keyPressed) {
case 'q':
case 'Q':
notEnd = 0;
break;
default:
break;
}
}
return 0;
}
示例13: main
void main(int argc, char *argv[])
{
Mat emptyFrame = Mat::zeros(Camera::reso_height, Camera::reso_width, CV_8UC3);
Thesis::FastTracking fastTrack(20); //used to be 50, why? i dno
Thesis::KalmanFilter kalman;
kalman.initialise(CoordinateReal(0, 0, 0));
kalman.openFile();
// the two stereoscope images
Camera one(0,-125,0,0,0,90);
Camera two(2, 125,0,0,0,90);
Camera three;
// list of cameras and cameraLocs
std::vector<Camera> cameraList;
std::vector<CoordinateReal> locList;
VideoWriter writeOne ;
VideoWriter writeTwo;
VideoWriter writeThree;
VideoCapture capOne;
VideoCapture capTwo;
VideoCapture capThree;
Thesis::Stats stat;
cv::Point2d horizontalOne(0,Camera::reso_height/2);
cv::Point2d horizontalTwo(Camera::reso_width, Camera::reso_height/2);
cv::Point2d verticalOne(Camera::reso_width / 2, 0);
cv::Point2d verticalTwo(Camera::reso_width / 2, Camera::reso_height);
ofstream framesFile_;
framesFile_.open("../../../../ThesisImages/fps_ABSDIFF.txt");
double framesPerSecond = 1 / 10.0;
//open the recorders
FeatureExtraction surf(5000);
Stereoscope stereo;
Util util;
bool once = false;
bool foundInBoth = false;
bool foundInMono = false;
std::vector<cv::Point2f> leftRect(4);
cv::Rect leftRealRect;
cv::Rect rightRealRect;
std::vector<cv::Point2f> rightRect(4);
cv::Mat frameLeft;
cv::Mat frameRight;
cv::Mat frameThree;
cv::Mat prevFrameLeft;
cv::Mat prevFrameRight;
cv::Mat prevFrameThree;
// check if you going to run simulation or not or record
cout << " run simulation: 's' or normal: 'n' or record 'o' or threeCameras 'c' " << endl;
imshow("main", emptyFrame);
char command = waitKey(0);
string left = "../../../../ThesisImages/leftTen.avi";
string right = "../../../../ThesisImages/rightTen.avi";
string mid = "../../../../ThesisImages/midTen.avi";
commands(command);
emptyFrame = Mat::ones(10, 10, CV_64F);
imshow("main", emptyFrame);
command = waitKey(0);
camCount(command);
// checkt the cam count
if (multiCams){
//load in all the cameras
three = Camera(3, 175, -50, 585, 7.1, 97);//Camera(3, 200, -60, 480, 7,111);
}
//==========hsv values=======================
cv::Mat hsvFrame;
cv::Mat threshold;
int iLowH = 155;
int iHighH = 179;
int iLowS = 75;
int iHighS = 255;
int iLowV = 0;
int iHighV = 255;
//=================================
double elapsedTime = 0;
double waitDelta = 0;
if (record){
writeOne.open("../../../../ThesisImages/leftTen.avi", 0, 10, cv::Size(864, 480), true);
writeTwo.open("../../../../ThesisImages/rightTen.avi", 0, 10, cv::Size(864, 480), true);
writeThree.open("../../../../ThesisImages/midTen.avi", 0, 10, cv::Size(864, 480), true);
}else if (simulation){
capOne.open(left);
capTwo.open(right);
capThree.open(mid);
assert(capOne.isOpened() && capTwo.isOpened());
}
if (hsv){
//Create trackbars in "Control" window
cvCreateTrackbar("LowH", "main", &iLowH, 179); //Hue (0 - 179)
cvCreateTrackbar("HighH", "main", &iHighH, 179);
cvCreateTrackbar("LowS", "main", &iLowS, 255); //Saturation (0 - 255)
cvCreateTrackbar("HighS", "main", &iHighS, 255);
cvCreateTrackbar("LowV", "main", &iLowV, 255); //Value (0 - 255)
cvCreateTrackbar("HighV", "main", &iHighV, 255);
}
//.........这里部分代码省略.........
示例14: main
int main(int argc, char *argv[])
{
Temporal_Filter filter;
Mat dst;
// help();
//if (argc != 4)
{
// cout << "Not enough parameters" << endl;
// return -1;
}
const string source = argv[1]; // the source file name
const bool askOutputType = false; // If false it will use the inputs codec type
VideoCapture inputVideo(source); // Open input
if (!inputVideo.isOpened())
{
cout << "Could not open the input video: " << source << endl;
return -1;
}
string::size_type pAt = source.find_last_of('.'); // Find extension point
const string NAME = argv[2]; // Form the new name with container
int ex = static_cast<int>(inputVideo.get(CV_CAP_PROP_FOURCC)); // Get Codec Type- Int form
// Transform from int to char via Bitwise operators
char EXT[] = {(char)(ex & 0XFF) , (char)((ex & 0XFF00) >> 8),(char)((ex & 0XFF0000) >> 16),(char)((ex & 0XFF000000) >> 24), 0};
Size S = Size(320,240); // Acquire input size
//(int) inputVideo.get(CV_CAP_PROP_FRAME_HEIGHT));
VideoWriter outputVideo; // Open the output
if (askOutputType)
outputVideo.open(NAME, ex=-1, inputVideo.get(CV_CAP_PROP_FPS), S, true);
else
outputVideo.open(NAME, ex, inputVideo.get(CV_CAP_PROP_FPS), S, true);
if (!outputVideo.isOpened())
{
cout << "Could not open the output video for write: " << source << endl;
return -1;
}
cout << "Input frame resolution: Width=" << S.width << " Height=" << S.height
<< " of nr#: " << inputVideo.get(CV_CAP_PROP_FRAME_COUNT) << endl;
cout << "Input codec type: " << EXT << endl;
Mat src, res;
vector<Mat> spl;
Mat a;
a.create(240,320,CV_8UC(3));
for(;;) //Show the image captured in the window and repeat
{
inputVideo >> src; // read
if (src.empty()) break; // check if at end
cvtColor(src,src,CV_BGR2GRAY);
resize(src,a, a.size(), 0, 0, INTER_NEAREST);
imshow("input",a);
dst=filter.temporal_filter(a);
cvtColor(dst,res,CV_GRAY2BGR);
//outputVideo.write(res); //save or
outputVideo << res;
imshow("filtered",res);
cv::waitKey(1);
}
cout << "Finished writing" << endl;
return 0;
}
示例15: split_img
void split_img( int split_num, int x, int y, int num_x, int num_y, int time_split, string fn, string out_dir, int overlap) {
mtx.lock();
cout << "worker " << x << "-" << y << "-" << split_num << " running." << endl;
mtx.unlock();
VideoCapture capture(fn);
int max_frames = capture.get(CV_CAP_PROP_FRAME_COUNT);
int rect_width = (int) capture.get(CV_CAP_PROP_FRAME_WIDTH)/num_x;
int rect_height = (int) capture.get(CV_CAP_PROP_FRAME_HEIGHT)/num_y;
int start_frame = split_num * (max_frames / time_split);
capture.set(CV_CAP_PROP_POS_FRAMES, start_frame);
int this_x = x*rect_width;
int this_y = y*rect_height;
int this_width = rect_width;
int this_height = rect_height;
//Determine whether to add overlap to the quadrant.
if (x > 0){
this_x -= overlap;
this_width += overlap;
}
if (y > 0) {
this_y -= overlap;
this_height += overlap;
}
if (x != num_x-1) {
this_width += overlap;
}
if (y != num_y-1) {
this_height += overlap;
}
Size sz = Size(this_width, this_height);
stringstream out_key;
out_key << y << "-" << x << "-" << split_num;
VideoWriter writer;
string out_fn = out_dir + "/" + out_key.str() + ".avi";
writer.open(out_fn, CV_FOURCC('m','p','4','v'), capture.get(CV_CAP_PROP_FPS), sz, true);
//writer.open(out_fn, CV_FOURCC('m','p','4','v'), 29.97, sz, true);
Mat src;
Rect rect = Rect( this_x, this_y, this_width, this_height );
int k = 0;
while ( k < (max_frames / time_split)-1 )
{
capture >> src;
if ( src.data == NULL )
break;
writer << Mat(src, rect);
int percent = int(100 * ((float)k/(max_frames/time_split)));
if ( percent % 5 == 0 )
{
mtx.lock();
cout << "worker " << x << "-" << y << "-" << split_num << ": " << percent << "%" << endl;
mtx.unlock();
}
k++;
}
}