Something More for Research

Explorer of Research #HEMBAD

Archive for the ‘OpenCV’ Category

OpenCV 3.1 with CUDA , QT , Python Complete Installation on Windows in With Extra Modules

Posted by Hemprasad Y. Badgujar on May 13, 2016


OpenCV 3.1 with CUDA , QT , Python Complete Installation on Windows in With Extra Modules

The description here was tested on Windows 8.1 Pro. Nevertheless, it should also work on any other relatively modern version of Windows OS. If you encounter errors after following the steps described below, feel free to contact me.

Note :  To use the OpenCV library you have two options: Installation by Using the Pre-built Libraries or Installation by Making Your Own Libraries from the Source Files. While the first one is easier to complete, it only works if you are coding with the latest Microsoft Visual Studio IDE and doesn’t take advantage of the most advanced technologies we integrate into our library.

I am going to skip Installation by Using the Pre-built Libraries is it is easier to install even for New User. So Let’s Work on Installation by Making Your Own Libraries from the Source Files (If you are building your own libraries you can take the source files from OpenCV Git repository.) Building the OpenCV library from scratch requires a couple of tools installed beforehand

Prerequisites  Tools

Step By Step Prerequisites Setup

  • IDE : Microsoft Visual Studio. However, you can use any other IDE that has a valid CC++ compiler.

    Installing By Downloading from the Product Website Start installing Visual Studio by going to Visual Studio Downloads on the MSDN website and then choosing the edition you want to download.here we will going to use Visual Studio 2012 / ISO keys with  Visual Studio 2012 Update 4 /ISO and Step By Step Installing Visual Studio Professional 2012
  • Make Tool : Cmake is a cross-platform, open-source build system.

    Download and install the latest stable binary version: here we will going to use CMake 3 Choose the windows installer (cmake-x.y.z-win32.exe) and install it. Letting the cmake installer add itself to your path will make it easier but is not required.

  • Download OpenCV source Files by GIT/Sourceforge by : TortoiseGit or download source files from page on Sourceforge.

    The Open Source Computer Vision Library has >2500 algorithms, extensive documentation and sample code for real-time computer vision. It works on Windows, Linux, Mac OS X, Android and iOS.

  •  Python and Python libraries : Installation notes

    • It is recommended to uninstall any other Python distribution before installing Python(x,y)
    • You may update your Python(x,y) installation via individual package installers which are updated more frequently — see the plugins page
    • Please use the Issues page to request new features or report unknown bugs
    • Python(x,y) can be easily extended with other Python libraries because Python(x,y) is compatible with all Python modules installers: distutils installers (.exe), Python eggs (.egg), and all other NSIS (.exe) or MSI (.msi) setups which were built for Python 2.7 official distribution – see the plugins page for customizing options
    • Another Python(x,y) exclusive feature: all packages are optional (i.e. install only what you need)
    • Basemap users (data plotting on map projections): please see the AdditionalPlugins
  • Sphinx is a python documentation generator

    After installation, you better add the Python executable directories to the environment variable PATH in order to run Python and package commands such as sphinx-build easily from the Command Prompt.

    1. Right-click the “My Computer” icon and choose “Properties”

    2. Click the “Environment Variables” button under the “Advanced” tab

    3. If “Path” (or “PATH”) is already an entry in the “System variables” list, edit it. If it is not present, add a new variable called “PATH”.

      • Right-click the “My Computer” icon and choose “Properties”

      • Click the “Environment Variables” button under the “Advanced” tab

      • If “Path” (or “PATH”) is already an entry in the “System variables” list, edit it. If it is not present, add a new variable called “PATH”.

      • Add these paths, separating entries by ”;”:

        • C:\Python27 – this folder contains the main Python executable
        • C:\Python27\Scripts – this folder will contain executables added by Python packages installed with pip (see below)

        This is for Python 2.7. If you use another version of Python or installed to a non-default location, change the digits “27” accordingly.

      • Now run the Command Prompt. After command prompt window appear, type python and Enter. If the Python installation was successful, the installed Python version is printed, and you are greeted by the prompt>>> . TypeCtrl+Z and Enter to quit.

        Add these paths, separating entries by ”;”:

        • C:\Python27 – this folder contains the main Python executable
        • C:\Python27\Scripts – this folder will contain executables added by Python packages installed with easy_install (see below)

        This is for Python 2.7. If you use another version of Python or installed to a non-default location, change the digits “27” accordingly.

        After installation, you better add the Python executable directories to the environment variable PATH in order to run Python and package commands such as sphinx-build easily from the Command Prompt.

      • Install the pip command

      Python has a very useful pip command which can download and install 3rd-party libraries with a single command. This is provided by the Python Packaging Authority(PyPA): https://groups.google.com/forum/#!forum/pypa-dev

      To install pip, download https://bootstrap.pypa.io/get-pip.py and save it somewhere. After download, invoke the command prompt, go to the directory with get-pip.py and run this command:

      C:\> python get-pip.py
      

      Now pip command is installed. From there we can go to the Sphinx install.

      Note :pip has been contained in the Python official installation after version

        of Python-3.4.0 or Python-2.7.9.
  • Installing Sphinx with pip

    If you finished the installation of pip, type this line in the command prompt:

    C:\> pip install sphinx
    

    After installation, type sphinx-build -h on the command prompt. If everything worked fine, you will get a Sphinx version number and a list of options for this command.

    That it. Installation is over. Head to First Steps with Sphinx to make a Sphinx project.

    Now run the Command Prompt. After command prompt window appear, type python and Enter. If the Python installation was successful, the installed Python version is printed, and you are greeted by the prompt>>> . TypeCtrl+Z and Enter to quit.

  • Install the easy_install command

    Python has a very useful easy_install command which can download and install 3rd-party libraries with a single command. This is provided by the “setuptools” project: https://pypi.python.org/pypi/setuptools.

    To install setuptools, download https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py and save it somewhere. After download, invoke the command prompt, go to the directory with ez_setup.py and run this command:

    C:\> python ez_setup.py
    

    Now setuptools and its easy_install command is installed. From there we can go to the Sphinx install.

    Installing Sphinx with easy_install

    If you finished the installation of setuptools, type this line in the command prompt:
    C:\> easy_install sphinx
    

    After installation, type sphinx-build on the command prompt. If everything worked fine, you will get a Sphinx version number and a list of options for this command.

  • Numpy is a scientific computing package for Python. Required for the Python interface.

Try the (unofficial) binaries in this site: http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
You can get numpy 1.6.2 x64 with or without Intel MKL libs to Python 2.7

I suggest WinPython, a Python 2.7 distribution for Windows with both 32- and 64-bit versions.

It is also worth considering the Anaconda Python distribution. http://continuum.io/downloads

  • Numpy :Required for the Python interface abve Installation of python alosho included with Numpy and Scipy libraries

  • Intel © Threading Building Blocks (TBB) is used inside OpenCV for parallel code snippets. Download Here

    • Download TBB
      • Go to TBB download page to download the open source binary releases. I choose Commercial Aligned Release, because this has the most stable releases. I downloaded tbb43_20141204os, TBB 4.3 Update 3, specifically tbb43_20141204os for Windows. The release has the header files as well as the import library and DLL files prebuilt for Microsoft Visual C++ 8.0 and 9.0 on both x86(IA32) and x64(intel64). If you are aggressive and need the source code of TBB, you can try stable releases or development releases.
    • Install TBB
      • Extract the files in the zip file to a local directory, for example, C:\TBB. You should find tbb22_013oss under it. This is the installation directory, and doc, example, include etc should be directly under the installation folder.
      • Set a Windows environment variable TBB22_INSTALL_DIR to the above directory, e.g., C:\TBB\tbb22_013oss.
    • Develop with TBB
      • Add $(TBB22_INSTALL_DIR)\include to your C++ project’s additional include directories.
      • Add $(TBB22_INSTALL_DIR)\<arch>\<compiler>\lib (e.g., $(TBB22_INSTALL_DIR)\ia32\vc9\lib) to your project’s additional library directories.
      • Add to your project’s additional dependencies tbb.lib (Release) or tbb_debug.lib (Debug).
      • Write your C++ code to use TBB. See code below as an example.
    • Deploy with TBB
      • The TBB runtime is in TBB DLLs (tbb.dll/tbbmalloc.dll/tbbmalloc_proxy.dll for Release, tbb_debug.dll/tbbmalloc_debug.dll/tbbmalloc_proxy_debug.dll for Debug). They can be found in $(TBB22_INSTALL_DIR)\\\bin.
      • Your executable should have these DLLs in the same folder for execution.

    Intel © Integrated Performance Primitives (IPP) may be used to improve the performance of color conversion.(Paid)

    Intel Parallel Studio XE 2015 – Cluster Edition includes everything in the Professional edition (compilers, performance libraries, parallel models, performance profiler, threading design/prototyping, and memory & thread debugger). It adds a MPI cluster communications library, along with MPI error checking and tuning to design, build, debug and tune fast parallel code that includes MPI.

  • Eigen is a C++ template library for linear algebra.

     “install” Eigen?

    In order to use Eigen, you just need to download and extract Eigen‘s source code (see the wiki for download instructions). In fact, the header files in the Eigen subdirectory are the only files required to compile programs using Eigen. The header files are the same for all platforms. It is not necessary to use CMake or install anything.

     simple first program

    Here is a rather simple program to get you started.

    #include <iostream>
    #include <Eigen/Dense>
     int main()
    {
    MatrixXd m(2,2);
    m(0,0) = 3;
    m(1,0) = 2.5;
    m(0,1) = -1;
    m(1,1) = m(1,0) + m(0,1);
    std::cout << m << std::endl;
    }
  • Installing CUDA Development Tools

    The setup of CUDA development tools on a system running the appropriate version of Windows consists of a few simple steps:

    • Verify the system has a CUDA-capable GPU.
    • Download the NVIDIA CUDA Toolkit.
    • Install the NVIDIA CUDA Toolkit.
    • Test that the installed software runs correctly and communicates with the hardware.
    • CUDA Toolkit will allow you to use the power lying inside your GPU. we will going to use CUDA 7.5  Toolkit

      To verify that your GPU is CUDA-capable, open the Control Panel (StartControl > Panel) and double click on System. In the System Propertieswindow that opens, click the Hardware tab, then Device Manager. Expand the Display adapters entry. There you will find the vendor name and model of your graphics card. If it is an NVIDIA card that is listed inhttp://developer.nvidia.com/cuda-gpus, your GPU is CUDA-capable.

      The Release Notes for the CUDA Toolkit also contain a list of supported products.

       Download the NVIDIA CUDA Toolkit

      The NVIDIA CUDA Toolkit is available at http://developer.nvidia.com/cuda-downloads.

      Choose the platform you are using and download the NVIDIA CUDA Toolkit

      The CUDA Toolkit contains the CUDA driver and tools needed to create, build and run a CUDA application as well as libraries, header files, CUDA samples source code, and other resources.

      Download Verification

      The download can be verified by comparing the MD5 checksum posted at http://developer.nvidia.com/cuda-downloads/checksums with that of the downloaded file. If either of the checksums differ, the downloaded file is corrupt and needs to be downloaded again.

      To calculate the MD5 checksum of the downloaded file, follow the instructions at http://support.microsoft.com/kb/889768.

      Install the CUDA Software

      Before installing the toolkit, you should read the Release Notes, as they provide details on installation and software functionality.

      Note: The driver and toolkit must be installed for CUDA to function. If you have not installed a stand-alone driver, install the driver from the NVIDIA CUDA Toolkit.

      Graphical Installation

      Install the CUDA Software by executing the CUDA installer and following the on-screen prompts.

      Silent Installation

      Alternatively, the installer can be executed in silent mode by executing the package with the -s flag. Additional flags can be passed which will install specific subpackages instead of all packages. Allowed subpackage names are: CUDAToolkit_6.5, CUDASamples_6.5, CUDAVisualStudioIntegration_6.5, and Display.Driver. For example, to install only the driver and the toolkit components:

      .exe -s CUDAToolkit_6.5 Display.Driver

      This will drastically improve performance for some algorithms (e.g the HOG descriptor). Getting more and more of our algorithms to work on the GPUs is a constant effort of the OpenCV .

  • JRE :Java run time environment

    Installing Ant The binary distribution of Ant consists of the following directory layout:

      ant
       +--- README, LICENSE, fetch.xml, other text files. //basic information
       +--- bin  // contains launcher scripts
       |
       +--- lib  // contains Ant jars plus necessary dependencies
       |
       +--- docs // contains documentation
       |      |
       |      +--- images  // various logos for html documentation
       |      |
       |      +--- manual  // Ant documentation (a must read ;-)
       |
       +--- etc // contains xsl goodies to:
                //   - create an enhanced report from xml output of various tasks.
                //   - migrate your build files and get rid of 'deprecated' warning
                //   - ... and more ;-)
    

    Only the bin and lib directories are required to run Ant. To install Ant, choose a directory and copy the distribution files there. This directory will be known as ANT_HOME.

Before you can run Ant there is some additional set up you will need to do unless you are installing the RPM version from jpackage.org:

  • Add the bin directory to your path.
  • Set the ANT_HOME environment variable to the directory where you installed Ant. On some operating systems, Ant’s startup scripts can guess ANT_HOME(Unix dialects and Windows NT/2000), but it is better to not rely on this behavior.
  • Optionally, set the JAVA_HOME environment variable (see the Advanced section below). This should be set to the directory where your JDK is installed.

Operating System-specific instructions for doing this from the command line are in the Windows, Linux/Unix (bash), and Linux/Unix (csh) sections. Note that using this method, the settings will only be valid for the command line session you run them in. Note: Do not install Ant’s ant.jar file into the lib/ext directory of the JDK/JRE. Ant is an application, whilst the extension directory is intended for JDK extensions. In particular there are security restrictions on the classes which may be loaded by an extension.

Windows Note:
The ant.bat script makes use of three environment variables – ANT_HOME, CLASSPATH and JAVA_HOME. Ensure that ANT_HOME and JAVA_HOME variables are set, and that they do not have quotes (either ‘ or “) and they do not end with \ or with /. CLASSPATH should be unset or empty.

Check Installation

You can check the basic installation with opening a new shell and typing ant. You should get a message like this

Buildfile: build.xml does not exist!
Build failed

So Ant works. This message is there because you need to write an individual buildfile for your project. With a ant -version you should get an output like

Apache Ant(TM) version 1.9.2 compiled on July 8 2013

If this does not work ensure your environment variables are set right. They must resolve to:

  • required: %ANT_HOME%\bin\ant.bat
  • optional: %JAVA_HOME%\bin\java.exe
  • required: %PATH%=…maybe-other-entries…;%ANT_HOME%\bin;…maybe-other-entries

ANT_HOME is used by the launcher script for finding the libraries. JAVA_HOME is used by the launcher for finding the JDK/JRE to use. (JDK is recommended as some tasks require the java tools.) If not set, the launcher tries to find one via the %PATH% environment variable. PATH is set for user convenience. With that set you can just start ant instead of always typingthe/complete/path/to/your/ant/installation/bin/ant.

Posted in GPU (CUDA), Image / Video Filters, Mixed, OpenCV, OpenCV | Leave a Comment »

Installing OpenCV 3.0 and Python 3.4 on Windows

Posted by Hemprasad Y. Badgujar on May 6, 2016


Installing OpenCV 3.0 and Python 3.4  on Windows

I recently decided to update to the newest OpenCV version (3.0) and wanted to add Python 3.4+ along with it. It took me a couple hours to set up because I couldn’t find a good tutorial on how to install them on Windows. So, here’s my attempt at a tutorial based on what I have just been through. Hope it helps.

For the rest of this post, I will show you how to compile and install OpenCV 3.0 with Python 3.4+ bindings on Windows.

Step 1

In order to use python 3.4+ with openCV, the first step is to build our own version of openCV using CMake and Visual Studio (I’m using Visual Studio 2013 Express for Desktop), since the prebuilt binaries in the openCV website includes python 2.7 libraries and not the 3.4+ libraries. So, if you have not done so, install these applications below:

Step 2

To use python with openCV, aside from installing the core python packages, you also need to install Numpy (a python array and matrices library). You can install them separately from their own websites. However, I like to use python packages from third-parties, specifically Anaconda. These packages give you all the common python libraries bundled with the core python packages. This way, you install everything in a single install. So, the next step is to download and install python+numpy using Anaconda. Download the source from the link below and just install with the recommended install settings.

Note:

It’s good to use virtual environments with python installation just so you can have several versions in one machine for different types of applications you’ll be developing. However, I wont get into this here.

Step 3

Next, we need to download the openCV source. Remember, we need to build a custom openCV build from the source and will not use the prebuilt binaries available for download from the openCV website. There are a couple of ways to download the source, and both of them involve the openCV GitHub webpage.

The easiest way to download the source is to download a zip file containing the contents of the openCV GitHub page. This can be done by pressing the Download Zip button towards the right side of the page. Once your done, extract the contents of the zip file to a folder, for convenience, name it opencv.

gitbutton

If you want to receive updated versions of openCV as they are made by the contributors, you can also clone the source using Git. If you’re familiar with git then you can just use the clone URL as shown in the above image or fork a version of the code for yourself. If you are just getting started with Git, you can use the Clone in Desktop button to copy the updated version of openCV to your local machine. For this to work, you will be asked to download the GitHub Desktop application (you can just follow the instructions from GitHub on how to install this application).

Step 4

Now that all the tools we need to build our very own openCV have been installed, we will start building our openCV binaries. To start the process, create a new folder called build inside your openCV directory (the directory you unzipped/cloned the openCV source to).

We use CMake, the application installed in Step 1, to build the openCV binaries from its source code. So, open CMake-gui from the Start Menu. Now, near the top of the CMake window chose the location of your source code (the openCV directory) and choose the location to build the binaries in (the build folder you just created). I chose to put my openCV directory in C:/opencv, so the settings for me would look like this:

cmakefolder

Now, the next thing to do is to configure your build by clicking the Configure button in the CMake window. A pop-up that prompts you to select a compiler will show, choose Visual Studio 12 2013 or the VS version you have installed on your machine. Once chosen, click finish and the configuration process will start. Once its done, the status window should say Configuring done like below:

configure

Once the configuration is complete, you will receive fields marked in red in the above display window. If your result is just a long list of fields, make sure to check the Grouped checkbox so that they are nicely grouped like the image below.
configurecomplete

First, the WITH field describes the features you want to include inside your openCV binaries. You can include or exclude a feature by using the checkbox in the list. The defaults should be fine, by this is all up to you. If you want to know what each field does, just hover over them and an explanation will pop up.

with

Next, you need to configure the BUILD field. The BUILD field configures the build method used to build the binaries and also the modules that are to be build into the binaries. The fields in ALL CAPS are the build methods and the rest are the modules to be built. You can keep the methods as is. This is also the case for the modules except for one thing. Since we are building for python 3.4+ we do not need to build for python 2+, therefore it is necessary to uncheck the BUILD_opencv_python2 checkbox. If left checked, this will cause an error during the build process if you do not have python 2+ installed in your machine.

buildcmake

Now, that everything is configured, click the Generate button to create the build filesinside the build folder.

Step 5

Once the build files have been generated by CMake, the next step is to create the binaries using Visual Studio as the compiler. First, go to the your opencv/build directory, then find and open the openCV solution (opencv.sln). Once the solution is open, you should get a solution explorer that looks something like this

allbuild

Before we build anything, change the build mode to Release instead of Debug. Now,right-click on the Solution ‘OpenCV’ or on ALL_BUILD and select Build. This will start the build process and may take some time.

Once the build is complete, right-click on INSTALL to install openCV-Python on your machine.

Step 6

Once the installation is complete, we need to verify the installation by using python IDLE. Just search for IDLE in the Start Menu and run the program. Type import cv2 in the command line and hit Enter. If no error is found then congratulations, you have just successfully built and installed openCV 3.0 with python 3.4+ bindings on Windows.

idle


Additional Notes:

  • You can also check the openCV version you have installed with python by using the cv2.__version__ command (as shown above).
  • One error I did receive was that the openCV dll could not be found when calling the command import cv2. This can be solved by adding the Release folder created during the build process to your system path (for me, it was C:\opencv\build\bin\Release)
  • In order to code python in Visual Studio, you need to use PTVS (Python Tools for Visual Studio). You can download PTVS from Microsoft’s PTVS page here.

Posted in OpenCV | Tagged: , , | Leave a Comment »

Bilateral Filtering

Posted by Hemprasad Y. Badgujar on September 14, 2015


Popular Filters

When smoothing or blurring images (the most popular goal of smoothing is to reduce noise), we can use diverse linear filters, because linear filters are easy to achieve, and are kind of fast, the most used ones are Homogeneous filter, Gaussian filter, Median filter, et al.

When performing a linear filter, we do nothing but output pixel’s value g(i,j)  which is determined as a weighted sum of input pixel values f(i+k, j+l):

g(i, j)=SUM[f(i+k, j+l) h(k, l)];

in which, h(k, l)) is called the kernel, which is nothing more than the coefficients of the filter.

Homogeneous filter is the most simple filter, each output pixel is the mean of its kernel neighbors ( all of them contribute with equal weights), and its kernel K looks like:

1

 Gaussian filter is nothing but using different-weight-kernel, in both x and y direction, pixels located in the middle would have bigger weight, and the weights decrease with distance from the neighborhood center, so pixels located on sides have smaller weight, its kernel K is something like (when kernel is 5*5):

gkernel

Median filter is something that replace each pixel’s value with the median of its neighboring pixels. This method is great when dealing with “salt and pepper noise“.

Bilateral Filter

By using all the three above filters to smooth image, we not only dissolve noise, but also smooth edges, which make edges less sharper, even disappear. To solve this problem, we can use a filter called bilateral filter, which is an advanced version of Gaussian filter, it introduces another weight that represents how two pixels can be close (or similar) to one another in value, and by considering both weights in image,  Bilateral filter can keep edges sharp while blurring image.

Let me show you the process by using this image which have sharp edge.

21

 

Say we are smoothing this image (we can see noise in the image), and now we are dealing with the pixel at middle of the blue rect.

22   23

Left-above picture is a Gaussian kernel, and right-above picture is Bilateral filter kernel, which considered both weight.

We can also see the difference between Gaussian filter and Bilateral filter by these pictures:

Say we have an original image with noise like this

32

 

By using Gaussian filter, the image is smoother than before, but we can see the edge is no longer sharp, a slope appeared between white and black pixels.

33

 

However, by using Bilateral filter, the image is smoother, the edge is sharp, as well.

31

OpenCV code

It is super easy to make these kind of filters in OpenCV:

1 //Homogeneous blur:
2 blur(image, dstHomo, Size(kernel_length, kernel_length), Point(-1,-1));
3 //Gaussian blur:
4 GaussianBlur(image, dstGaus, Size(kernel_length, kernel_length), 0, 0);
5 //Median blur:
6 medianBlur(image, dstMed, kernel_length);
7 //Bilateral blur:
8 bilateralFilter(image, dstBila, kernel_length, kernel_length*2, kernel_length/2);

and for each function, you can find more details in OpenCV Documentation

Test Images

Glad to use my favorite Van Gogh image :

vangogh

 

From left to right: Homogeneous blur, Gaussian blur, Median blur, Bilateral blur.

(click iamge to view full size version :p )

kernel length = 3:

homo3 Gaussian3 Median3 Bilateral3

kernel length = 9:

homo9 Gaussian9 Median9 Bilateral9
kernel length = 15:

homo15 Gaussian15 Median15 Bilateral15

kernel length = 23:

homo23 Gaussian23 Median23 Bilateral23
kernel length = 31:

homo31 Gaussian31 Median31 Bilateral31
kernel length = 49:

homo49 Gaussian49 Median49 Bilateral49
kernel length = 99:

homo99 Gaussian99 Median99 Bilateral99

Trackback URL.

Posted in C, Image / Video Filters, Image Processing, OpenCV, OpenCV, OpenCV Tutorial | Leave a Comment »

OpenCV: Color-spaces and splitting channels

Posted by Hemprasad Y. Badgujar on July 18, 2015


Conversion between color-spaces

Our goal here is to visualize each of the three channels of these color-spaces: RGB, HSV, YCrCb and Lab. In general, none of them are absolute color-spaces and the last three (HSV, YCrCb and Lab) are ways of encoding RGB information. Our images will be read in BGR (Blue-Green-Red), because of OpenCV defaults. For each of these color-spaces there is a mapping function and they can be found at OpenCV cvtColor documentation.
One important point is: OpenCV imshow() function will always assume that the Mat shown is in BGR color-space. Which means, we will always need to convert back to see what we want. Let’s start.

OpenCV Program: Split Channels (356 downloads )

HSV

While in BGR, an image is treated as an additive result of three base colors (blue, green and red), HSV stands for Hue, Saturation and Value (Brightness). We can say that HSV is a rearrangement of RGB in a cylindrical shape. The HSV ranges are:

  • 0 > H > 360 ⇒ OpenCV range = H/2 (0 > H > 180)
  • 0 > S > 1 ⇒ OpenCV range = 255*S (0 > S > 255)
  • 0 > V > 1 ⇒ OpenCV range = 255*V (0 > V > 255)

YCrCb or YCbCr

It is used widely in video and image compression schemes. The YCrCb stands for Luminance (sometimes you can see Y’ as luma), Red-difference and Blue-difference chroma components. The YCrCb ranges are:

  • 0 > Y > 255
  • 0 > Cr > 255
  • 0 > Cb > 255

L*a*b

In this color-opponent space, L stands for the Luminance dimension, while a and b are the color-opponent dimensions. The Lab ranges are:

  • 0 > L > 100 ⇒ OpenCV range = L*255/100 (1 > L > 255)
  • -127 > a > 127 ⇒ OpenCV range = a + 128 (1 > a > 255)
  • -127 > b > 127 ⇒ OpenCV range = b + 128 (1 > b > 255)

Splitting channels

All the color-spaces mentioned above were constructed using three channels (dimensions). It is a good exercise to visualize each of these channels and realize what they really store, because when I say that the third channel of HSV stores the brightness, what do you expect to see? Remember: a colored image is made of three-channels (in our cases) and when we see each of them separately, what do you think the output will be? If you said a grayscale image, you are correct! However, you might have seen these channels as colored images out there. So, how? For that, we need to choose a fixed value for the other two channels. Let’s do this!
To visualize each channel with color, I used the same values used on the Slides 53 to 65 from CS143, Lecture 03 from Brown University.

RGB or BGR

Original image (a) and its channels with color: blue (b), green (c) and red (d). On the second row, each channel in grayscale (single channel image), respectively.

HSV

Original image (a) and its channels with color: hue (b), saturation (c) and value or brightness (d). On the second row, each channel in grayscale (single channel image), respectively.

YCrCb or YCbCr

Original image (a) and its channels with color: luminance (b), red-difference (c) and blue difference (d). On the second row, each channel in grayscale (single channel image), respectively.

Lab or CIE Lab

Original image (a) and its channels with color: luminance (b), a-dimension (c) and b-dimension (d). On the second row, each channel in grayscale (single channel image), respectively.

Posted in Computer Vision, GPU (CUDA), OpenCV, OpenCV, OpenCV Tutorial | Tagged: , , | Leave a Comment »

build Tesseract 3.03 with Visual Studio 2013

Posted by Hemprasad Y. Badgujar on March 17, 2015


Compiling Tesseract 3.02.02 with Visual C++ 2008 (Express) is covered by the documentation whereas compiling Tesseract 3.03 isn’t covered at all, though.

Unfortunately newer versions of Tesseract also require a new version of Leptonica, a C library for image processing and image analysis applications, which in turn requires new versions of zlib, libpng, libtiff, libjpeg and giflib. Tesseract provides pre-compiled versions of Leptonica, which prevents you from having to collect and set up projects for all of these libraries in Visual Studio, which can be a tedious task.

Yesterday I found a project on GitHub that includes a Visual Studio solution file for all dependencies required to compile Tesseract 3.03: charlesw/tesseract-vs2012. While following the build instructions there, I stumpled over several build errors, which I could easily resolve by removing a definition. The necessary change is in my fork of the repository mentioned above.

This is a write-up of all steps that are required to compile Tesseract 3.03 with Visual Studio 2013.

Prerequisites

  1. Install Git.
  2. Install SVN. There are many versions of SVN. You can, for example, install the binary package from SlickSVN for free.
  3. Install Visual Studio 2013 for Windows Desktop (the Express version will be enough). You don’t need the optional features except for “Microsoft Foundation Classes for C++”.

Building the dependencies

  1. Create a directory where you want to compile Tesseract. In this document, I’ll assume it’s C:\Tesseract-Build\.
  2. Open a CMD prompt and change to that directory.
    cd \Tesseract-Build\
  3. Clone the dependencies repository from GitHub.
    git clone https://github.com/SGGS-IT/tesseract-ocr.git
  4. Open the “VS 2013 Developer Command Prompt”. (It can be found in the Start Menu.)
  5. Change to the newly cloned repository.
    cd \Tesseract-Build\tesseract-vs2012
  6. Build the dependencies
    msbuild build.proj
  7. You can close the “VS 2013 Developer Command Prompt”.

Building Tesseract

  1. Re-open the first command prompt and ensure it’s still in C:\Tesseract-Build\.
  2. Get the latest source from SVN.
    svn checkout http://tesseract-ocr.googlecode.com/svn/trunk/
  3. Change to the newly checked-out repository.
    cd tesseract-ocr
  4. Apply the patch provided in tesseract-vs2013.
    svn patch ..\tesseract-vs2012\vs2013+64bit_support.patch
  5. Copy both directories in C:\Tesseract-Build\tesseract-vs2012\release\ toC:\Tesseract-Build\. Now you should have
    • C:\Tesseract-Build\include\
    • C:\Tesseract-Build\lib\
  6. Open C:\Tesseract-Build\tesseract-ocr\vs2013\tesseract.sln with Visual Studio 2013.
  7. Press F7 on your keyboard. Both libtesseract303 and tesseract should compile without errors.

The Visual Studio solution file contains configurations for dynamic and static compilation as well as debugging and release configurations for both 32-Bit and 64-Bit. Select whichever configuration you need and recompile with F7.

You can find the compiled binaries in C:\Tesseract-Build\tesseract-ocr\vs2013\bin\.

Posted in Computer Softwares, Installation, Mixed, OpenCV, Project Related | Tagged: , , , , | Leave a Comment »

Assessing the pixel values of an image

Posted by Hemprasad Y. Badgujar on March 14, 2015



Assessing the pixel values of an image

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "iostream"
 
using namespace cv;
using namespace std;
 
int main( )
{
 
 Mat src1;
 src1 = imread("lena.jpg", CV_LOAD_IMAGE_COLOR); 
 namedWindow( "Original image", CV_WINDOW_AUTOSIZE ); 
 imshow( "Original image", src1 ); 
 
 Mat gray;
 cvtColor(src1, gray, CV_BGR2GRAY);
 namedWindow( "Gray image", CV_WINDOW_AUTOSIZE ); 
 imshow( "Gray image", gray );
 
 // know the number of channels the image has
 cout<<"original image channels: "<<src1.channels()<<"gray image="" channels:="" "<="" *******************="" read="" the="" pixel="" intensity="" *********************="" single="" channel="" grey="" scale="" (type="" 8uc1)="" and="" coordinates="" x="5" y="2" by="" convention,="" {row="" number="y}" {column="" intensity.val[0]="" contains="" a="" value="" from="" 0="" to="" 255="" scalar="" intensity1="gray.at(2," 5);="" cout="" <<="" "intensity=" << endl << " "="" intensity1.val[0]="" endl="" endl;="" 3="" with="" bgr="" color="" 8uc3)="" values="" can="" be="" stored="" in="" "int"="" or="" "uchar".="" here="" int="" is="" used.="" vec3b="" intensity2="src1.at(10,15);" blue="intensity2.val[0];" green="intensity2.val[1];" red="intensity2.val[2];" write="" **********************="" this="" an="" example="" opencv="" 2.4.6.0="" documentation="" mat="" h(10,="" 10,="" cv_64f);="" for(int="" i="0;" <="" h.rows;="" i++)="" j="0;" h.cols;="" j++)="" h.at(i,j)="1./(i+j+1);" cout<<h<<endl<<endl;="" modify="" pixels="" of="" for="" (int="" {="" j<src1.cols;="" src1.at<vec3b="">(i,j)[0] = 0;
 src1.at(i,j)[1] = 200;
 src1.at(i,j)[2] = 0; 
 }
 }
 namedWindow( "Modify pixel", CV_WINDOW_AUTOSIZE ); 
 imshow( "Modify pixel", src1 );
 
 waitKey(0); 
 return 0;
}

Posted in OpenCV, OpenCV Tutorial | Tagged: , , , , | Leave a Comment »

Detect and Track Objects

Posted by Hemprasad Y. Badgujar on January 20, 2015


Detect and Track Objects With OpenCV

In the following, I made an overview of tutorials and guides to getting strted how to use OpenCV for detection and tracking objects. OpenCV is a library for computer visions designed for analyze, process, and understand the objects from images aiming to produce information.

  • OpenCV Tutorials – comprehensive list with basic OpenCV tutorials and source code based on the OpenCV library;
  • Object Detection & Tracking Using Color – example of application where OpenCV is used to detect objects based on color differences;
  • Face Detection Using OpenCV – guide how to use OpenCV to detect one or more faces from the same image;
  • SURF in OpenCV – tutorial how to use SURF algorithm designed to detect key-points and descriptors in images;
  • Introduction to Face Detection and Face Recognition – face detection and recognition are two of the most common applications in computer vision from robotics, and this tutorial present the steps how a face is detected and recognized from images;
  • Find Objects with a Webcam – using a simple webcam mounted on a robot and the Simple Qt interface designed to work with OpenCV, as you can see in this tutorial any object can be detected and tracked in images;
  • Features 2D + Homography to Find a Known Object – tutorial with programming code and explanation in order to use two important functions included in OpenCV. These two functions – findHomography and perspectiveTransform – are used to find objects in images. The findHomography is a function based on a technique called Key-point Matching, while the perspectiveTransform is an advanced class capable of mapping the points from an image;
  • Back Projection – tutorial based on calcBackProject function designed to calculate the back project of the histogram;
  • Tracking Colored Objects in OpenCV – tutorial for detection and tracking the colored objects from images using the OpenCV library;
  • OpenCV Tutorials – Based on “Learning OpenCV – Computer Vision with the OpenCV Library” – in order to be familiar with computer vision concepts, these tutorials can be useful for beginner and advanced users to start building applications or to improve the skills;
  • Image Processing on Pandaboard using OpenCV and Kinect – in this presentation you can find information about image processing with a Pandaboard single board computer using the Kinect sensor and the OpenCV library;
  • Video Capture using OpenCV with VC++ – OpenCV library can be integrated with Visual Studio and this article explain you as a programmer how to use the Visual C++ together with OpenCV;

Tutorials for Detecting and Tracking Objects with Mobile Devices

Mobile devices such as smartphones and tablets with iOS or Android operating systems can be integrated into robots and used to detect and track objects. Below is an overview of tutorials with comprehensive information for tracking objects using different mobile devices.

 Particle filter based trackers

  • Particle Filter Color Tracker [Link 1]
    • Matlab and c/c++ code.
    • Key words: region tracker, color histogram, ellipsoidal region, particle filter, SIR resampling.
  • Region Tracker based on a color Particle Filter [Link 1] [Example]
    • Matlab and c/c++ code.
    • Key words: region tracker, color histogram, ellipsoidal region, particle filter, SIR resampling.
  • Region Tracker based on an intensity Particle Filter [Link]
    • Matlab and c/c++ code.
    • Key words: region tracker, intensity histogram, ellipsoidal region, particle filter, SIR resampling.
  • Particle Filter Object Tracking [Link]
    • C/C++.

Mean shift based trackers

  • Scale and Orientation Adaptive Mean Shift Tracking. [Link]
    • Matlab.
  • Robust Mean Shift  Tracking with Corrected Background-Weighted Histogram. [Link]
    • Matlab.
  • Robust Object Tracking using Joint Color-Texture Histogram. [Link]
    • Matlab.
  • Tracking moving video objects using mean-shift algorithm. [Link]
    • Matlab.
  • Mean-shift Based Moving Object Tracker [Link]
    • C/C++.
  • Mean-Shift Video Tracking [Link]
    • Matlab.
  • Gray scale mean shift algorithm for tracking. [Link]
    • Matlab.
  • Mean shift tracking algorithm for tracking [Link]
    • Matlab.

Deformable/articulable object trackers

  • Visual Tracking with Integral Histograms and Articulating Blocks [Link]
    • Matlab and c/c++ code
    • Key words: region tracker, intensity histogram, multi-rectangular regions, integral histogram, exhaustive search, graph cut segmentation.

Appearance learning based trackers

  • Robust Object Tracking with Online Multiple Instance Learning. [Link]
    • C/C++.
  • Visual Tracking via Adaptive Structural Local Sparse Appearance Model. [Link]
    • Matlab.
  • Online Discriminative Object Tracking with Local Sparse Representation. [Link]
    • Matlab
  • Superpixel Tracking. [Link]
    • Matlab.
  • Online Multiple Support Instance Tracking. [Link]
    • Matlab.
  • Incremental Learning for Robust Visual Tracking. [Link]
    • Matlab.
  • Tracking with Online Multiple Instance Learning (MILTrack). [Link]
    • C/C++, OpenCV
  • Predator. [Link]
    • Matlab.
  • Object Tracking via Partial Least Squares Analysis. [Link]
    • Matlab.
  • Robust Object Tracking via Sparsity-based Collaborative Model. [Link]
    • Matlab.
  • On-line boosting trackers. [Link]
    • C/C++.

Advanced appearance model based trackers

  • Real-Time Compressive Tracking [Link]

Resources

Below is a list with resources including OpenCV documentation, libraries, and OpenCV compatible tools.

Posted in Computer Vision, OpenCV, OpenCV, OpenCV Tutorial | Tagged: , , , | Leave a Comment »

Draw graphs using OpenCV

Posted by Hemprasad Y. Badgujar on January 20, 2015


 basic graphing library to allow plotting graphs on the screen or into an image using OpenCV. This can be very useful to view the contents of a numerical array, such as during testing of an algorithm.

This “library” is just a collection of functions that can be used to simply plot a graph of an array in its own window, or to overlay graphs into existing an IplImage. This makes it both easy to use and powerful enough for more complex uses such as combining multiple graphs into one.

Showing a simple graph of an array

Here is a simple example to see a graph of a float array in a new window, by calling:

showFloatGraph("Rotation Angle", floatArray, numFloats );


The same sort of graph could be shown from a std::vector of floats or ints or even a byte array:

showFloatGraph("Rotation Angle", &floatVector[0], floatVector.size());
showIntGraph("Rotation Angle", &intVector[0], intVector.size());
showUCharGraph("Pixel Values", pixelData, numPixels);

Note that the window will only stay active for half a second by default. To make it wait until the user hits a key, add “0” as the wait time, by calling:

showIntGraph("Rotation Angle", &intVector[0], intVector.size(), 0);

Drawing multiple graphs into an IplImage

It is also possible to draw a graph into an existing image of your own, such as to overlay a graph on top of your work, or to graph multiple values in the same graph:

IplImage *graphImg = drawFloatGraph(&floatVec1[0], floatVec1.size(), NULL,
	-25,25, 400,180, "X Angle (blue is truth, green is POSIT)" );
drawFloatGraph(&floatVec2[0], floatVec2.size(), graphImg, -25,25, 400,180);
cvSaveImage("my_graph.jpg", graphImg);
cvReleaseImage(&graphImg);

Overlaying graphs onto an existing IplImage

You can also plot the graphs onto existing images, as shown here:

IplImage *bgImg = cvLoadImage("my_background_photo.jpg");
int w = bgImg->width;
int h = bgImg->height;
drawFloatGraph(floatArray, numFloats, bgImg, -25,25, w, h, "Yaw (in degrees)");
showImage(bgImg, 0, "Rotation Angle");
cvReleaseImage(&bgImg);

Here is a more complex example, where 3 graphs are drawn over a larger photo:

IplImage *dstImage = cvLoadImage("my_background_photo.jpg");
int W = 400, H = 200;
float RANGE = 25.0f;
char *name;

name = "X Angle (blue is truth, green is POSIT)";
setGraphColor(0);	// Start with a blue graph
// Set the position of the graph within the image
CvRect region = cvRect(dstImage->width-1 - W-10, 10, W+20, H+20);
cvSetImageROI(dstImage, region);
drawFloatGraph(&vecX1[0], vecX1.size(), dstImage, -RANGE,+RANGE, W,H, name);
drawFloatGraph(&vecX2[0], vecX2.size(), dstImage, -RANGE,+RANGE, W,H);

name = "Y Angle (blue is truth, green is POSIT)";
setGraphColor(0);	// Start with a blue graph
// Set the position of the graph within the image
region.y += H+20;
cvSetImageROI(dstImage, region);
drawFloatGraph(&vecY1[0], vecY1.size(), dstImage, -RANGE,+RANGE, W,H, name);
drawFloatGraph(&vecY2[0], vecY2.size(), dstImage, -RANGE,+RANGE, W,H);

name = "Z Angle (blue is truth, green is POSIT)";
setGraphColor(0);	// Start with a blue graph
// Set the position of the graph within the image
region.y += H+20;
cvSetImageROI(dstImage, region);
drawFloatGraph(&vecZ1[0], vecZ1.size(), dstImage, -RANGE,+RANGE, W,H, name);
drawFloatGraph(&vecZ2[0], vecZ2.size(), dstImage, -RANGE,+RANGE, W,H);

cvResetImageROI(dstImage);

showImage(dstImage);
cvReleaseImage(&dstImage);

 


//------------------------------------------------------------------------------
"ImageUtils.cpp",
//------------------------------------------------------------------------------

#define USE_HIGHGUI // Enable this to display graph windows using OpenCV's HighGUI. (Supports Windows, Linux & Mac, but not iPhone).

#include <stdio.h>
#include <iostream>
//#include <tchar.h>

// OpenCV
#include <cv.h>
#include <cxcore.h>
#ifdef USE_HIGHGUI
#include <highgui.h>
#endif

#ifndef UCHAR
typedef unsigned char UCHAR;
#endif

#include "GraphUtils.h"

//------------------------------------------------------------------------------
// Graphing functions
//------------------------------------------------------------------------------
const CvScalar BLACK = CV_RGB(0,0,0);
const CvScalar WHITE = CV_RGB(255,255,255);
const CvScalar GREY = CV_RGB(150,150,150);

int countGraph = 0; // Used by 'getGraphColor()'
CvScalar customGraphColor;
int usingCustomGraphColor = 0;

// Get a new color to draw graphs. Will use the latest custom color, or change between blue, green, red, dark-blue, dark-green and dark-red until a new image is created.
CvScalar getGraphColor(void)
{
if (usingCustomGraphColor) {
usingCustomGraphColor = 0;
return customGraphColor;
}

countGraph++;
switch (countGraph) {
case 1: return CV_RGB(60,60,255); // light-blue
case 2: return CV_RGB(60,255,60); // light-green
case 3: return CV_RGB(255,60,40); // light-red
case 4: return CV_RGB(0,210,210); // blue-green
case 5: return CV_RGB(180,210,0); // red-green
case 6: return CV_RGB(210,0,180); // red-blue
case 7: return CV_RGB(0,0,185); // dark-blue
case 8: return CV_RGB(0,185,0); // dark-green
case 9: return CV_RGB(185,0,0); // dark-red
default:
countGraph = 0; // start rotating through colors again.
return CV_RGB(200,200,200); // grey
}
}
// Call 'setGraphColor()' to reset the colors that will be used for graphs.
void setGraphColor(int index)
{
countGraph = index;
usingCustomGraphColor = 0; // dont use a custom color.
}
// Specify the exact color that the next graph should be drawn as.
void setCustomGraphColor(int R, int B, int G)
{
customGraphColor = CV_RGB(R, G, B);
usingCustomGraphColor = 1; // show that it will be used.
}

// Draw the graph of an array of floats into imageDst or a new image, between minV & maxV if given.
// Remember to free the newly created image if imageDst is not given.
IplImage* drawFloatGraph(const float *arraySrc, int nArrayLength, IplImage *imageDst, float minV, float maxV, int width, int height, char *graphLabel, bool showScale)
{
int w = width;
int h = height;
int b = 10; // border around graph within the image
if (w <= 20)
w = nArrayLength + b*2; // width of the image
if (h <= 20)
h = 220;

int s = h - b*2;// size of graph height
float xscale = 1.0;
if (nArrayLength > 1)
xscale = (w - b*2) / (float)(nArrayLength-1); // horizontal scale
IplImage *imageGraph; // output image

// Get the desired image to draw into.
if (!imageDst) {
// Create an RGB image for graphing the data
imageGraph = cvCreateImage(cvSize(w,h), 8, 3);

// Clear the image
cvSet(imageGraph, WHITE);
}
else {
// Draw onto the given image.
imageGraph = imageDst;
}
if (!imageGraph) {
std::cerr << "ERROR in drawFloatGraph(): Couldn't create image of " << w << " x " << h << std::endl;
exit(1);
}
CvScalar colorGraph = getGraphColor(); // use a different color each time.

// If the user didnt supply min & mav values, find them from the data, so we can draw it at full scale.
if (fabs(minV) < 0.0000001f && fabs(maxV) < 0.0000001f) {
for (int i=0; i
float v = (float)arraySrc[i];
if (v < minV)
minV = v;
if (v > maxV)
maxV = v;
}
}
float diffV = maxV - minV;
if (diffV == 0)
diffV = 0.00000001f; // Stop a divide-by-zero error
float fscale = (float)s / diffV;

// Draw the horizontal & vertical axis
int y0 = cvRound(minV*fscale);
cvLine(imageGraph, cvPoint(b,h-(b-y0)), cvPoint(w-b, h-(b-y0)), BLACK);
cvLine(imageGraph, cvPoint(b,h-(b)), cvPoint(b, h-(b+s)), BLACK);

// Write the scale of the y axis
CvFont font;
cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.55,0.7, 0,1,CV_AA); // For OpenCV 1.1
if (showScale) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.5,0.6, 0,1, CV_AA); // For OpenCV 2.0
CvScalar clr = GREY;
char text[16];
sprintf_s(text, sizeof(text)-1, "%.1f", maxV);
cvPutText(imageGraph, text, cvPoint(1, b+4), &font, clr);
// Write the scale of the x axis
sprintf_s(text, sizeof(text)-1, "%d", (nArrayLength-1) );
cvPutText(imageGraph, text, cvPoint(w-b+4-5*strlen(text), (h/2)+10), &font, clr);
}

// Draw the values
CvPoint ptPrev = cvPoint(b,h-(b-y0)); // Start the lines at the 1st point.
for (int i=0; i
int y = cvRound((arraySrc[i] - minV) * fscale); // Get the values at a bigger scale
int x = cvRound(i * xscale);
CvPoint ptNew = cvPoint(b+x, h-(b+y));
cvLine(imageGraph, ptPrev, ptNew, colorGraph, 1, CV_AA); // Draw a line from the previous point to the new point
ptPrev = ptNew;
}

// Write the graph label, if desired
if (graphLabel != NULL && strlen(graphLabel) > 0) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN, 0.5,0.7, 0,1,CV_AA);
cvPutText(imageGraph, graphLabel, cvPoint(30, 10), &font, CV_RGB(0,0,0)); // black text
}

return imageGraph;
}

// Draw the graph of an array of ints into imageDst or a new image, between minV & maxV if given.
// Remember to free the newly created image if imageDst is not given.
IplImage* drawIntGraph(const int *arraySrc, int nArrayLength, IplImage *imageDst, int minV, int maxV, int width, int height, char *graphLabel, bool showScale)
{
int w = width;
int h = height;
int b = 10; // border around graph within the image
if (w <= 20)
w = nArrayLength + b*2; // width of the image
if (h <= 20)
h = 220;

int s = h - b*2;// size of graph height
float xscale = 1.0;
if (nArrayLength > 1)
xscale = (w - b*2) / (float)(nArrayLength-1); // horizontal scale
IplImage *imageGraph; // output image

// Get the desired image to draw into.
if (!imageDst) {
// Create an RGB image for graphing the data
imageGraph = cvCreateImage(cvSize(w,h), 8, 3);

// Clear the image
cvSet(imageGraph, WHITE);
}
else {
// Draw onto the given image.
imageGraph = imageDst;
}
if (!imageGraph) {
std::cerr << "ERROR in drawIntGraph(): Couldn't create image of " << w << " x " << h << std::endl;
exit(1);
}
CvScalar colorGraph = getGraphColor(); // use a different color each time.

// If the user didnt supply min & mav values, find them from the data, so we can draw it at full scale.
if (minV == 0 && maxV == 0) {
for (int i=0; i
int v = arraySrc[i];
if (v < minV)
minV = v;
if (v > maxV)
maxV = v;
}
}
int diffV = maxV - minV;
if (diffV == 0)
diffV = 1; // Stop a divide-by-zero error
float fscale = (float)s / (float)diffV;

// Draw the horizontal & vertical axis
int y0 = cvRound(minV*fscale);
cvLine(imageGraph, cvPoint(b,h-(b-y0)), cvPoint(w-b, h-(b-y0)), BLACK);
cvLine(imageGraph, cvPoint(b,h-(b)), cvPoint(b, h-(b+s)), BLACK);

// Write the scale of the y axis
CvFont font;
cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.55,0.7, 0,1,CV_AA); // For OpenCV 1.1
if (showScale) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.5,0.6, 0,1, CV_AA); // For OpenCV 2.0
CvScalar clr = GREY;
char text[16];
sprintf_s(text, sizeof(text)-1, "%.1f", maxV);
cvPutText(imageGraph, text, cvPoint(1, b+4), &font, clr);
// Write the scale of the x axis
sprintf_s(text, sizeof(text)-1, "%d", (nArrayLength-1) );
cvPutText(imageGraph, text, cvPoint(w-b+4-5*strlen(text), (h/2)+10), &font, clr);
}

// Draw the values
CvPoint ptPrev = cvPoint(b,h-(b-y0)); // Start the lines at the 1st point.
for (int i=0; i
int y = cvRound((arraySrc[i] - minV) * fscale); // Get the values at a bigger scale
int x = cvRound(i * xscale);
CvPoint ptNew = cvPoint(b+x, h-(b+y));
cvLine(imageGraph, ptPrev, ptNew, colorGraph, 1, CV_AA); // Draw a line from the previous point to the new point
ptPrev = ptNew;
}

// Write the graph label, if desired
if (graphLabel != NULL && strlen(graphLabel) > 0) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN, 0.5,0.7, 0,1,CV_AA);
cvPutText(imageGraph, graphLabel, cvPoint(30, 10), &font, CV_RGB(0,0,0)); // black text
}

return imageGraph;
}

// Draw the graph of an array of uchars into imageDst or a new image, between minV & maxV if given..
// Remember to free the newly created image if imageDst is not given.
IplImage* drawUCharGraph(const uchar *arraySrc, int nArrayLength, IplImage *imageDst, int minV, int maxV, int width, int height, char *graphLabel, bool showScale)
{
int w = width;
int h = height;
int b = 10; // border around graph within the image
if (w <= 20)
w = nArrayLength + b*2; // width of the image
if (h <= 20)
h = 220;

int s = h - b*2;// size of graph height
float xscale = 1.0;
if (nArrayLength > 1)
xscale = (w - b*2) / (float)(nArrayLength-1); // horizontal scale
IplImage *imageGraph; // output image

// Get the desired image to draw into.
if (!imageDst) {
// Create an RGB image for graphing the data
imageGraph = cvCreateImage(cvSize(w,h), 8, 3);

// Clear the image
cvSet(imageGraph, WHITE);
}
else {
// Draw onto the given image.
imageGraph = imageDst;
}
if (!imageGraph) {
std::cerr << "ERROR in drawUCharGraph(): Couldn't create image of " << w << " x " << h << std::endl;
exit(1);
}
CvScalar colorGraph = getGraphColor(); // use a different color each time.

// If the user didnt supply min & mav values, find them from the data, so we can draw it at full scale.
if (minV == 0 && maxV == 0) {
for (int i=0; i<nArrayLength; i++) {
int v = arraySrc[i];
if (v < minV)
minV = v;
if (v > maxV)
maxV = v;
}
}
int diffV = maxV - minV;
if (diffV == 0)
diffV = 1; // Stop a divide-by-zero error
float fscale = (float)s / (float)diffV;

// Draw the horizontal & vertical axis
int y0 = cvRound(minV*fscale);
cvLine(imageGraph, cvPoint(b,h-(b-y0)), cvPoint(w-b, h-(b-y0)), BLACK);
cvLine(imageGraph, cvPoint(b,h-(b)), cvPoint(b, h-(b+s)), BLACK);

// Write the scale of the y axis
CvFont font;
cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.55,0.7, 0,1,CV_AA); // For OpenCV 1.1
if (showScale) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.5,0.6, 0,1, CV_AA); // For OpenCV 2.0
CvScalar clr = GREY;
char text[16];
sprintf_s(text, sizeof(text)-1, "%.1f", maxV);
cvPutText(imageGraph, text, cvPoint(1, b+4), &font, clr);
// Write the scale of the x axis
sprintf_s(text, sizeof(text)-1, "%d", (nArrayLength-1) );
cvPutText(imageGraph, text, cvPoint(w-b+4-5*strlen(text), (h/2)+10), &font, clr);
}

// Draw the values
CvPoint ptPrev = cvPoint(b,h-(b-y0)); // Start the lines at the 1st point.
for (int i=0; i<nArrayLength; i++) {
int y = cvRound((arraySrc[i] - minV) * fscale); // Get the values at a bigger scale
int x = cvRound(i * xscale);
CvPoint ptNew = cvPoint(b+x, h-(b+y));
cvLine(imageGraph, ptPrev, ptNew, colorGraph, 1, CV_AA); // Draw a line from the previous point to the new point
ptPrev = ptNew;
}

// Write the graph label, if desired
if (graphLabel != NULL && strlen(graphLabel) > 0) {
//cvInitFont(&font,CV_FONT_HERSHEY_PLAIN, 0.5,0.7, 0,1,CV_AA);
cvPutText(imageGraph, graphLabel, cvPoint(30, 10), &font, CV_RGB(0,0,0)); // black text
}

return imageGraph;
}

// Display a graph of the given float array.
// If background is provided, it will be drawn into, for combining multiple graphs using drawFloatGraph().
// Set delay_ms to 0 if you want to wait forever until a keypress, or set it to 1 if you want it to delay just 1 millisecond.
void showFloatGraph(const char *name, const float *arraySrc, int nArrayLength, int delay_ms, IplImage *background)
{
#ifdef USE_HIGHGUI
// Draw the graph
IplImage *imageGraph = drawFloatGraph(arraySrc, nArrayLength, background);

// Display the graph into a window
cvNamedWindow( name );
cvShowImage( name, imageGraph );

cvWaitKey( 10 ); // Note that cvWaitKey() is required for the OpenCV window to show!
cvWaitKey( delay_ms ); // Wait longer to make sure the user has seen the graph

cvReleaseImage(&imageGraph);
#endif
}

// Display a graph of the given int array.
// If background is provided, it will be drawn into, for combining multiple graphs using drawIntGraph().
// Set delay_ms to 0 if you want to wait forever until a keypress, or set it to 1 if you want it to delay just 1 millisecond.
void showIntGraph(const char *name, const int *arraySrc, int nArrayLength, int delay_ms, IplImage *background)
{
#ifdef USE_HIGHGUI
// Draw the graph
IplImage *imageGraph = drawIntGraph(arraySrc, nArrayLength, background);

// Display the graph into a window
cvNamedWindow( name );
cvShowImage( name, imageGraph );

cvWaitKey( 10 ); // Note that cvWaitKey() is required for the OpenCV window to show!
cvWaitKey( delay_ms ); // Wait longer to make sure the user has seen the graph

cvReleaseImage(&imageGraph);
#endif
}

// Display a graph of the given unsigned char array.
// If background is provided, it will be drawn into, for combining multiple graphs using drawUCharGraph().
// Set delay_ms to 0 if you want to wait forever until a keypress, or set it to 1 if you want it to delay just 1 millisecond.
void showUCharGraph(const char *name, const uchar *arraySrc, int nArrayLength, int delay_ms, IplImage *background)
{
#ifdef USE_HIGHGUI
// Draw the graph
IplImage *imageGraph = drawUCharGraph(arraySrc, nArrayLength, background);

// Display the graph into a window
cvNamedWindow( name );
cvShowImage( name, imageGraph );

cvWaitKey( 10 ); // Note that cvWaitKey() is required for the OpenCV window to show!
cvWaitKey( delay_ms ); // Wait longer to make sure the user has seen the graph

cvReleaseImage(&imageGraph);
#endif
}

// Simple helper function to easily view an image, with an optional pause.
void showImage(const IplImage *img, int delay_ms, char *name)
{
#ifdef USE_HIGHGUI
if (!name)
name = "Image";
cvNamedWindow(name, CV_WINDOW_AUTOSIZE);
cvShowImage(name, img);
cvWaitKey(delay_ms);
#endif
}
<pre>

Header File

//------------------------------------------------------------------------------
// Graphing functions for OpenCV. Part of "ImageUtils.h
//------------------------------------------------------------------------------

#ifndef GRAPH_UTILS_H
#define GRAPH_UTILS_H

#ifdef __cplusplus
extern "C"
{
#endif

// Allow 'bool' variables in both C and C++ code.
#ifdef __cplusplus
#else
typedef int bool;
#define true (1)
#define false (0)
#endif

#ifdef __cplusplus
#define DEFAULT(val) = val
#else
#define DEFAULT(val)
#endif

//------------------------------------------------------------------------------
// Graphing functions
//------------------------------------------------------------------------------

// Draw the graph of an array of floats into imageDst or a new image, between minV & maxV if given.
// Remember to free the newly created image if imageDst is not given.
IplImage* drawFloatGraph(const float *arraySrc, int nArrayLength, IplImage *imageDst DEFAULT(0), float minV DEFAULT(0.0), float maxV DEFAULT(0.0), int width DEFAULT(0), int height DEFAULT(0), char *graphLabel DEFAULT(0), bool showScale DEFAULT(true));

// Draw the graph of an array of ints into imageDst or a new image, between minV & maxV if given.
// Remember to free the newly created image if imageDst is not given.
IplImage* drawIntGraph(const int *arraySrc, int nArrayLength, IplImage *imageDst DEFAULT(0), int minV DEFAULT(0), int maxV DEFAULT(0), int width DEFAULT(0), int height DEFAULT(0), char *graphLabel DEFAULT(0), bool showScale DEFAULT(true));

// Draw the graph of an array of uchars into imageDst or a new image, between minV & maxV if given.
// Remember to free the newly created image if imageDst is not given.
IplImage* drawUCharGraph(const uchar *arraySrc, int nArrayLength, IplImage *imageDst DEFAULT(0), int minV DEFAULT(0), int maxV DEFAULT(0), int width DEFAULT(0), int height DEFAULT(0), char *graphLabel DEFAULT(0), bool showScale DEFAULT(true));

// Display a graph of the given float array.
// If background is provided, it will be drawn into, for combining multiple graphs using drawFloatGraph().
// Set delay_ms to 0 if you want to wait forever until a keypress, or set it to 1 if you want it to delay just 1 millisecond.
void showFloatGraph(const char *name, const float *arraySrc, int nArrayLength, int delay_ms DEFAULT(500), IplImage *background DEFAULT(0));

// Display a graph of the given int array.
// If background is provided, it will be drawn into, for combining multiple graphs using drawIntGraph().
// Set delay_ms to 0 if you want to wait forever until a keypress, or set it to 1 if you want it to delay just 1 millisecond.
void showIntGraph(const char *name, const int *arraySrc, int nArrayLength, int delay_ms DEFAULT(500), IplImage *background DEFAULT(0));

// Display a graph of the given unsigned char array.
// If background is provided, it will be drawn into, for combining multiple graphs using drawUCharGraph().
// Set delay_ms to 0 if you want to wait forever until a keypress, or set it to 1 if you want it to delay just 1 millisecond.
void showUCharGraph(const char *name, const uchar *arraySrc, int nArrayLength, int delay_ms DEFAULT(500), IplImage *background DEFAULT(0));

// Simple helper function to easily view an image, with an optional pause.
void showImage(const IplImage *img, int delay_ms DEFAULT(0), char *name DEFAULT(0));

// Call 'setGraphColor(0)' to reset the colors that will be used for graphs.
void setGraphColor(int index DEFAULT(0));
// Specify the exact color that the next graph should be drawn as.
void setCustomGraphColor(int R, int B, int G);

#if defined (__cplusplus)
}
#endif

#endif //end GRAPH_UTILS
<pre>

Posted in OpenCV | Leave a Comment »

Writing Video to a File

Posted by Hemprasad Y. Badgujar on January 19, 2015



</pre>
<pre></pre>
<pre></pre>
<pre>#include <opencv\highgui.h>
#include <opencv\cv.h>
#include 

using namespace cv;
using namespace std;

string intToString(int number){

	std::stringstream ss;
	ss << number;
	return ss.str();
}

int main(int argc, char* argv[])
{

	VideoCapture cap(0); // open the video camera no. 0

	if (!cap.isOpened())  // if not success, exit program
	{
		cout << "ERROR INITIALIZING VIDEO CAPTURE" << endl;
		return -1;
	}

	char* windowName = "Webcam Feed";
	namedWindow(windowName,CV_WINDOW_AUTOSIZE); //create a window to display our webcam feed

	while (1) {

		Mat frame;

		bool bSuccess = cap.read(frame); // read a new frame from camera feed

		if (!bSuccess) //test if frame successfully read
		{
			cout << "ERROR READING FRAME FROM CAMERA FEED" << endl;
			break;
		}

		imshow(windowName, frame); //show the frame in "MyVideo" window

		//listen for 10ms for a key to be pressed
		switch(waitKey(10)){

		case 27:
			//'esc' has been pressed (ASCII value for 'esc' is 27)
			//exit program.
			return 0;

		}

	}

	return 0;

}

 

</pre>
<pre>#include <opencv\highgui.h>
#include <opencv\cv.h>
#include 

using namespace cv;
using namespace std;

string intToString(int number){

	std::stringstream ss;
	ss << number;
	return ss.str();
}

int main(int argc, char* argv[])
{
	bool recording = false;
	bool startNewRecording = false;
	int inc=0;
	bool firstRun = true;

	VideoCapture cap(0); // open the video camera no. 0
	VideoWriter oVideoWriter;//create videoWriter object, not initialized yet

	if (!cap.isOpened())  // if not success, exit program
	{
		cout << "ERROR: Cannot open the video file" << endl;
		return -1;
	}

	namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"

	double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
	double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video

	cout << "Frame Size = " << dWidth << "x" << dHeight << endl;

	//set framesize for use with videoWriter
	Size frameSize(static_cast(dWidth), static_cast(dHeight));

	while (1) {

		if(startNewRecording==true){

			oVideoWriter  = VideoWriter("D:/MyVideo"+intToString(inc)+".avi", CV_FOURCC('D', 'I', 'V', '3'), 20, frameSize, true); //initialize the VideoWriter object
			//oVideoWriter  = VideoWriter("D:/MyVideo"+intToString(inc)+".avi", (int)cap.get(CV_CAP_PROP_FOURCC), 20, frameSize, true); //initialize the VideoWriter object 

			recording = true;
			startNewRecording = false;
			cout<<"New video file created D:/MyVideo"+intToString(inc)+".avi "<
<pre>

 

Posted in Computer Vision, OpenCV, OpenCV, OpenCV Tutorial | Tagged: , , , | Leave a Comment »

People Detection

Posted by Hemprasad Y. Badgujar on January 19, 2015


People Detection Sample from OpenCV

</pre>
<pre class="cpp">#include <opencv2/opencv.hpp>
 
using namespace cv;
 
int main (int argc, const char * argv[])
{
    VideoCapture cap(0);
    cap.set(CV_CAP_PROP_FRAME_WIDTH, 320);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
 
    if (!cap.isOpened())
        return -1;
 
    Mat img;
    namedWindow("opencv", CV_WINDOW_AUTOSIZE);
    HOGDescriptor hog;
    hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
 
    while (true)
    {
        cap >> img;
        if (img.empty())
            continue;
 
        vector found, found_filtered;
        hog.detectMultiScale(img, found, 0, Size(8,8), Size(32,32), 1.05, 2);
        size_t i, j;
        for (i=0; i<found.size(); i++)="" {="" rect="" r="found[i];" for="" (j="0;" j<found.size();="" j++)="" if="" (j!="i" &&="" (r="" &="" found[j])="=" r)="" break;="" found.size())="" found_filtered.push_back(r);="" }=""  ="" (i="0;" i<found_filtered.size();="" r.x="" +="cvRound(r.width*0.1);" r.width="cvRound(r.width*0.8);" r.y="" r.height="cvRound(r.height*0.8);" rectangle(img,="" r.tl(),="" r.br(),="" scalar(0,255,0),="" 3);="" imshow("opencv",="" img);="" (waitkey(10)="">=0)
            break;
    }
    return 0;
}</pre>
<pre>

Posted in Computer Vision, OpenCV, OpenCV, OpenCV Tutorial | Tagged: | Leave a Comment »

 
Extracts from a Personal Diary

dedicated to the life of a silent girl who eventually learnt to open up

Num3ri v 2.0

I miei numeri - seconda versione

ThuyDX

Just another WordPress.com site

Algunos Intereses de Abraham Zamudio Chauca

Matematica, Linux , Programacion Serial , Programacion Paralela (CPU - GPU) , Cluster de Computadores , Software Cientifico

josephdung

thoughts...

Tech_Raj

A great WordPress.com site

Travel tips

Travel tips

Experience the real life.....!!!

Shurwaat achi honi chahiye ...

Ronzii's Blog

Just your average geek's blog

Karan Jitendra Thakkar

Everything I think. Everything I do. Right here.

VentureBeat

News About Tech, Money and Innovation

Chetan Solanki

Helpful to u, if u need it.....

ScreenCrush

Explorer of Research #HEMBAD

managedCUDA

Explorer of Research #HEMBAD

siddheshsathe

A great WordPress.com site

Ari's

This is My Space so Dont Mess With IT !!

%d bloggers like this: