OpenCV Examples 1 Colorado School of Mines

advertisement
OpenCV
Examples
Colorado School of Mines
Department of Electrical Engineering and Computer Science
1
Example
• Copy the whole directory containing your tutorial
project to a new directory.
• Edit the “main.cpp” file and replace it with the code
on the next page.
– The program captures images from a USB web camera, and
applies a simple intensity scaling and offset.
– If you don’t have a USB camera you can read images from
the test video instead.
• When you copy-and-paste you may lose the
formatting and indentation. To fix it:
– Go to Edit->Advanced and choose “Format
Document”
Colorado School of Mines
Department of Electrical Engineering and Computer Science
2
Example - continued
#include <iostream>
#include <opencv2/opencv.hpp>
int main(int argc, char* argv[])
{
printf("Hit ESC key to quit ...\n");
Code – page
1 of 2
cv::VideoCapture cap(0);
// open the default camera
/* If you don't have a camera, you can read from a video file
instead using the following line. The video file should be
put into the same directory as your source code file. */
//cv::VideoCapture cap("testvideo.wmv");
if (!cap.isOpened()) {
// check if we succeeded
printf("error - can't open the input source\n");
system("PAUSE");
return EXIT_FAILURE;
}
// Let's just see what the image size is from this camera or file.
double WIDTH = cap.get(CV_CAP_PROP_FRAME_WIDTH);
double HEIGHT = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
printf("Image width=%f, height=%f\n", WIDTH, HEIGHT);
// Allocate images
cv::Mat imgInput, imgOutput;
Colorado School of Mines
Department of Electrical Engineering and Computer Science
3
Example - continued
// Run an infinite loop until user hits the ESC key
while (1)
{
cap >> imgInput;
// get image from camera
if (!imgInput.data)
{
printf("image is empty\n");
system("PAUSE");
break;
}
Code – page
2 of 2
// Convert to grayscale.
cv::cvtColor(imgInput, imgInput, cv::COLOR_BGR2GRAY);
// Scale and offset the image values.
float alpha = 2.0;
float beta = -128;
imgOutput = alpha * imgInput + beta;
// Show the images
cv::imshow("Input Image", imgInput);
cv::imshow("Output Image", imgOutput);
// wait for x ms (0 means wait until a keypress)
if (cv::waitKey(1) == 27)
break;
// ESC is ascii 27
}
return EXIT_SUCCESS;
}
Colorado School of Mines
Department of Electrical Engineering and Computer Science
4
Download