对于一个程序宅来说,一直有想法把C++,opencv,python结合起来,python的并发性优点,opencv的图像处理算法的优点,C++的灵活,然后就开始了下面的旅程:

 

     配置版本:VS2008+Python2.7+OpenCV2.1.0

    

     源码:

OpenCV2.1.0  sampes里面的Python例程camera.py:

     [置顶] Python编程->混合编程(C++,python,opencv)实现_第1张图片

将其放到VS2008的例子python的工程目录下:

[置顶] Python编程->混合编程(C++,python,opencv)实现_第2张图片

然后就开始写代码了:

#include "stdafx.h" #include "python.h" #include  #define _AFXDLL  #include "stdafx.h" #include  #include  #include  #include  #include  #include  #include  using namespace std; #pragma comment (lib,"python27.lib")   int test1() { 	Py_Initialize();  	CString strPath;   	GetCurrentDirectory(MAX_PATH,strPath.GetBuffer(MAX_PATH));   	char ch[BUFSIZ]; 	WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK, (strPath.GetBuffer(strPath.GetLength() + 1)), -1, ch, sizeof(ch), NULL, NULL );  	;  	strPath.ReleaseBuffer();   	string tmpStr; 	cout << ch << endl;  	int len = strlen(ch);  	string fileName = "\\camera.py";  	for( int i = 0; i < int(fileName.length()); i++) 		ch[len++] = fileName[i];   	ch[len] = '\0';  	cout << ch << endl; 	PyObject *pyfile = PyFile_FromString(ch,"r"); 	if(pyfile==NULL) 	{ 		printf("exit 1"); 		system("pause"); 		return 1; 	}  	FILE *f = PyFile_AsFile(pyfile);  	if(f==NULL) 	{ 		printf("exit 2"); 		system("pause"); 		return 1;   	} 	PyRun_AnyFileEx(f,"camera.py",0);   	Py_Finalize();  } int main() {     test1(); 	system("pause"); }
点击Run后,打开摄像头如下:
[置顶] Python编程->混合编程(C++,python,opencv)实现_第3张图片

调用如下: