C++ Programming : Class

This tutorial will show you how to use class in C++.  This is the class standard format :

class name_of_class

{

private:

// write private variables or function here

public:

// write public variables or function here

};

The difference between class and struct is the visibility. Struct declaration is always public while class can be set into private or public. To understand more about class in C++, we will make a simple class to create Point3D data type just like what we do in constructor section. Suppose we want to create a constructor to handle 3D data type which contain coordinate X, Y and Z.

Add this to your header in .cpp file

#include <math.h>

Write this code in your .cpp.

// create a class to handle coordinates 3D
class Point3D
{
public:
// declare public variable coordinate X, Y and Z
float X;
float Y;
float Z;
float Magnitude;
// create an empty constructor
Point3D() { };
// create a constructor to fill Point3D data type
Point3D(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
calcMagnitude();
};
// check if constructor is empty
bool isEmpty()
{
if (X != NULL && Y != NULL && Z != NULL)
return false;
return true;
};
// create a desctructor to destroy Point3D data type
~Point3D() { };
private:
// calculate magnitude from this point3D
void calcMagnitude()
{
Magnitude = isEmpty() ? 0 : sqrt(pow(X, 2) + pow(Y, 2) + pow(Z, 2));
}
};
// main function
int main(int argc, char** argv)
{
int key;
// create a Point3D data type named point
// insert X = 2.2, Y = 3.1 and Z = 4.5
Point3D point(2.2, 3.1, 4.5);
// read the value
cout << “The coordinate is P(“ << point.X << “,” << point.Y << “,” << point.Z << “)\n”;
cout << “The magnitude is “ << point.Magnitude << “\n”;
cout << “\nArray\n”;
// create an array of Point3D data type
Point3D* arrayPoint = new Point3D[10];
// fill the array of point using for loop
for (int i=0; i<10; i++)
{
arrayPoint[i] = Point3D(i, i, i);
cout << “The coordinate in P” << i << ” is (“ << arrayPoint[i].X << “,” << arrayPoint[i].Y << “,” << arrayPoint[i].Z << “)\n”;
}
// don’t forget to destroy the array if it is not used
delete[] arrayPoint;
cout << “\nVector\n”;
// create vector of Point3D data type
vector<Point3D> listPoint;
// fill the vector of point using for loop
for (int i=0; i<10; i++)
{
listPoint.push_back(Point3D(i, i, i));
cout << “The coordinate in P” << i << ” is (“ << listPoint[i].X << “,” << listPoint[i].Y << “,” << listPoint[i].Z << “)\n”;
}
// don’t forget to empty the vector if it is not used
listPoint.clear();
cin >> key;
return 0;
}

This is the result :

class1


 

C++ Programming : Function

This tutorial will show you how to use function in C++. We will make a simple function to write text in our console. This is the function standard format :

output function_name(input1, input2, …)

{

// write your code here

return output

}

Now we will create function to write a string in a specific coordinate in our console.

Add this to your .cpp header

#include <Windows.h>

Now write this in your .cpp

// A function to go to point (x, y) on console
void goTo(int xLine, int yLine)
{
COORD coord = {xLine, yLine};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
// A function to write a text on specific point on console
void writeText(int xLine, int yLine, string text)
{
goTo(xLine, yLine);
cout << text << flush;
}
// main function
int main(int argc, char** argv)
{
int key;
string text = “Hello World!”;
writeText(20, 10, text); // write text in point (20, 10)
writeText(40, 30, “Hello World!!”); // write text in point (40, 30)
cin >> key;
return 0;
}

This is the result

fuction


 

C++ Programming : Constructor

This tutorial will show you how to use struct to create a constructor in C++. We assume that you have already done the previous tutorial.


Constructor

You can use class or struct to create a constructor. The general format is :

struct name_of_constructor

{

// declare the variables here

name_of_constructor() { } // create empty constructor

~name_of_constructor() { } // create destructor

};

Suppose we want to create a constructor to handle 2D data type which contain coordinate X and Y. Write this code in your .cpp.

// create a constructor to handle coordinates 2D
struct Point2D
{
// declare local variable coordinate X and Y
int X;
int Y;
// create an empty constructor
Point2D() { }
// create a constructor to fill Point2D data type
Point2D(int x, int y)
{
X = x;
Y = y;
}
// create a desctructor to destroy Point2D data type
~Point2D() { };
};
// main function
int main(int argc, char** argv)
{
int key;
// create a Point2D data type named point
// insert X = 2 and Y = 3
Point2D point(2, 3);
// read the value
cout << “The coordinate is P(“ << point.X << “,” << point.Y << “)\n”;
cout << “\nArray\n”;
// create an array of Point2D data type
Point2D* arrayPoint = new Point2D[10];
// fill the array of point using for loop
for (int i=0; i<10; i++)
{
arrayPoint[i] = Point2D(i, i);
cout << “The coordinate in P” << i << “is (“ << arrayPoint[i].X << “,” << arrayPoint[i].Y << “)\n”;
}
// don’t forget to destroy the array if it is not used
delete[] arrayPoint;
cout << “\nVector\n”;
// create vector of Point2D data type
vector<Point2D> listPoint;
// fill the vector of point using for loop
for (int i=0; i<10; i++)
{
listPoint.push_back(Point2D(i, i));
cout << “The coordinate in P” << i << “is (“ << listPoint[i].X << “,” << listPoint[i].Y << “)\n”;
}
// don’t forget to empty the vector if it is not used
listPoint.clear();
cin >> key;
return 0;
}

The result is :

structure


 

C++ Programming : Array and Vector

This tutorial will show you how to use array and vector in C++. We assume that you have already done the previous tutorial.


Array

The general array declaration format is :

 type_array_data_with_pointer name_of_array = new type_array_data[number_of_array_allocation];

This code will show how to initialize an array and allocate array with for loop. In your main function :

// main function
int main(int argc, char** argv)
{
int key;
// array declaration
int* data = new int[10];
// use for loop to fill the array one by one
for (int i=0; i<10; i++)
{
// fill the i-th data with a value
data[i] = i;
// show the value inside i-th data
cout << “value inside “ << i << “-th data is “ << data[i] << “\n”;
}
cin >> key;
return 0;
}

The result is :

array


Vector

The general vector declaration format is :

// this declaration will create dynamic vector

vector<type_vector_data> name_of_vector;

// this declaration will create static vector

vector<type_vector_data> name_of_vector(number_of_vector_allocation);

This code will show how to initialize dynamic vector and allocate vector with for loop. In your main function :

// main function
int main(int argc, char** argv)
{
int key;
// dynamic vector declaration
vector<int> data;
// use for loop to fill the vector one by one
for (int i=0; i<10; i++)
{
// fill the i-th data with a value
data.push_back(i);
// show the value inside i-th data
cout << “value inside “ << i << “-th data is ” << data[i] << “\n”;
}
cin >> key;
return 0;
}

The result is :

array

This code will show how to initialize static vector and allocate vector with for loop. In your main function :

// main function
int main(int argc, char** argv)
{
int key;
// static vector declaration
vector<int> data(10);
// use for loop to fill the vector one by one
for (int i=0; i<10; i++)
{
// fill the i-th data with a value
// you can use this
data.at(i) = i;
// or this
data[i] = i;
// show the value inside i-th data
cout << “value inside “ << i << “-th data is “ << data[i] << “\n”;
}
cin >> key;
return 0;
}

The result is :

array


 

C++ Programming : Iteration

This tutorial will show you how to use iteration in C++. We only cover iteration which most used in programming. We assume that you have already done the previous tutorial.


For Loop

The general format is :

for (initial condition; stopping condition; increment)

{

// write your code here

}

In your main function :

// main function
int main(int argc, char** argv)
{
int key;
// loop from i=0 until i<10 with increment i=i+1
for (int i=0; i<10; i++)
{
cout << “data number “ << i << “\n”;
}
cin >> key;
return 0;
}

The result is :

iteration


While Loop

The general format is :

// initialize stopping condition here;

while (stopping condition is false)

{

// write your code here

// if (condition met)

//          stopping condition is true;

}

In your main function :

// main function
int main(int argc, char** argv)
{
int key;
// loop from i=0 until i<10
int i = 0; // initialize variable for stopping condition
while (i < 10) // i < 10 is the stopping condition
{
cout << “data number “ << i << “\n”;
i++; // increment i
}
cin >> key;
return 0;
}

The result is :

iteration


 

C++ Programming : Conditional

This tutorial will show you how to use conditional statements in C++. We only cover conditional statements which most used in programming. We assume that you have already done the previous tutorial.


If Else

The general format is :

if (condition 1) statement 1;

else if (condition 2) statement 2;

else statement 3;

In your main function :

// main program
int main(int argc, char** argv)
{
// \n is enter; \t is tab
cout << “Conditional Statements Demo\n\n”;
cout << “Information :\n”; // display text
cout << “Hello\t<Press 1>\n”;
cout << “Exit\t<Press 0>\n\n”;
cout << “Key Command : “;
cin >> key; // take integer input
/////////////////////////////////////////////////////////////////
// conditional statements
// if condition 1 then statement 1
if (key == 0)
exit(0);
// if condition 2 then statement 2
else if (key == 1)
{
text = “Hello World!”;
cout << “\n” << text;
}
// otherwise
else
{
text = “Press 1 or 0”;
cout << “\n” << text;
}
/////////////////////////////////////////////////////////////////
cout << “\n\n” << “Press any key to exit…”;
cin >> key;
return 0;
}

Switch Case

The general format is :

switch (input condition)

{

case condition 1 : statement 1; break;

case condition 2 : statement 2; break;

default : statement 3; break;

}

In your main function :

// main program
int main(int argc, char** argv)
{
// \n is enter; \t is tab
cout << “Conditional Statements Demo\n\n”;
cout << “Information :\n”; // display text
cout << “Hello\t<Press 1>\n”;
cout << “Exit\t<Press 0>\n\n”;
cout << “Key Command : “;
cin >> key; // take integer input
/////////////////////////////////////////////////////////////////
// conditional statements
switch (key)
{
// if condition 1 then statement 1
case 0:
exit(0);
break;
// if condition 2 then statement 2
case 1:
text = “Hello World!”;
cout << “\n” << text;
break;
// otherwise
default:
text = “Press 1 or 0”;
cout << “\n” << text;
break;
}
/////////////////////////////////////////////////////////////////
cout << “\n\n” << “Press any key to exit…”;
cin >> key;
return 0;
}

Other kind

If there is a condition and two statement then you can use this format :

result = condition ? statement 1 : statement 2;

This format is equivalent to :

if (condition) statement 1;

else statement 2;

In your main function :

// main program
int main(int argc, char** argv)
{
// \n is enter; \t is tab
cout << “Conditional Statements Demo\n\n”;
cout << “Information :\n”; // display text
cout << “Hello\t<Press 1>\n”;
cout << “Exit\t<Press Anything>\n\n”;
cout << “Key Command : “;
cin >> key; // take integer input

/////////////////////////////////////////////////////////////////
// conditional statements
text = key == 1 ? “Hello World!” : “Press anything to exit…”;
/////////////////////////////////////////////////////////////////

cout << “\n\n” << text;
cin >> key;
return 0;
}

 

C++ Programming : Hello World!

After you have done the previous tutorialwe will write a simple program to display “Hello World!” text in our console. Here is the step :

  • Assume you already have an empty .cpp file in the previous tutorial.
  • C++ file usually has three important parts : header declaration, variable initialization, and main function.

Header declaration

  • We declare all necessary header which used in our program.
  • To display “Hello World!” text in our program, we need standard input/output library and string library.
  • Here is the header that will be used:
// header declaration
#include <iostream> // handle standard input/output
#include <string> // handle string type
using namespace std;

Variable initialization

  • We initiate all variable (global) which used in our program.
  • Here is the variables that will be used :
// variable initialization
string text;
int key;

Main function

  • We write our program in the main function because this function will be the first function to be executed after the program running.
  • Here is the program to display “Hello World!” text in our console :
// main program
int main(int argc, char** argv)
{
text = “Hello World!”; // text that will be displayed
cout << text; // display text
cin >> key; // take integer input
return 0;
}

Executing the program

  • In Visual Studio, we run the program by clicking green play button.

runbutton

  • And the result is :

resulthelloworld


 

C++ Programming : Visual Studio C++

We can write a program with C++ language using Visual Studio C++. Here is the configuration :

  • Open Visual Studio C++.
  • Create a C++ project and select Win32 console application.
  • Give a name to the project (without space or characters) then click OK.

vs-solution

  • Click Next — select Console Application — check Empty project — click Finish.

empty-win32-console

  • Now you are done creating empty project in Visual C++.
  • Go to Solution ExplorerSource Files — Right click — AddNew Item.

solution-new-file

  • Select C++ File (.cpp) file then give it a name — click Add

make-cpp-file

  • You will get a .cpp file in your project. The Source Files is a folder where you put all your .cpp / .c / .cu files and the Header Files is a folder where you put all your .h / .hpp / .cuh files
  • Now you good to go to the coding tutorial.

 

Image Processing : Acquisition with OpenCV Part II

This tutorial will explain on how to grab frames from IP Camera and Kinect or Xtion Pro Live.


Read IP Camera

Prepare a router and an IP camera.  See how to configure your IP camera to connect to your already-connected internet-router via wireless and access that IP camera via wireless public IP here. 

To access IP camera using OpenCV we’ll need to compile OpenCV with ffmpeg codec support because we will stream mjpg type data. The code similar with opening webcam but with different address. Remember to delete ?mute in <ipcameraaddress>/video.mjpg?mute because OpenCV only accept video streaming.

int main(int argc, char** argv)

{

VideoCapture ipcam;
Mat frame;
bool status;

// the address format is 
// http://<user>:<password>@<ipaddress>:<port>/video.mjpg
// example with my ip camera connected to internet via EVDO-router
// http://admin:admin@10.241.126.66:3333/video.mjpg
// 
// Find your ip camera address : 
// 1. Open your ip camera on chrome, 
// 2. Right click on the streaming video – select inspect element. 
// 3. There your  address revealed 
// 4. You need to add your username and password to access ip camera
// 5. The format is just like the given format above

ipcam.open(http://admin:admin@10.241.126.66:3333/video.mjpg); 
if (ipcam.isOpened()) 
{
   int keyCode = 1;
   // we can choose the size of captured frame
   // set frame width to 640
   ipcam.set(CV_CAP_PROP_FRAME_WIDTH, 640); 
   // set frame height to 480 
   ipcam.set(CV_CAP_PROP_FRAME_HEIGHT, 480); 
   // stop ipcam capture if keyboard ‘space’ pressed
   while (keyCode != 32)
   {
      // grab frame from streaming video
      ipcam >> frame;                        
      if (frame.empty() == false
      {
         imshow(“Preview IP-Cam”, frame);     // show frame
         keyCode = cvWaitKey(1);
      }
   }
}
// don’t forget to release after it is not used
frame.release();
ipcam.release();
return 0;
}

Read Kinect / Asus XTion Pro Live

I assume you already have OpenNI, PrimeSense NITE installed in your system and read about configuring Visual Studio 2010 with OpenCV, OpenNI, PrimeSense, and CUDA here.  I didn’t use OpenCV to stream Asus XTion Pro Live RGB-D, but I will converted that stream to OpenCV Mat so I can manipulate further with that input. You can find these code from OpenNI samples but they will use OpenGL to view the stream. You can use OpenNI with OpenCV if you compile OpenCV with WITH_OPENNI flag checked.


These are the header that will be used:

#include <Windows.h>
#include <XnCppWrapper.h>
#include <XnPropNames.h>
#include <opencv2\opencv.hpp>

using namespace cv;
using namespace xn;

These are variables that will be used:

enum StreamMode             // streaming mode
{
  DUAL_SENSOR,
  OVERLAY_SENSOR
};

Context context;            // create context
XnStatus statusRet;         // status for an operation
XnMapOutputMode outputMode; // setting output mode

float* depthHist;           // histogram depth
XnDepthPixel depthZRes;     // depth-Z
DepthGenerator depthMap;    // depth generator
DepthMetaData depthData;    // depth metadata

XnRGB24Pixel* texMap;       // texture map
unsigned int texMapX = 0;   // X-size texture map
unsigned int texMapY = 0;   // Y-size texture map
ImageGenerator colorMap;    // color generator
ImageMetaData colorData;    // color metadata

int streamFPS;     // streaming FPS 
Size streamSize;   // size streaming

// OpenCV Mat that contain depth and color pixel matrix
Mat depthFrame, colorFrame, overlayFrame; 

Function to draw overlay RGB-D with accumulative histogram

void DrawOverlay(DepthMetaData &data)
{
  const XnDepthPixel* depthBuff = data.Data();
  texMapX = (unsigned short)data.FullXRes();
  texMapY = (unsigned short)data.FullYRes();
  depthZRes = data.ZRes();
  depthHist = (float*)malloc(depthZRes * sizeof(float));
  // create accumulative histogram from depth  
  unsigned int nValue = 0;
  unsigned int numPoints = 0;
  memset(depthHist, 0, depthZRes * sizeof(float));
  for (XnUInt y = 0; y < data.YRes(); ++y)
  {
    for (XnUInt x = 0; x < data.XRes(); ++x)
    {
      nValue = *depthBuff;
      if (nValue != 0)
      {
++depthHist[nValue];
++numPoints;
      }
++depthBuff;
    }
  }
  for (int nIndex=1; nIndex < depthZRes; nIndex++)
    depthHist[nIndex] += depthHist[nIndex-1];
  if (numPoints)
  {
    for (int nIndex=1; nIndex < depthZRes; nIndex++)
      depthHist[nIndex] = (unsigned int)(256 * (1.0f – (depthHist[nIndex] / numPoints)));
  }
  // create texture map  
  memset(texMap, 0, texMapX * texMapY * sizeof(XnRGB24Pixel));
  const XnDepthPixel* pDepthRow = data.Data();
  XnRGB24Pixel* pTexRow = texMap + data.YOffset() * texMapX;
  for (XnUInt y = 0; y < data.YRes(); ++y)
  {
    const XnDepthPixel* pDepth = pDepthRow;
    XnRGB24Pixel* pTex = pTexRow + data.XOffset();
    for (XnUInt x = 0; x < data.XRes(); ++x, ++pDepth, ++pTex)
    {
      if (*pDepth != 0)
      {
int nHistValue = depthHist[*pDepth];
pTex->nRed = nHistValue;
pTex->nGreen = nHistValue;
pTex->nBlue = 0;
      }
    }
    pDepthRow += data.XRes();
    pTexRow += texMapX;
  }
  delete(depthHist);
}

Function to capture stream RGB, Depth sensor and Overlay RGB-D:

XnStatus CaptureStream(int mode)
{
  statusRet = context.WaitAnyUpdateAll();
  if (statusRet == XN_STATUS_OK)
  {
    switch (mode)
    {
    // Read dual RGB-Depth Sensor
    case 0:  
// Depth
depthMap.GetMetaData(depthData);
const XnDepthPixel* depthBuff = depthMap.GetDepthMap();
depthFrame.create(depthData.FullYRes(), depthData.FullXRes(), CV_16UC1);
memcpy(depthFrame.data, depthBuff, depthData.FullYRes() * 
depthData.FullXRes() * sizeof(XnDepthPixel));
// RGB
colorMap.GetMetaData(colorData);
const XnRGB24Pixel* colorBuff = colorMap.GetRGB24ImageMap();
colorFrame.create(colorData.FullYRes(), colorData.FullXRes(), CV_8UC3);
memcpy(colorFrame.data, colorBuff, colorData.FullYRes() *
colorData.FullXRes() * sizeof(XnRGB24Pixel));
cvtColor(colorFrame, colorFrame, CV_RGB2BGR);
break;
    // Overlay RGB-Depth Sensor
    case 1:
depthMap.GetMetaData(depthData);
colorMap.GetMetaData(colorData);
DrawOverlay(depthData);
overlayFrame.create(texMapY, texMapX, CV_8UC3);
memcpy(overlayFrame.data, texMap, texMapY * texMapX * sizeof(XnRGB24Pixel));
cvtColor(overlayFrame, overlayFrame, CV_RGB2BGR);
break;
    }
  }
  return statusRet;
}

Main program: 

Just press “1” or “2” to change streaming mode dual RGB&Depth – Overlay

Press “space” to exit program

int main(int argc, char** argv) 
{
  outputMode.nFPS = 30;    // set fps to 30
  outputMode.nXRes = 640;  // set frame width
  outputMode.nYRes = 480;  // set frame height

  int cIdxGen = DUAL_SENSOR;     // default view dual RGB-Depth
  int pIdxGen = cIdxGen;
  statusRet = context.Init();    // initialize openni
  context.SetGlobalMirror(true); // mirror output stream
  if (statusRet == XN_STATUS_OK) 
  {
    statusRet = depthMap.Create(context); // create depth map
    statusRet = colorMap.Create(context); // create color map
    // set output stream from each sensor to our settings
    statusRet = colorMap.SetMapOutputMode(outputMode); 
    statusRet = depthMap.SetMapOutputMode(outputMode);
    // begin to stream
    statusRet = context.StartGeneratingAll();
    if (statusRet == XN_STATUS_OK)
    {
      texMap = new XnRGB24Pixel[outputMode.nXRes*outputMode.nYRes];
      while (true)
      {
        if (CaptureStream(cIdxGen) == XN_STATUS_OK)
{
         switch (cIdxGen)
         {
         case 0:     
           imshow(“Depth Sensor”, depthFrame);
           imshow(“RGB Sensor”, colorFrame);
           break;
         case 1:      
           imshow(“Overlay Sensor”, overlayFrame);
           break;
         }
         char key = cvWaitKey(10);
         if (key == 49)                // keyboard “1” pressed
           cIdxGen = DUAL_SENSOR;
         else if (key == 50)           // keyboard “2” pressed
           cIdxGen = OVERLAY_SENSOR;
         else if (key == 32)           // keyboard “space” pressed
           break;  
         if (pIdxGen != cIdxGen)
           pIdxGen = cIdxGen;
          }
        }
      }
    }
    else
      MessageBox(NULL, L“Failed to initialize OpenNI!”, L“Error!”, 0);
  }
  // release all unused created memory
  depthMap.Release(); colorMap.Release(); userMap.Release();
  depthFrame.release(); colorFrame.release();
  overlayFrame.release(); userFrame.release();
  context.Shutdown();

  return 0;
}

You can do the same to get streaming from Infra Red sensor