title: OpenCV, Python and C++:The application has requested the Runtime to terminate in an unusual way
body: <p>I have run into the error "The application has requested the Runtime to terminate in an unusual way", whilst trying to run a simple colour tracking program in Visual C++ using OpenCV. I should start by saying that my experience in C++ spans only the past week.</p>
  
  <p>Originally I developed a colour tracking program in Python that ran without any problems. Unfortunately, due to problems with the hardware this program was supposed to interface with, I have had to rewrite the  entire thing in C++ (which I do not know at all), since there is no support for Python. I tried a number of methods of communication between the Python and Visual C++ in order to try and avoid this, however, my limited knowledge led me to considerable confusion.</p>
  
  <p>The original Python code is here(shortened from three colours to a single colour for space purposes):</p>
  
  <pre><code># Import libraries.
  import cv2 #Import the openCV 2 library.
  import numpy as np #Import NumPy.
  from matplotlib.widgets import Slider #Import the slider widget from MatPlotLib.
  import csv #Import CSV.
  import serial #Import the serial library.
  
  def nothing(x):
      pass
  
  # Start capturing from the webcam.  
  cap = cv2.VideoCapture(2)           
  
  # HSV Sliders 
  Slider_win_red=np.zeros((450,768,3),np.uint8)
  cv2.namedWindow('Red Slider', flags=cv2.cv.CV_WINDOW_NORMAL)
  
  # Create a switch to toggle between slider input and preset bound values.
  switch_red='0 : On \n1 : Off'
  cv2.createTrackbar(switch_red, 'Red Slider',1,1,nothing)
  
  # Create  trackbars for HSV masking.
  # Minimum
  cv2.createTrackbar('H (Min)','Red Slider',90,180,nothing)
  cv2.createTrackbar('S (Min)','Red Slider',128,255,nothing)
  cv2.createTrackbar('V (Min)','Red Slider',128,255,nothing)
  # Maximum
  cv2.createTrackbar('H (Max)','Red Slider',90,180,nothing)
  cv2.createTrackbar('S (Max)','Red Slider',128,255,nothing)
  cv2.createTrackbar('V (Max)','Red Slider',128,255,nothing)
  
  # Process image to isolate tracked colour:   #
  while(1):
      #Take each frame.
      _, frame=cap.read()
  
      # Apply Gaussian Blur to the source image to reduce colour noise.
      blur = cv2.GaussianBlur(frame, (5,5), 0)
  
      # Convert BGR colour to HSV colour.
      hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)
  
      # Apply the colour masks.
      # If the switch is set to 0, use slider values.
      # Get the position of the switch.
      s_red = cv2.getTrackbarPos(switch_red,'Red Slider')
      if s_red ==0:
          # Get the current positions of the trackbars.
          # Lower blue boundary.
          Red_H_low=cv2.getTrackbarPos('H (Min)','Red Slider')
          Red_S_low=cv2.getTrackbarPos('S (Min)','Red Slider')
          Red_V_low=cv2.getTrackbarPos('V (Min)','Red Slider')
          # Upper blue boundary.
          Red_H_high=cv2.getTrackbarPos('H (Max)','Red Slider')
          Red_S_high=cv2.getTrackbarPos('S (Max)','Red Slider')
          Red_V_high=cv2.getTrackbarPos('V (Max)','Red Slider')
      # If the switch is set to 1, use preset values.    
      else:
          Red_H_low=0
          Red_S_low=10
          Red_V_low=200
          # Upper blue boundary.
          Red_H_high=20
          Red_S_high=80
          Red_V_high=255
  
      # Define the colour range to be extracted in HSV colour space.
      lower_red = np.array([Red_H_low,Red_S_low,Red_V_low],np.uint8) # Specified in HSV range H: 0-180, S: 0-255, V: 0-255. Lower bound original(105,50,50)
      upper_red = np.array([Red_H_high,Red_S_high,Red_V_high],np.uint8) # Upper bound original(125,255,255)
  
      # Define the red binary mask.
      red_binary=cv2.inRange(hsv, lower_red, upper_red)
      # Bitwise-AND red binary + original image.
      res_red=cv2.bitwise_and(frame, frame, mask=red_binary)
      if s_red==0:
          cv2.imshow('Residual Red', res_red)
  
  # Process the colour isolated image to find contours.
      contours_red, hierarchy_red = cv2.findContours(red_binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
      max_area_red = 0
      largest_contour_red = None
      red_centroid=np.zeros(2)
      for idx, contour_red in enumerate(contours_red):
          red_area = cv2.contourArea(contour_red)
          if red_area &gt; max_area_red:
              max_area_red = red_area
              largest_contour_red = contour_red
      if not largest_contour_red == None:
          moment_red = cv2.moments(largest_contour_red)
          if moment_red["m00"] &gt; 1000:
              rect_red = cv2.minAreaRect(largest_contour_red)
              rect_red = ((rect_red[0][0], rect_red[0][1]), (rect_red[1][0], rect_red[1][1]), rect_red[2])
              red_box = cv2.cv.BoxPoints(rect_red)
              red_box = np.int0(red_box)
              cv2.drawContours(frame,[red_box], 0, (0, 0, 255), 2)
              #Find the centroid of the detected area.
              red_centroid=(moment_red['m10']/moment_red['m00'],moment_red['m01']/moment_red['m00'])    
  
      # Apply wait key.
      k=cv2.waitKey(5) &amp; 0xFF
      if k==27:
           break
  
  # When everything is done, release the capture.
  cap.release()
  cv2.destroyAllWindows()
  </code></pre>
  
  <p>The code translated to C++ (minus some functionalities, such as the track-bars) is:</p>
  
  <pre><code>// Pragma Comment Compiler Directives for use of OpenCV.
  #ifdef _DEBUG
  //Debug mode
  #pragma comment(lib,"opencv_core231d.lib")
  #pragma comment(lib,"opencv_imgproc231d.lib")
  #pragma comment(lib,"opencv_highgui231d.lib")
  #else
  //Release mode
  #pragma comment(lib,"opencv_core231.lib")
  #pragma comment(lib,"opencv_imgproc231.lib")
  #pragma comment(lib,"opencv_highgui231.lib")
  #endif
  //Include
  #include "stdafx.h"     //To assist with compiling.
  #include &lt;iostream&gt;
  #include &lt;stdio.h&gt;      //C library for input/output operations.
  #include &lt;stdlib.h&gt;     //C Standard General Utilities Library.
  #include &lt;math.h&gt;       //Declares basic mathematical functions.
  #include &lt;windows.h&gt;    //Declares all functions in the Windows API.
  #include &lt;conio.h&gt;      //For console input/output.
  //#include "Caio.h"     //For Contec
  #include &lt;time.h&gt;       //Definitions for time functions.
  #include &lt;opencv2/core/core.hpp&gt;        //For OpenCV.
  #include &lt;opencv2/highgui/highgui.hpp&gt;  //For OpenCV.
  #include &lt;opencv2/imgproc/imgproc.hpp&gt;  //For OpenCV.
  using namespace std;                    //For definition of names.
  #pragma comment(lib, "winmm.lib")       //Visual C++ (MSVC) library.
  
  int i;
  
  //Vision settings and declarations.
  //Use OpenCV to output the video capture.
  cv::VideoWriter video01;
  //Declare image types.
  cv::Mat smooth_img;
  cv::Mat hsv_img;
  cv::Mat frame;
  
  //Declare masks.
  cv::Mat maskRed;
  cv::Mat maskGreen;
  cv::Mat maskBlue;
  
  double Point;
  
  //Declare contour variables.
  vector&lt;vector&lt;cv::Point&gt;&gt; redContours;
  vector&lt;vector&lt;cv::Vec4i&gt;&gt; redHier;
  //CvSeq *redContours = 0;
  
  
  cv::Mat greenContours;
  cv::Mat greenHier;
  cv::Mat blueContours;
  cv::Mat blueHier;
  int largestContourIndexRed=0;
  double maxAreaRed = 0;
  double largestContourRed = 0;
  double maxAreaGreen = 0;
  double largestContourGreen = 0;
  double maxAreaBlue = 0;
  double largestContourBlue = 0;
  
  //Declare moment variables.
  double momentRed = 0;
  double momentGreen = 0;
  double momentBlue = 0;
  
  //Declare the colour coordinate arrays.
  double redCent [2] = { };
  double greenCent [2] = { };
  double blueCent [2] = { };
  //Declare the coordinate array.
  double coords [6] = { };
  
  //Main:
  int main(int argc, char *argv[]){
  
  
  //Set video capture device.
  //Open capture device.
  cv::VideoCapture cap(0); 
  cap.set(CV_CAP_PROP_FRAME_WIDTH, 320);
  cap.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
  //cap = cv::VideoCapture(0);
  
  if(!cap.isOpened()){
      return -1;
      printf("Capture device not found!");
  }
  
  cv::Mat  bin_img;
  //Start the visual processing.
  while(1){
      //Take the camera feed frame by frame.
      cap &gt;&gt; frame;
  
      //Apply Gaussian Blur.
      cv::GaussianBlur(frame,smooth_img, cv::Size(5,5),0,0);
      //Convert BGR colour to HSV colour.
      cv::cvtColor(smooth_img,hsv_img,CV_BGR2HSV);
  
  
      //Apply colour masks (specified in HSV range H: 0-180, S: 0-255, V: 0-255).
      cv::inRange(hsv_img,  cv::Scalar(0,0,0,0), cv::Scalar(15,255,255,0) , maskRed);         //Red mask (source, lower threshold, upper threshold, destination). Red: HSV: Low boundary(0,110,60), high boundary(5,255,110).
      cv::inRange(hsv_img, cv::Scalar(55,110,60,0), cv::Scalar(5,255,110,0) , maskGreen);         //Green mask. Green: HSV: Low boundary(55,35,0), high boundary(70,190,130).
      cv::inRange(hsv_img, cv::Scalar(0,110,60,0), cv::Scalar(5,255,110,0), maskBlue);            //Blue mask. Blue: HSV: Low boundary(95,55,145), high boundary(120,185,255).
      cv::imshow("Mask", maskRed);
  
      //Process the colour binary maps.
      //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
      //Red:
      //Find contours of the isolated colour extracted from the binary image.
      //std::vector&lt;std::vector&lt;cv::Point&gt; &gt; redContours;
      cv::findContours(maskRed,redContours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
      printf("%d\n",redContours);
  
      //Take moments
      vector&lt;cv::Moments&gt; muRed(redContours.size());
      for( size_t i = 0; i &lt; redContours.size(); ++i){
          muRed[i] = cv::moments( redContours[i], false );
      }
  
      //Find the centre of mass.
      vector&lt;cv::Point2d&gt; mcRed( redContours.size() );
      for( size_t i = 0; i &lt; redContours.size(); ++i )
      {
      mcRed[i] = cv::Point2d( muRed[i].m10/muRed[i].m00 , muRed[i].m01/muRed[i].m00 );
      }
  
      //Draw the detected contours onto the "frame".
      for (size_t i = 0; i&lt; redContours.size(); ++i)
          {
          cv::drawContours(frame, redContours, i, (255,0,255), 2, 8, redHier, 0, cv::Point() );
          }
  
      cv::imshow("Detected Markers",frame);
  
      //Apply waitkey.
      int k = cv::waitKey(27);
      if (k==27){
          break;
      }
  }
      /*cv::VideoCapture::release();
      cv::destroyAllWindows();*/
      return 0;
  }
  </code></pre>
  
  <p>This code compiles in Visual Studio 2008 without any errors/warnings, however, when it is run the aforementioned error surfaces. I attempted to pinpoint the cause of the error using printf and imshow functions and I believe it resides within the "findContours" function. The print function returns a value before that function, but not after and the imshow of the "maskRed" value appears as expected. A colleague (better versed in C++) and I have thoroughly checked the documentation for C++ and OpenCV and cannot work out how to fix it.</p>
  
  <p>Any advice/pointers in the way of decrypting this error and getting the code functional would be greatly appreciated.</p>
  
  <p>Thanks.</p>