Git Product home page Git Product logo

learning-opencv-3_examples's Introduction

Learning OpenCV 3

INTRO

This is the example code that accompanies Learning OpenCV 3 by Adrian Kaehler and Gary Bradski (9781491937990).

Click the Download Zip button to the right to download example code.

Visit the catalog page here.

See an error? Report it here, or simply fork and send us a pull request

NOTES

For default suggestions of how the run the code, it assumes you put your build directory under Learning-OpenCV-3_examples directory.

Thus, from the Learning-OpenCV-3_examples directory:

  mkdir build
  cd build
  cmake ..
  make -j

Docker

For your interest, included here is an Ubuntu Docker file that

  • Shares a directory with the host operating system
  • Shares the first camera between both systems
  • Loads Ubuntu 16.04
  • Loads all dependencies for OpenCV 3.2 and opencv_contrib
  • Loads and builds OpenCV 3.2 and opencv_contrib into a build directory
    • executable files end up in opencv-3.2.0/build/bin
  • Next, it git clones the code (and Docker file) for Learning OpenCV 3 and builds it
    • executable files end up in Learning_OpenCV-3_examples/build
  • To get to the top level directory, just type: cd

CONTENTS:

SPECIAL FILES:

  • README.md -- this readme file
  • Dockerfile -- complete self contained opencv environment using Ubuntu 16-04
  • CMakeLists.txt -- how to buld everything here

EXERCISES:

  • Exercises at end of Chapter 5
  • Exercises at end of Chapter 7
  • Exercises_8_1.cpp Exercises at end of Chapter 8
  • Exercises_9_1-2-10-11-12-15-16.cpp Exercises at end of Chapter 8
  • Exercises_9_4.cpp Exercises at end of Chapter 9
  • Exercises_9_5.cpp Exercises at end of Chapter 9
  • Exercises at end of Chapter 11
  • Exercises_13_1-2-11.cpp Exercises for Chapter 13
  • Exercises_13_9.cpp

EXAMPLES:

  • Example 2-1. A simple OpenCV program that loads an image from disk and displays it
  • Example 2-2. Same as Example 2-1 but employing the “using namespace” directive
  • Example 2-3. A simple OpenCV program for playing a video file from disk
  • Example 2-4. Adding a trackbar slider to the basic viewer window for moving around
  • Example 2-5. Loading and then smoothing an image before it is displayed on the screen
  • Example 2-6. Using cv::pyrDown() to create a new image that is half the width and
  • Example 2-7. The Canny edge detector writes its output to a single-channel (grayscale) image
  • Example 2-8. Combining the pyramid down operator (twice) and the Canny
  • Example 2-9. Getting and setting pixels in Example 2-8
  • Example 2-10. The same object can load videos from a camera or a file
  • Example 2-11. A complete program to read in a color video and write out the log-polar-
  • Example 4-1. Summation of a multidimensional array, done plane by plane
  • Example 4-2. Summation of two arrays using the N-ary operator
  • Example 4-3. Printing all of the nonzero elements of a sparse array
  • Example 4-4. A better way to print a matrix
  • Example 5-1. Complete program to alpha-blend the ROI starting at (0,0) in src2 with the ROI starting at (x,y) in src1
  • Example 7-1. Using the default random number generator to generate a pair of integers
  • Example 8-1. Unpacking a four-character code to identify a video codec
  • Example 8-2. Using cv::FileStorage to create a .yml data file
  • Example 8-3. Using cv::FileStorage to read a .yml file
  • Example 9-1. Creating a window and displaying an image in that window
  • Example 9-2. Toy program for using a mouse to draw boxes on the screen
  • Example 9-3. Using a trackbar to create a “switch” tha t the user can turn on and off;
  • Example 9-4. Slightly modified code from the OpenCV documentation that draws a
  • Example 9-5. An example program ch4_qt.cpp, which takes a single argument
  • Example 9-6. The QMoviePlayer object header file QMoviePlayer.hpp
  • Example 9-7. The QMoviePlayer object source file: QMoviePlayer.cpp
  • Example 9-8. An example program which takes a single argument
  • Example 9-9. The WxMoviePlayer object header file WxMoviePlayer.hpp
  • Example 9-10. The WxMoviePlayer object source file WxMoviePlayer.cpp
  • Example 9-11. An example header file for our custom View class
  • Example 10-1. Using cv::threshold() to sum three channels of an image
  • Example 10-2. Alternative method to combine and threshold image planes
  • Example 10-3. Threshold versus adaptive threshold
  • Example 11-1. An affine transformation.
  • Example 11-2. Code for perspective transformation
  • Example 11-3. Log-polar transform example
  • Example 12-1. Using cv::dft() and cv::idft() to accelerate the computation of
  • Example 12-2. Using cv::HoughCircles() to return a sequence of circles found in a
  • EXTRA Example 12-3. Using GrabCut for background removal
  • EXTRA Example 12-4. Using GrabCut for background removal
  • Example 13-1. Histogram computation and display
  • Example 13-2. Creating signatures from histograms for EMD; note that this code is the
  • Example 13-3. Template matching
  • Example 14-1. Finding contours based on a trackbar’s location; the contours are
  • Example 14-2. Finding and drawing contours on an input image
  • Example 14-3. Drawing labeled connected components
  • Example 14-4. Using the shape context distance extractor
  • Example 15-1. Reading out the RGB values of all pixels in one row of a video and
  • Example 15-2. Learning a background model to identify foreground pixels
  • Example 15-3. Computing the on and off-diagonal elements of a variance/covariance model
  • Example 15-4. Codebook algorithm implementation
  • Example 15-5. Cleanup using connected components
  • EXTRA Example 15-6, using OpenCV's background subtractor class. Modified by Gary Bradski, 6/4/2017
  • Example 16-1. Pyramid L-K optical flow
  • EXTRA Example 16-2. 2D Feature detectors and 2D Extra Features framework
  • Example 17-1. Kalman filter example code
  • Example 17-2. Farneback optical flow example code
  • Example 18-1. Reading a chessboard’s width and height, reading them and calibrating
  • EXTRA Example 18-1. From disk. Reading a chessboard’s width and height, reading them and calibrating
  • Example 19-1. Bird’s - eye view
  • Example 19-2. Computing the fundamental matrix using RANSAC
  • Example 19-3. Stereo calibration, rectification, and correspondence
  • Example 19-4. Two-dimensional line fitting
  • Example 20-01. Using K-means
  • Example 20-02. Using the Mahalanobis distance for classification
  • Example 21-1. Creating and training a decision tree
  • Example 22-1. Detecting and drawing faces

IMAGES:

  • box.png
  • box_in_scene.png
  • checkerboard9x6.png
  • example_16-01-imgA.png
  • example_16-01-imgB.png
  • faces.png
  • BlueCup.jpg
  • HandIndoorColor.jpg
  • HandOutdoorColor.jpg
  • HandOutdoorSunColor.jpg
  • adrian.jpg
  • faceScene.jpg
  • faceTemplate.jpg
  • fruits.jpg
  • stuff.jpg

MOVIES:

  • test.avi
  • tree.avi

CLASSIFIERS:

  • haarcascade_frontalcatface.xml #Cat faces!
  • haarcascade_frontalcatface_extended.xml
  • haarcascade_frontalface_alt.xml

DIRECTORIES:

  • birdseye -- where the images are of checkerboards on the floor
  • build -- you will make and build things in this directory
  • calibration -- checkerboard images to calibrate on
  • muchroom -- machine learning database
  • shape_sample -- silhoette shapes to recognize
  • stereoData -- left, right image pairs of checkboards to calibrate and view on

LINKS:

Click the Download Zip button to the right to download example code.

Visit the catalog page here.

See an error? Report it here, or simply fork and send us a pull request

learning-opencv-3_examples's People

Contributors

adrian-kaehler avatar aseronick avatar dolotovevgeniy avatar garybradski avatar jsxyhelu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

learning-opencv-3_examples's Issues

Source Code

Please,
some feedback aboutwhen the example's code is planned to be available?

Random forest gives incorrect prediction.

I have trained a random forest model in opencv. Following is my code

cv::Ptr<cv::ml::RTrees> dtree = cv::ml::RTrees::create();
dtree->setMaxDepth(18);

int numTrees = 50;
dtree->setTermCriteria(TermCriteria(TermCriteria::COUNT, numTrees, 1e-6));

cv::Ptr<cv::ml::TrainData> train_data_set = cv::ml::TrainData::loadFromCSV(
    "Train_Data.csv",  1, 0, 1);

dtree->train(train_data_set);
dtree->save("E:/RFModel.xml");

Train_Data.csv contains 28 columns (features/attributes) in integer format. After training I saved the model as RFModel.xml.

Now, I want to perform prediction. I have my features saved in vector data structure.

Following is my code for performing prediction:

// I will extract my attribute values and push in `mRFParams`
vector<int> mRFParams;

/*
Feature extraction and push in mRFParams vector happens here
*/

// Load the model
cv::Ptr<cv::ml::RTrees> model = cv::ml::RTrees::load("E:/RFModel.xml");

auto numParams = mRFParams.size();
cv::Mat RFParamMat(1, numParams, CV_32FC1);
memcpy(RFParamMat.data, &mRFParams, numParams);
cv::Mat predict_labels;
auto prediction = model->predict(RFParamMat);
std::cout<<"Prediction : ", prediction);

This gives me totally incorrect output. Am I correctly calling prediction? Or am I doing something totally wrong?
Thanks in advance

there is some questions about the example of connectedComponentsWithStats

in page 419(pdf)
1、when i use

 int i, nccomps = cv::connectedComponentsWithStats (
    img_edge, labels,
    stats, cv::noArray()
  );

OpenCV gvies me an ERROR,
I had change my code to

cv::Mat  centroids;
int nccomps = cv::connectedComponentsWithStats (
		img_edge, labels,
		stats, centroids
		);

2、i think

for( i = 1; i <= nccomps; i++ ) {

    colors[i] = Vec3b(rand()%256, rand()%256, rand()%256);

    if( stats.at<int>(i-1, cv::CC_STAT_AREA) < 100 )

      colors[i] = Vec3b(0,0,0); // small regions are painted with black too.

  }

may be changed to

for( i = 1; i < nccomps; i++ ) {
		colors[i] = Vec3b(rand()%256, rand()%256, rand()%256);
		if( stats.at<int>(i, cv::CC_STAT_AREA) < 100 )
			colors[i] = Vec3b(0,0,0); // small regions are painted with black too.
	}

and the below code gives me the right result.
am i right?thanks.

Exercise 4-1 Incorrect

For the Third Release of Learning OpenCV3, exercise 4-1 should be creating an ASCII typewriter.

example code for chapter18 and 19

Hi, @authors,

Would you release example code for chapter18 and 19 first? I'm reading these chapters for 3D reconstruction project and need the corresponding example code for practice.

Thanks!

Would like to confirm with Example 2-5 (Page: 31)

In the book "Learning OpenCV 3", on Page 31, "A Simple Transformation", Example 2-5.

Loading and then smoothing an image before it is displayed on the screen.

The Example 2-5 code, shows:

void example2_5( const cv::Mat & image ) 
{
    // Create some windows to show the input and output images in:
    cv::namedWindow( "Example2_5-in", cv::WINDOW_AUTOSIZE );
    cv::namedWindow( "Example2_5-out", cv::WINDOW_AUTOSIZE );
    
    // Create a window to show our input image:
    cv::imshow( "Example2_5-in", image );
    
    // Create an image to hold the smoothed output:
    cv::Mat out;

    // Do the smoothing
    // ( Note: Could use GaussianBlur(), blur(), medianBlur() or bilateralFilter(). )
    cv::GaussianBlur(image, out, cv::Size(5,5), 3, 3);
    cv::GaussianBlur(out, out, cv::Size(5,5), 3, 3);

    // Show the smoothed image in the output window:
    cv::imshow( "Example2_5-out", out );

    // Wait for the user to hit a key, windows will self destruct:
    cv::waitKey( 0 );
}

Were we suppose to call it as a function or take this code and modify it as to the example shown in github?
If not how to solve it for the book?
Not sure how "argv" on int main can pass it to the void function of example 2-5.

The github example for Example 2-5 does not show the usage of the function "void example2_5( const cv::Mat & image )".

Thanks.

the question of Exercise 6.1 is not right

the question of exercise 6.1 is

Find and open .../opencv/cxcore/include/cxtypes.h. Read through and find the
many conversion helper functions.
a. Choose a negative floating-point number.
b. Take its absolute value, round it, and then take its ceiling and floor.
c. Generate some random numbers.
d. Create a floating-point cv::Point2f and convert it to an integer cv::Point.
Convert a cv::Point to a cv::Point2f.

as cxtypes.h is no longer used in opencv3,please change this question .

example_15-04.cpp

my enviroment mac os mojave 10.14

updateCodebook(cv::Vec<unsigned char, 3> const&, CodeBook&, int*, int) + 117 (ex-15.4.cpp:67)

segmentation fault: 11

for (n = 0; n<numChannels; n++) {
        high[n] = p[n] + *(cbBounds+n); // segmentation fault 11 point
        if ( high[n] > 255 ) {
            high[n] = 255;
        }

        low[n] = p[n] - *(cbBounds+n);
        if ( low[n] < 0 ) {
            low[n] = 0;
        }
    }

example 2.5 in printed book

not having the source to fork is pretty BS but moving on, the source code in example 2.5, pages 31,32 is incomplete.

#include <opencv2/opencv.hpp>
using namespace cv;
void example2_5(cv::Mat & image){
	Mat out;
	namedWindow("input",WINDOW_AUTOSIZE);
	namedWindow("output",WINDOW_AUTOSIZE);
	imshow("input", image);
	GaussianBlur(image, out, Size(5,5) ,3, 3);
	GaussianBlur(  out, out, Size(5,5) ,3, 3);
	
	imshow("output",out);
	
	waitKey(0);
	}


int main(int argc, char **argv){
	Mat input;
	input = imread(argv[1]);
	example2_5(input);
	return 0;
	}

is "cv::smooth() "out of use?

in chapter 8 ,page 321
"3. Load an interesting image, and then blur it with cv::smooth() using a Gaussian
filter.
a. Set param1=param2=9. Try several settings of param3 (e.g., 1, 4, and 6). Display
the results.
b. Set param1=param2=0 before setting param3 to 1, 4, and 6. Display the results.
Are they different? Why?
c. Use param1=param2=0 again, but this time set param3=1 and param4=9.
Smooth the picture and display the results.
d. Repeat Exercise 3c but with param3=9 and param4=1. Display the results.
e. Now smooth the image once with the settings of Exercise 3c and once with
the settings of Exercise 3d. Display the results.
f. Compare the results in Exercise 3e with smoothings that use
param3=param4=9 and param3=param4=0 (i.e., a 9 × 9 filter). Are the results the
same? Why or why not?"
as i kown,cv::smooth() is out of use for quite a long time (am i right,i cant find it neither in the code nor in the book) ,then how to solve this problem,and where is the param1?param2?

the question of 6.2 have some problem

/*2. Compact matrix and vector types:
a. Using the cv::Mat33f and cv::Vec3f objects (respectively), create a 3 × 3
matrix and 3-row vector.
b. Can you multiply them together directly? If not, why not?

chage cv::Mat33f into cv::Matx33f ?
as we dont have Mat33f in opencv3……

example 20-02

Shouldn't you be calculating the inverse covariance matrix for the Mahalanobis distance?

example_18-01_from_disk readFilenames problem

The code of readFilenames for windows users has two problem as below:

  1. When dealing with the situation no files found, will cause no return value problem.
...
if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE)
        return;  // no files found
    do {
...
  1. Add full_file_name into vector of filenames, cause the program can not find files.
    ...
        filenames.push_back(full_file_name);
    } while (FindNextFile(dir, &file_data));
    ....

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.