c++利用opencv打开摄像头并且保存图片

c++利用opencv打开双目摄像头并且保存图片

  • 项目背景
    • 打开双目相机的函数
    • 保存图片函数Save
    • 全部代码

项目背景

利用一个usb双目摄像机进行双目测距的项目,这个项目代码有助于使用usb双目摄像机打开摄像机并且保存图片

打开双目相机的函数


void SetCam(int weigth, int height, int num)
{
	string a = "0";
	string Error;
	VideoCapture Cam(0);
	/*设定缓冲区大小*/
	Cam.set(CV_CAP_PROP_FRAME_WIDTH, weigth);
	Cam.set(CV_CAP_PROP_FRAME_HEIGHT, height);

	while (!Cam.isOpened())
	{
		
		a = to_string(num);
		Error = "cannot open the camera1!";
		Error = Error.replace(22, 1, a);
		//Error.copy(error, 24, 0);//这里5代表复制几个字符,0代表复制的位置,
	}
	
	//namedWindow("摄像头");//关键一句代码
	while (true) {
		Cam >> input_image;//将影像传入图片
		leftImage = input_image(Rect(0, 0, input_image.size().width / 2, input_image.size().height));//split left image
		rightImage = input_image(Rect(input_image.size().width / 2, 0, input_image.size().width / 2, input_image.size().height));
		imshow("leftImage", leftImage);//left image
		imshow("rightImage", rightImage);//right image
		Save(i, 20);
		if (27 == waitKey(30))

			break;
	}

	
	return ;
}

保存图片函数Save

void Save(int &imgnum, int amount)
{
	if (imgnum < amount)
	{
		a = to_string(imgnum);
		seat = floor((imgnum - 1) / 10);
		Left = Left.replace(4 + seat, 1, a);
		Right = Right.replace(5 + seat, 1, a);
		imwrite(Left, leftImage);
		imwrite(Right, rightImage);
		imgnum += 1;
	}
}

全部代码

#include 


#include



using namespace cv;

using namespace std;
VideoCapture Cam1, Cam2;
const int  weigth = 1280;
const int height = 480;
static string Left = "Left0.jpg", Right = "Right0.jpg", a = "0";
static int seat = 0;
static Mat input_image, leftImage, rightImage;
static int i = 0;
void Save(int &imgnum, int amount)
{
	if (imgnum < amount)
	{
		a = to_string(imgnum);
		seat = floor((imgnum - 1) / 10);
		Left = Left.replace(4 + seat, 1, a);
		Right = Right.replace(5 + seat, 1, a);
		imwrite(Left, leftImage);
		imwrite(Right, rightImage);
		imgnum += 1;
	}
}



void SetCam(int weigth, int height, int num)
{
	string a = "0";
	string Error;
	VideoCapture Cam(0);
	/*设定缓冲区大小*/
	Cam.set(CV_CAP_PROP_FRAME_WIDTH, weigth);
	Cam.set(CV_CAP_PROP_FRAME_HEIGHT, height);

	while (!Cam.isOpened())
	{
		
		a = to_string(num);
		Error = "cannot open the camera1!";
		Error = Error.replace(22, 1, a);
		//Error.copy(error, 24, 0);//这里5代表复制几个字符,0代表复制的位置,
	}
	
	//namedWindow("摄像头");//关键一句代码
	while (true) {
		Cam >> input_image;//将影像传入图片
		leftImage = input_image(Rect(0, 0, input_image.size().width / 2, input_image.size().height));//split left image
		rightImage = input_image(Rect(input_image.size().width / 2, 0, input_image.size().width / 2, input_image.size().height));
		imshow("leftImage", leftImage);//left image
		imshow("rightImage", rightImage);//right image
		Save(i, 20);
		if (27 == waitKey(30))

			break;
	}

	
	return ;
}



void main()
{
	//char* error = "error";
	SetCam(weigth, height, 10);
	
	return ;
}

你可能感兴趣的:(opencv,1024程序员节)