设为首页 收藏本站
查看: 878|回复: 0

[经验分享] Python C++扩展

[复制链接]

尚未签到

发表于 2015-11-30 12:27:26 | 显示全部楼层 |阅读模式
  Python C++扩展
  前段时间看了一篇文章,http://blog.jobbole.com/78859/, 颇有感触,于是就结合自己工作中的知识作了一个简单的Python移动侦测:移动侦测的算法使用C++实现,封装成Python可以调用的格式,具体流程如图1。
DSC0000.jpg
  图1
  首先看一下C++的工程配置,如图2
DSC0001.jpg    DSC0002.jpg    DSC0003.jpg
  图2
  C++部分代码:
  #include "stdafx.h"
#include "Python.h"
#include "C:\Python27\Lib\site-packages\numpy\core\include\numpy\arrayobject.h"
#include "motiondetector.h"
  static int MD_GRID_W      = 32;
static int MD_GRID_H      = 32;
static int MD_NOISE_LEVEL = 150;
static int MD_SENSITIVITY = 150;
  class VideoDetector
{
public:
~VideoDetector()
{
  if (m_motionDetector != NULL)
  {
   delete m_motionDetector;
   m_motionDetector = NULL;
   printf("~VideoDetector\r\n");
  }
}
VideoDetector(int width, int height):m_width(width), m_height(height)
{
        m_motionDetector = new simple_md::MotionDetector();
  if (m_motionDetector != NULL)
  {
      m_motionDetector->init(MD_GRID_W, MD_GRID_H, m_width, height);
   m_motionDetector->set_noise_level(MD_NOISE_LEVEL);
   m_motionDetector->set_sensitivity(MD_SENSITIVITY);
  // Setup default zone
   std::vector<simple_md::Zone> zones;
   simple_md::Zone z;
   z.sensitivity = 100;
  for (int i = 0; i < MD_GRID_W * MD_GRID_H; ++i)
   {
    z.mask.push_back(100);
   }
  zones.push_back(z);
   m_motionDetector->set_zones(zones);
   m_motionDetector->set_md_enbale();
         printf("VideoDetector\r\n");
  }
}
  int process_frame(uint8_t *frame)
{
  
  if (m_motionDetector != NULL && frame != NULL)
  {
  m_motionDetector->feed_frame(frame, m_width, m_height, m_width - 1, GetTickCount(), NULL, 0, NULL, 0, NULL, 0);
   return m_motionDetector->get_state();
  }
  return 0;
}
  int test(void)
{
  return m_width * m_height;
}
private:
VideoDetector();
simple_md::MotionDetector *m_motionDetector;
int m_width;
int m_height;
};
  static void PyDelVideoDetector(void *ptr)
{
    printf("VideoDetector_UnInit\n");
VideoDetector *tmp = static_cast<VideoDetector *>(ptr);
delete tmp;
return;
}
  PyObject *VideoDetector_Init(PyObject *self, PyObject *args)
{
printf("VideoDetector_Init\n");
int arg1 = 0;
int arg2 = 0;
int ret = PyArg_ParseTuple(args, "ii", &arg1, &arg2);
if (ret == 0)
{
  printf("VideoDetector_Init fail\n");
  return NULL;
}
VideoDetector *vd = new VideoDetector(arg1, arg2);
return PyCObject_FromVoidPtr(vd, PyDelVideoDetector);
}
  #define f(x0) (*((uint8_t*)PyArray_DATA(py_pix) + (x0) * PyArray_STRIDES(py_pix)[0]))
#define shape(i) (py_pix->dimensions[(i)])
  PyObject *VideoDetector_Process(PyObject *self, PyObject *args)
{
printf("VideoDetector_Process\n");
PyObject *py_obj = 0;
PyArrayObject *py_pix = 0;
npy_int64 idx = 0;
int ret = PyArg_ParseTuple(args, "OO", &py_obj, &py_pix);
if (ret == 0)
{
     printf("VideoDetector_Process fail\n");
  return NULL;
}
  uint8_t *frame = (uint8_t *)malloc(sizeof(uint8_t) * shape(0));
if (frame == NULL)
{
  return NULL;
}
  for (idx = 0; idx < shape(0); idx++)
{
  *(frame + idx) = (uint8_t)f(idx);
}
    printf("-------process_frame start-------\n");
void * tmp = PyCObject_AsVoidPtr(py_obj);
VideoDetector *vd = static_cast<VideoDetector *>(tmp);
int result = vd->process_frame(frame);
free(frame);
frame = NULL;
printf("-------process_frame end(%d)-------\n", result);
return Py_BuildValue("i", result);
}
  PyObject *VideoDetector_Test(PyObject *self, PyObject *args)
{
printf("VideoDetector_Test\n");
PyObject *pynum = 0;
int ret = PyArg_ParseTuple(args, "O", &pynum);
if (ret == 0)
{
     printf("VideoDetector_Test fail\n");
  return NULL;
}
void * tmp = PyCObject_AsVoidPtr(pynum);
VideoDetector *vd = static_cast<VideoDetector *>(tmp);
int result = vd->test();
return Py_BuildValue("i", result);
}
  static PyMethodDef VideoDetector_methods[] = {
{"VideoDetector", VideoDetector_Init    , METH_VARARGS},
{"test"    ,      VideoDetector_Test    , METH_VARARGS},
{"process"    ,   VideoDetector_Process , METH_VARARGS},
{NULL, NULL, 0}
};
  PyMODINIT_FUNC initVideoDetector(void)
{
Py_InitModule("VideoDetector", VideoDetector_methods);
}
  videodetector.py代码:
  from VideoDetector import *
  class videodetector(object):
def __init__(self, arg1, arg2):
  self._base = VideoDetector(arg1, arg2)
def test(self):
  return test(self._base)
def process(self, frame):
  return process(self._base, frame)
  
  camera.py代码:
  import cv2
import time
import datetime
import numpy as np
from videodetector import *
  frame_num = 0
  def motion_detect(obj, frame):
global frame_num
if frame_num % 5 == 0:
  print frame_num
  pixels = []
  for ch in frame.tostring():
   pixels.append(ord(ch))
  #rgb2yuv = np.array([[0.299, 0.587, 0.114],
        #                    [-0.14713, -0.28886, 0.436],
        #                    [0.615, -0.51499, -0.10001]])
  #rgb = np.array(pixels).reshape(len(pixels) / 3, 3)
  #yuv = np.dot(rgb, rgb2yuv.T)
  #y = np.array(yuv[ :, 0]).reshape(len(yuv), 1)
  #print yuv.shape
  #print y.shape
  #print obj.process(y)
  
  rgb = np.array(pixels).reshape(len(pixels) / 3, 3)
  r = rgb[ : , 0];
  g = rgb[ : , 1];
  b = rgb[ : , 2];
  raw = r + g + b;
  #print datetime.datetime.now().second
  #print datetime.datetime.now().microsecond
  print raw.shape;
  print obj.process(raw)
frame_num += 1
  
camera = cv2.VideoCapture(0)
fps = camera.get(cv2.cv.CV_CAP_PROP_FPS)
(width, height) = (int(camera.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)), int(camera.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)))
print width
print height
obj = videodetector(width, height)
#print obj.test()
  print("program begin")
while True:
(grabbed, frame) = camera.read()
if not grabbed:
  continue
cv2.imshow("Frame", frame)
motion_detect(obj, frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
  break
print("program end")
camera.release()
cv2.destroyAllWindows()
print("program release")
  
  效果如图3:
DSC0004.jpg
  图3

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-145360-1-1.html 上篇帖子: 高级正则表达式技术(Python版) 下篇帖子: python class对象转换成json/字典
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表