Putting multiple video feed next to each other with OpenCV - opencv

I have real-time video from 3 different cameras, I would like to resize and then put the videos next to each other and fit them on one screen, basically:
-------------------------------------
| CAM LEFT | CAM MIDDLE | CAM RIGHT |
-------------------------------------
I have written the following code but for whatever reason I only have image on the LEFT side only. The middle and right side are replaced by a gray color background (I have no idea where that comes from). I have printed out all the coordinates and they look fine to me, with a total screen size of 1440 x 540 (I want the picture in the middle to be bigger).
- LEFT: 0,0,380,540
- MIDDLE: 380,0,680,540
- RIGHT: 1060,0,380,540
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/stitching.hpp"
#include <opencv2/opencv.hpp>
#include <opencv2/imgcodecs.hpp>
#include<iostream>
#include <fstream>
#include<conio.h> // may have to modify this line if not using Windows
int main(int argc, char **argv) {
int combinedScreenWidth = 1440;
int combinedScreenHeight = 540;
int rearCameraBiggerByThis = 100;
int combinedScreenWidthHalv = combinedScreenWidth / 3;
//initialize and allocate memory to load the video stream from camera
cv::VideoCapture cameraRight(0); // RIGHT CAM
cv::VideoCapture cameraMiddle(3); // REAR CAM
cv::VideoCapture cameraLeft(2); // LEFT CAM
if (!cameraRight.isOpened()) return 1;
if (!cameraMiddle.isOpened()) return 1;
if (!cameraLeft.isOpened()) return 1;
cv::Mat3b cameraRightFrame;
cv::Mat3b cameraMiddleFrame;
cv::Mat3b cameraLeftFrame;
cv::Mat3b cameraRightFrameMirrored;
cv::Mat3b cameraMiddleFrameMirrored;
cv::Mat3b cameraLeftFrameMirrored;
cv::Size camRightSize;
cv::Size camMiddleSize;
cv::Size camLeftSize;
cv::Mat3b cameraRightFrameMirroredResize;
cv::Mat3b cameraMiddleFrameMirroredResize;
cv::Mat3b cameraLeftFrameMirroredResize;
while (true) {
// Grab
cameraRight >> cameraRightFrame;
cameraMiddle >> cameraMiddleFrame;
cameraLeft >> cameraLeftFrame;
// Mirror
cv::flip(cameraRightFrame, cameraRightFrameMirrored, 1);
cv::flip(cameraMiddleFrame, cameraMiddleFrameMirrored, 1);
cv::flip(cameraLeftFrame, cameraLeftFrameMirrored, 1);
// Resize
camRightSize = cameraRightFrame.size();
camMiddleSize = cameraMiddleFrame.size();
camLeftSize = cameraLeftFrame.size();
std::cout << "----------------------> original camRightSize " << camRightSize.width << "x" << camRightSize.height << std::endl;
std::cout << "----------------------> original camMiddletSize " << camMiddleSize.width << "x" << camMiddleSize.height << std::endl;
std::cout << "----------------------> original camLeftSize " << camLeftSize.width << "x" << camLeftSize.height << std::endl;
resize(cameraRightFrameMirrored, cameraRightFrameMirroredResize, cv::Size(combinedScreenWidthHalv - rearCameraBiggerByThis, combinedScreenHeight));
resize(cameraMiddleFrameMirrored, cameraMiddleFrameMirroredResize, cv::Size(combinedScreenWidthHalv + 2 * rearCameraBiggerByThis, combinedScreenHeight));
resize(cameraLeftFrameMirrored, cameraLeftFrameMirroredResize, cv::Size(combinedScreenWidthHalv - rearCameraBiggerByThis, combinedScreenHeight));
camRightSize = cameraRightFrameMirroredResize.size();
camMiddleSize = cameraMiddleFrameMirroredResize.size();
camLeftSize = cameraLeftFrameMirroredResize.size();
std::cout << "----------------------> resized camRightSize " << camRightSize.width << "x" << camRightSize.height << std::endl;
std::cout << "----------------------> resized camMiddletSize " << camMiddleSize.width << "x" << camMiddleSize.height << std::endl;
std::cout << "----------------------> resized camLeftSize " << camLeftSize.width << "x" << camLeftSize.height << std::endl;
// Compilation
cv::Mat3b combinedFrame(camRightSize.height, camLeftSize.width + camMiddleSize.width + camRightSize.width);
// LEFT
std::cout << "LEFT: 0,0," << camLeftSize.width << "," << camLeftSize.height << std::endl;
cv::Mat3b leftSideOfScreen(combinedFrame, cv::Rect(0, 0, camLeftSize.width, camLeftSize.height));
cameraLeftFrameMirroredResize.copyTo(leftSideOfScreen);
// MIDDLE
std::cout << "MIDDLE: " << camLeftSize.width << ",0," << camMiddleSize.width << "," << camMiddleSize.height << std::endl;
cv::Mat3b middleSideOfScreen(combinedFrame, cv::Rect(camLeftSize.width, 0, camMiddleSize.width, camMiddleSize.height));
cameraRightFrameMirroredResize.copyTo(middleSideOfScreen);
// RIGHT
std::cout << "RIGHT: " << camLeftSize.width + camMiddleSize.width << ",0," << camRightSize.width << "," << camRightSize.height << std::endl;
cv::Mat3b rightSideOfScreen(combinedFrame, cv::Rect(camLeftSize.width + camMiddleSize.width, 0, camRightSize.width, camRightSize.height));
cameraMiddleFrameMirroredResize.copyTo(rightSideOfScreen);
// declare windows
cv::namedWindow("Combined", CV_WINDOW_NORMAL);
cv::setWindowProperty("Combined", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
cv::putText(combinedFrame, "LEFT", cv::Point(250, 50), cv::FONT_HERSHEY_PLAIN, 2.0, cv::Scalar(255, 255, 255), 2);
cv::putText(combinedFrame, "REAR", cv::Point(650, 50), cv::FONT_HERSHEY_PLAIN, 2.0, cv::Scalar(255, 255, 255), 2);
cv::putText(combinedFrame, "RIGHT", cv::Point(1050, 50), cv::FONT_HERSHEY_PLAIN, 2.0, cv::Scalar(255, 255, 255), 2);
cv::imshow("Combined", combinedFrame); // 1440 x 540 Screen size
//cv::imshow("Right Cam", cameraRightFrame);
//cv::imshow("Middle Cam", cameraMiddleFrame);
//cv::imshow("Left Cam", cameraLeftFrame);
//wait for 40 milliseconds
int c = cvWaitKey(1);
//exit the loop if user press "Esc" key (ASCII value of "Esc" is 27)
if (27 == char(c)) {
break;
}
}
return 0;
}

Related

Matrix multiplication with vectorization in c++

I need to multiply and then add matrices AxB+C. Is there a way to do this operation in c++ such that vectorization is applied and the matrices are multiplied and added faster? If there is a reference or code for doing so it would be nice. Additionally do I need to modify something in order to enable vectorization.
Thank you in advance
EDIT:
//g++ -I/path/to/eigen -O3 -DEIGEN_NO_DEBUG -fopenmp new.cpp
// ./a.out
#pragma GCC optimize("O3","unroll-loops","omit-frame-pointer","inline") //Optimization flags
#pragma GCC option("arch=native","tune=native","no-zero-upper") //Enable AVX
#pragma GCC target("avx") //Enable AVX
#include <x86intrin.h> //AVX/SSE Extensions
#include <bits/stdc++.h> //All main STD libraries
#include <iostream>
#include <chrono>
#include <Eigen/Dense>
#include <unsupported/Eigen/FFT>
using namespace Eigen;
int main()
{
// Matrix2d mat;
// mat << 1, 2,
// 3, 4;
// mat= MatrixXd::Random(3000,3000);
// Vector2d u(-1,1), v(2,0);
// Matrix2d m1;
// auto start = std::chrono::steady_clock::now();
//
// m1 << mat*mat;
// auto end = std::chrono::steady_clock::now();
// std::cout << "Elapsed time in nanoseconds : "
// << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()
// << " ns" ;
// std::cout << "Here is mat*mat:\n" << mat*mat << std::endl;
// std::cout << "Here is mat*u:\n" << mat*u << std::endl;
// std::cout << "Here is u^T*mat:\n" << u.transpose()*mat << std::endl;
// std::cout << "Here is u^T*v:\n" << u.transpose()*v << std::endl;
// std::cout << "Here is u*v^T:\n" << u*v.transpose() << std::endl;
// std::cout << "Let's multiply mat by itself" << std::endl;
// mat = mat*mat;
// std::cout << "Now mat is mat:\n" << mat << std::endl;
// mat << 1, 2,
// 3, 4;
MatrixXf m1 = MatrixXf::Random(32,32);
MatrixXf m2 = MatrixXf::Random(32,32);
MatrixXf newM;
auto start = std::chrono::steady_clock::now();
newM=m1*m2;
auto end = std::chrono::steady_clock::now();
std::cout << "Elapsed time in nanoseconds : "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()
<< " ns" ;
MatrixXf a = MatrixXf::Random(1, 32);
MatrixXf b = MatrixXf::Random(32, 32);
MatrixXf c = MatrixXf::Random(32, 1);
time_t start1 = clock();
start = std::chrono::steady_clock::now();
MatrixXf d = a * b * c;
end = std::chrono::steady_clock::now();
std::cout << "Elapsed time in nanoseconds : "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()
<< " ns" ;
std::cout << (double)(clock() - start1) / CLOCKS_PER_SEC * 1000 << "ms" << std::endl;
const int ROWS = 32;
const int COLS = 32;
int random_matrix[ROWS][COLS];
int i;
int j;
/* initialize random seed: */
srand(static_cast<unsigned>(time(0)));
/* generate number: */
for (i=0;i<ROWS;i++)
{
for (j=0;j<COLS;j++)
random_matrix[i][j]= rand() % 100;
// std::cout << random_matrix[i][j] << std::endl; //display table
}
int mult[10][10], r1, c1, r2, c2, k;
r1=32*32;
c2=32*32;
c1=32*32;
start = std::chrono::steady_clock::now();
start1 = clock();
for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
{
mult[i][j]=0;
}
for(i = 0; i < r1; ++i)
for(j = 0; j < c2; ++j)
for(k = 0; k < c1; ++k)
{
// std::cout << "Elapsed time in nanoseconds : "
// << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()
// << " ns" ;
mult[i][j] += random_matrix[i][k] * random_matrix[k][j]* random_matrix[k][j];
}
end = std::chrono::steady_clock::now();
double end1=clock() - start1;
std::cout << "Elapsed time in nanoseconds : "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()
<< " ns" ;
std::cout << (double)(end1) / CLOCKS_PER_SEC * 1000 << "ms" << std::endl;
return 0;

How to track the 2d points over the images for 3d-reconstruction as specified in opencv sfm pipeline?

I am trying to do 3D reconstruction using this code from opencv. As far as I understood, I need a textfile with the 2D points as per the given format. I am wondering if anyone could help me in getting these 2D points they mention in this program. I have a set of images with the calibration parameters but I have been not able to understand how could I track and save these 2D points e.g. the first point in frame 1 is the same point in frame 2 in the format they specified .
#include <opencv2/core.hpp>
#include <opencv2/sfm.hpp>
#include <opencv2/viz.hpp>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
using namespace cv;
using namespace cv::sfm;
static void help() {
cout
<< "\n------------------------------------------------------------\n"
<< " This program shows the camera trajectory reconstruction capabilities\n"
<< " in the OpenCV Structure From Motion (SFM) module.\n"
<< " \n"
<< " Usage:\n"
<< " example_sfm_trajectory_reconstruction <path_to_tracks_file> <f> <cx> <cy>\n"
<< " where: is the tracks file absolute path into your system. \n"
<< " \n"
<< " The file must have the following format: \n"
<< " row1 : x1 y1 x2 y2 ... x36 y36 for track 1\n"
<< " row2 : x1 y1 x2 y2 ... x36 y36 for track 2\n"
<< " etc\n"
<< " \n"
<< " i.e. a row gives the 2D measured position of a point as it is tracked\n"
<< " through frames 1 to 36. If there is no match found in a view then x\n"
<< " and y are -1.\n"
<< " \n"
<< " Each row corresponds to a different point.\n"
<< " \n"
<< " f is the focal lenght in pixels. \n"
<< " cx is the image principal point x coordinates in pixels. \n"
<< " cy is the image principal point y coordinates in pixels. \n"
<< "------------------------------------------------------------------\n\n"
<< endl;
}
/* Build the following structure data
*
* frame1 frame2 frameN
* track1 | (x11,y11) | -> | (x12,y12) | -> | (x1N,y1N) |
* track2 | (x21,y11) | -> | (x22,y22) | -> | (x2N,y2N) |
* trackN | (xN1,yN1) | -> | (xN2,yN2) | -> | (xNN,yNN) |
*
*
* In case a marker (x,y) does not appear in a frame its
* values will be (-1,-1).
*/
void
parser_2D_tracks(const string &_filename, std::vector<Mat> &points2d )
{
ifstream myfile(_filename.c_str());
if (!myfile.is_open())
{
cout << "Unable to read file: " << _filename << endl;
exit(0);
} else {
double x, y;
string line_str;
int n_frames = 0, n_tracks = 0;
// extract data from text file
vector<vector<Vec2d> > tracks;
for ( ; getline(myfile,line_str); ++n_tracks)
{
istringstream line(line_str);
vector<Vec2d> track;
for ( n_frames = 0; line >> x >> y; ++n_frames)
{
if ( x > 0 && y > 0)
track.push_back(Vec2d(x,y));
else
track.push_back(Vec2d(-1));
}
tracks.push_back(track);
}
// embed data in reconstruction api format
for (int i = 0; i < n_frames; ++i)
{
Mat_<double> frame(2, n_tracks);
for (int j = 0; j < n_tracks; ++j)
{
frame(0,j) = tracks[j][i][0];
frame(1,j) = tracks[j][i][1];
}
points2d.push_back(Mat(frame));
}
myfile.close();
}
}
/* Keyboard callback to control 3D visualization
*/
bool camera_pov = false;
void keyboard_callback(const viz::KeyboardEvent &event, void* cookie)
{
if ( event.action == 0 &&!event.symbol.compare("s") )
camera_pov = !camera_pov;
}
/* Sample main code
*/
int main(int argc, char** argv)
{
// Read input parameters
if ( argc != 5 )
{
help();
exit(0);
}
// Read 2D points from text file
std::vector<Mat> points2d;
parser_2D_tracks( argv[1], points2d );
// Set the camera calibration matrix
const double f = atof(argv[2]),
cx = atof(argv[3]), cy = atof(argv[4]);
Matx33d K = Matx33d( f, 0, cx,
0, f, cy,
0, 0, 1);
bool is_projective = true;
vector<Mat> Rs_est, ts_est, points3d_estimated;
reconstruct(points2d, Rs_est, ts_est, K, points3d_estimated, is_projective);
// Print output
cout << "\n----------------------------\n" << endl;
cout << "Reconstruction: " << endl;
cout << "============================" << endl;
cout << "Estimated 3D points: " << points3d_estimated.size() << endl;
cout << "Estimated cameras: " << Rs_est.size() << endl;
cout << "Refined intrinsics: " << endl << K << endl << endl;
cout << "3D Visualization: " << endl;
cout << "============================" << endl;
viz::Viz3d window_est("Estimation Coordinate Frame");
window_est.setBackgroundColor(); // black by default
window_est.registerKeyboardCallback(&keyboard_callback);
// Create the pointcloud
cout << "Recovering points ... ";
// recover estimated points3d
vector<Vec3f> point_cloud_est;
for (int i = 0; i < points3d_estimated.size(); ++i)
point_cloud_est.push_back(Vec3f(points3d_estimated[i]));
cout << "[DONE]" << endl;
cout << "Recovering cameras ... ";
vector<Affine3d> path_est;
for (size_t i = 0; i < Rs_est.size(); ++i)
path_est.push_back(Affine3d(Rs_est[i],ts_est[i]));
cout << "[DONE]" << endl;
cout << "Rendering Trajectory ... ";
cout << endl << "Press: " << endl;
cout << " 's' to switch the camera pov" << endl;
cout << " 'q' to close the windows " << endl;
if ( path_est.size() > 0 )
{
// animated trajectory
int idx = 0, forw = -1, n = static_cast<int>(path_est.size());
while(!window_est.wasStopped())
{
for (size_t i = 0; i < point_cloud_est.size(); ++i)
{
Vec3d point = point_cloud_est[i];
Affine3d point_pose(Mat::eye(3,3,CV_64F), point);
char buffer[50];
sprintf (buffer, "%d", static_cast<int>(i));
viz::WCube cube_widget(Point3f(0.1,0.1,0.0), Point3f(0.0,0.0,-0.1), true, viz::Color::blue());
cube_widget.setRenderingProperty(viz::LINE_WIDTH, 2.0);
window_est.showWidget("Cube"+string(buffer), cube_widget, point_pose);
}
Affine3d cam_pose = path_est[idx];
viz::WCameraPosition cpw(0.25); // Coordinate axes
viz::WCameraPosition cpw_frustum(K, 0.3, viz::Color::yellow()); // Camera frustum
if ( camera_pov )
window_est.setViewerPose(cam_pose);
else
{
// render complete trajectory
window_est.showWidget("cameras_frames_and_lines_est", viz::WTrajectory(path_est, viz::WTrajectory::PATH, 1.0, viz::Color::green()));
window_est.showWidget("CPW", cpw, cam_pose);
window_est.showWidget("CPW_FRUSTUM", cpw_frustum, cam_pose);
}
// update trajectory index (spring effect)
forw *= (idx==n || idx==0) ? -1: 1; idx += forw;
// frame rate 1s
window_est.spinOnce(1, true);
window_est.removeAllWidgets();
}
}
return 0;
}
I would be really grateful if someone can help me through this. Thank you.

Out of Index Error when reading Image with OpenCV using Pointer

I receive a weird out of range error when reading an 16-bit RGB image with openCV. The image has a resolution of 2700 x 2000. Outer rows and columns of the image are black.
I got the following code:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
// Create Mat Container and rowPtr
Mat image;
image = imread(argv[1], -1);
uint16_t* rowPtr;
// Read Image characteristics
int width = image.cols;
int height = image.rows;
int numChannels = image.channels();
if (image.isContinuous())
{
std::cout << "isContinuous!" << "\n";
width *= height;
height = 1;
}
// Double for loop, reading using pointers according to
// https://docs.opencv.org/2.4/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html
for ( uint32_t y = 0; y < height; ++y )
{
rowPtr = image.ptr<uint16_t>(y);
for ( uint32_t x = 0; x < width; ++x )
{
const uint32_t idx = x + y * width;
// Quick Debug
if (idx > 2704713)
{
std::cout << "height : " << height << "\n";
std::cout << "width : " << width << "\n";
std::cout << "row : " << y << "\n";
std::cout << "col : " << x << "\n";
std::cout << "idx : " << idx << "\n";
std::cout << "B: " << rowPtr[numChannels * idx + 0] << "\n";
std::cout << "G: " << rowPtr[numChannels * idx + 1] << "\n";
std::cout << "R: " << rowPtr[numChannels * idx + 2] << "\n"; //The error occurs here!
}
}
}
namedWindow( "Display window", WINDOW_AUTOSIZE ); // Create a window for display.
imshow( "Display window", image ); // Show our image inside it.
waitKey(0); // Wait for a keystroke in the window
return 0;
}
The output of running the code is:
isContinuous!
height : 1
width : 5400000
row : 0
col : 2704714
idx : 2704714
B: 0
G: 0
So, the segmentation fault happens, when the value for R should be read, at Pixel No. 2,704,715.
This code runs without problems for images that don't exhibit large black borders. So I thought that openCV's imread might crop such images internally, leading to such an error?

How to Select a Region of Interest on a Video like this

I am working on a queue bypass detection project and i need to select a region of interest or the boundary. If a person crosses the boundary, we should get an alert. Please help me to select a region of interest in live video similar to the one in the image.
please see this image
After doing some research I found what you need on github
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
/*~~~~~~~~~~~~~~~~~~*/
char ky;
bool got_roi = false;
Point points_array[4];
Mat src, ROI_Img,backup,ROI_MASK;
Rect2d ROI_Select;
int width_roi = 0, height_roi = 0,min_x,min_y,max_x,max_y;
Rect ROI_RECT ;
vector< vector<Point> > co_ordinates;
/*~~~~~~~~~~~~~~~~~~*/
/*~~~~~~~~~~~~~~~~~~*/
//Callback for mousclick event, the x-y coordinate of mouse button-down
//are stored array of points [points_array].
void mouse_click(int event, int x, int y, int flags, void *param)
{
static int count=0;
switch (event)
{
case CV_EVENT_LBUTTONDOWN:
{
switch (count) // number of set Point
{
case 0:
cout << "Select top-right point" << endl;
break;
case 1:
cout << "Select bottom-right point" << endl;
break;
case 2:
cout << "Select bottom-left point" << endl << endl;
break;
default:
break;
}
if (!got_roi) // you are not select ROI yet!
{
points_array[count] = Point(x,y);
circle(src, points_array[count], 2, Scalar(0, 255, 0), 2); //show points on image
imshow("My_Win", src);
count++;
if (count == 4) // if select 4 point finished
{
cout << "ROI x & y points :" << endl;
cout << points_array[0] << endl;
cout << points_array[1] << endl;
cout << points_array[2] << endl;
cout << points_array[3] << endl;
cout << endl << "ROI Saved You can continue with double press any keys except 'c' " << endl <<"once press 'c' or 'C' to clear points and retry select ROI " << endl << endl;
ky = waitKey(0) & 0xFF;
if (ky == 99 || ky == 67) // c or C to clear
{
backup.copyTo(src);
points_array[0] = Point(0, 0);
points_array[1] = Point(0, 0);
points_array[2] = Point(0, 0);
points_array[3] = Point(0, 0);
imshow("My_Win", src);
count = 0;
cout << endl << endl << endl << "#--------------------- Clear Points! ------------------# " << endl << endl << endl ;
}
else // user accept points & dosn't want to clear them
{
min_x = std::min(points_array[0].x, points_array[3].x); //find rectangle for minimum ROI surround it!
max_x = std::max(points_array[1].x, points_array[2].x);
min_y = std::min(points_array[0].y, points_array[1].y);
max_y = std::max(points_array[3].y, points_array[2].y);
height_roi = max_y - min_y;
width_roi = max_x - min_x;
ROI_RECT = Rect(min_x, min_y, width_roi, height_roi);
got_roi = true;
co_ordinates.push_back(vector<Point>());
co_ordinates[0].push_back(points_array[0]);
co_ordinates[0].push_back(points_array[1]);
co_ordinates[0].push_back(points_array[2]);
co_ordinates[0].push_back(points_array[3]);
}
}
}
else { // if got_roi se true => select roi before
cout << endl << "You Select ROI Before " << endl << "if you want to clear point press 'c' or double press other keys to continue" << endl << endl;
}
break;
}
}
}
/*~~~~~~~~~~~~~~~~~~*/
int main()
{
// replace all "My_Win" with your window name
/*~~~~~~~~~~~~~~~~~~*/
namedWindow("My_Win", 1);
/*~~~~~~~~~~~~~~~~~~*/
VideoCapture input_video("Video_path");
// Set source imafe as [src]
/*~~~~~~~~~~~~~~~~~~*/
input_video >> src;
imshow("My_Win", src);
src.copyTo(backup);
setMouseCallback("My_Win", mouse_click, 0);
waitKey(0);
Mat mask(src.rows, src.cols, CV_8UC1, cv::Scalar(0));
drawContours(mask, co_ordinates, 0, Scalar(255), CV_FILLED, 8);
/*~~~~~~~~~~~~~~~~~~*/
while (1)
{
input_video >> src;
/*~~~~~~~~~~~~~~~~~~*/
//Need to copy Select ROI as MASK
src.copyTo(ROI_MASK, mask);
//Creat a rectangle around the Mask to reduce size of mask
ROI_Img = ROI_MASK(ROI_RECT);
/*~~~~~~~~~~~~~~~~~~*/
//Show Image
imshow("My_Win", ROI_Img);
// Do remaining processing here on capture roi for every frame
if(char (waitKey(1)& 0xFF) == 27) break;
}
}

Application error(0xc000007b) when runnning Opencv example in Visual Studio 2015

I am running canny edge example in Visual Studio 2015 and i got this error.
The application was unable to start correctly (0xc000007b).
And then visual studio show to this error.
Unhandled exception at 0x77A2D5B2 (ntdll.dll) in Canny Edge.exe: 0xC000007B: %hs is either not designed to run on Windows or it contains an error. Try installing the program again using the original installation media or contact your system administrator or the software vendor for support. Error status 0x.
I quite sure this coding is working as i ran this coding before in Visual Studio 2013. Here is my coding.
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <algorithm>
using namespace cv;
using namespace std;
void help()
{
cout << "\nThis program demonstrates line finding with the Hough transform.\n"
"Usage:\n"
"./houghlines <image_name>, Default is pic1.jpg\n" << endl;
}
bool less_by_y(const cv::Point& lhs, const cv::Point& rhs)
{
return lhs.y < rhs.y;
}
int main(int argc, char** argv)
{
const char* filename = argc >= 2 ? argv[1] : "pic1.jpg";
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Rect roi;
Mat src = imread("test_4_1.png");
if (src.empty())
{
help();
cout << "can not open " << filename << endl;
return -1;
}
Mat dst, cdst;
Canny(src, dst, 50, 200, 3);
cvtColor(dst, cdst, CV_GRAY2BGR);
findContours(dst, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
//vector<Vec2f> lines;
//HoughLines(dst, lines, 1, CV_PI / 180, 50, 0, 0);
//for (size_t i = 0; i < lines.size(); i++)
//{
// float rho = lines[i][0], theta = lines[i][1];
// Point pt1, pt2;
// double a = cos(theta), b = sin(theta);
// double x0 = a*rho, y0 = b*rho;
// pt1.x = cvRound(x0 + 1000 * (-b));
// pt1.y = cvRound(y0 + 1000 * (a));
// pt2.x = cvRound(x0 - 1000 * (-b));
// pt2.y = cvRound(y0 - 1000 * (a));
// line(cdst, pt1, pt2, Scalar(0, 0, 255), 1, CV_AA);
// cout << pt1 << " " << pt2 << endl;
//}
vector<Vec4i> lines;
HoughLinesP(dst, lines, 1, CV_PI / 180, 30, 50, 10);
for (size_t i = 0; i < lines.size(); i++)
{
Vec4i l = lines[i];
line(cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, CV_AA);
cout << l << endl;
}
cout << endl << lines.size() << endl;
cout << arcLength(contours[0], true) << endl;
cout << dst.size() << endl << endl;
for (int a = 0; a < contours[0].size(); a++){
cout << contours[0][a] << " ";
}
vector<Point> test = contours[0];
auto mmx = std::minmax_element(test.begin(), test.end(), less_by_y);
cout << endl << *mmx.first._Ptr << endl << *mmx.second._Ptr;
vector<Point> test2 = contours[1];
auto mmx_1 = std::minmax_element(test2.begin(), test2.end(), less_by_y);
cout << endl << *mmx_1.first._Ptr << endl << *mmx_1.second._Ptr;
imshow("source", src);
imshow("detected lines", cdst);
/* ROI by creating mask for the parallelogram */
Mat mask = cvCreateMat(dst.size().height, dst.size().width, CV_8UC1);
// Create black image with the same size as the original
for (int i = 0; i < mask.cols; i++)
for (int j = 0; j < mask.rows; j++)
mask.at<uchar>(Point(i, j)) = 0;
cout <<endl<<endl<< *mmx.first._Ptr << *mmx.second._Ptr << *mmx_1.first._Ptr << *mmx_1.second._Ptr << endl;
// Create Polygon from vertices
vector<Point> ROI_Vertices = { *mmx.first._Ptr, *mmx.second._Ptr, *mmx_1.first._Ptr, *mmx_1.second._Ptr};
vector<Point> ROI_Poly;
approxPolyDP(ROI_Vertices, ROI_Poly, 1.0, false);
// Fill polygon white
fillConvexPoly(mask, &ROI_Poly[0], ROI_Poly.size(), 255, 8, 0);
cout << ROI_Poly.size() << endl;
// Create new image for result storage
Mat imageDest = cvCreateMat(dst.size().height, dst.size().width, CV_8UC3);
// Cut out ROI and store it in imageDest
src.copyTo(imageDest, mask);
imshow("mask", mask);
imshow("image", imageDest);
waitKey();
return 0;
}
Actually my comment is the answer, with some additions
What OpenCV Libs are you linking to? Are you linking to vs12? Because
you need to upgrade your linker to vs13 for MSVS 2015
OpenCV Doesn't come with Visual Studio 15 pre-builds, so you need to build OpenCV yourself for VS2015
This person seems to have had a similar problem and talks you through how to compile for VS2015

Resources