python和C++共享内存传输图像的示例


Posted in Python onOctober 27, 2020

原理

python没有办法直接和c++共享内存交互,需要间接调用c++打包好的库来实现

流程

  • C++共享内存打包成库
  • python调用C++库往共享内存存图像数据
  • C++测试代码从共享内存读取图像数据

实现

1.c++打包库

创建文件

python和C++共享内存传输图像的示例

example.cpp

#include <iostream>
#include <cassert>
#include <stdlib.h>
#include <sys/shm.h>
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videoio.hpp"
 
#define key 650
#define image_size_max 1920*1080*3
 
using namespace std;
using namespace cv;
 
typedef struct{
int rows;
int cols;
uchar dataPointer[image_size_max];
}image_head;
 
int dump(int cam_num,int row_image, int col_image, void* block_data_image)
{
   int shm_id = shmget(key+cam_num,sizeof(image_head),IPC_CREAT);
   if(shm_id == -1)
   {
     cout<<"shmget error"<<endl;
      return -1;
   }
   cout << " shem id is  "<<shm_id<<endl;
 
   image_head *buffer_head;
   buffer_head = (image_head*) shmat(shm_id, NULL, 0);
 
   if((long)buffer_head == -1)
   {
     cout<<"Share memary can't get pointer"<<endl; 
      return -1; 
   }
    
   assert(row_image*col_image*3<=image_size_max);
   image_head image_dumper;
   image_dumper.rows=row_image;
   image_dumper.cols=col_image;
   uchar* ptr_tmp_image=(uchar*) block_data_image;
   for (int i=0;i<row_image*col_image*3;i++)
   {
      image_dumper.dataPointer[i] = *ptr_tmp_image;
      ptr_tmp_image++;
   }
   memcpy(buffer_head,&image_dumper,sizeof(image_dumper));
    
   return 1;
}
 
extern "C"
{
  int dump_(int cam_num,int row_image, int col_image, void* block_data_image)
  {
    int result=dump(cam_num,row_image, col_image, block_data_image);
    return result;
  }
}

CMakeLists.txt 

# cmake needs this line
cmake_minimum_required(VERSION 2.8)
 
# Define project name
project(opencv_example_project)
 
# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)
 
# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS "    version: ${OpenCV_VERSION}")
message(STATUS "    libraries: ${OpenCV_LIBS}")
message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")
 
if(CMAKE_VERSION VERSION_LESS "2.8.11")
  # Add OpenCV headers location to your include paths
  include_directories(${OpenCV_INCLUDE_DIRS})
endif()
 
# Declare the executable target built from your sources
add_library(opencv_example  SHARED example.cpp)
add_executable(test_example test_run.cpp)
 
# Link your application with OpenCV libraries
target_link_libraries(opencv_example ${OpenCV_LIBS})
target_link_libraries(test_example ${OpenCV_LIBS})

最后生成库

python和C++共享内存传输图像的示例

2.python调用C++动态库进行存图

#!/usr/bin/env python
 
import sys
 
#sys.path.append("/usr/lib/python3/dist-packages")
#sys.path.append("/home/frank/Documents/215/code/parrot-groundsdk/.python/py3/lib/python3.5/site-packages")
 
import cv2
import ctypes
import numpy as np
ll = ctypes.cdll.LoadLibrary
lib = ll("./build/libopencv_example.so")
lib.dump_.restype = ctypes.c_int
 
count = 1
#path = "/home/frank/Documents/215/2020.10.24/python_ctypes/image/"
 
while count < 30:
    path = "./image/"+str(count)+".jpg"
    print(path)
    image=cv2.imread(path)
     
    #cv2.imshow("test",image)
    #cv2.waitKey(0)
 
    image_data = np.asarray(image, dtype=np.uint8)
    image_data = image_data.ctypes.data_as(ctypes.c_void_p)
 
    value = lib.dump_(0,image.shape[0], image.shape[1], image_data)
    print(value)
 
    count += 1
 
    if count == 30:
        count = 1

3.C++读取共享内存获取图像

#include <iostream>
#include <stdlib.h>
#include <sys/shm.h>
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videoio.hpp"
 
#define key 650
#define image_size_max 1920*1080*3
 
using namespace cv;
using namespace std;
 
typedef struct{
int rows;
int cols;
uchar dataPointer[image_size_max];
}image_head;
 
int main()
{
  int count = 1;
  while(true)
  {
 
    int shm_id = shmget(key+0,sizeof(image_head) ,IPC_CREAT);
    if(shm_id == -1)
     {
        cout<<"shmget error"<<endl;
      return -1;
     }
    cout << " shem id is  "<<shm_id<<endl;
 
    image_head* buffer_head;
    buffer_head = (image_head*)shmat(shm_id, NULL, 0);
     
    if((long)buffer_head == -1)
    {
        perror("Share memary can't get pointer\n"); 
          return -1; 
    }
 
    image_head image_dumper;
    memcpy(&image_dumper, buffer_head, sizeof(image_head));
    cout<<image_dumper.rows<<"  "<<image_dumper.cols<<endl;
 
    uchar* data_raw_image=image_dumper.dataPointer;
 
    cv::Mat image(image_dumper.rows, image_dumper.cols, CV_8UC3);
    uchar* pxvec =image.ptr<uchar>(0);
    int count = 0;
    for (int row = 0; row < image_dumper.rows; row++)
    {
      pxvec = image.ptr<uchar>(row);
      for(int col = 0; col < image_dumper.cols; col++)
      {
        for(int c = 0; c < 3; c++)
        {
          pxvec[col*3+c] = data_raw_image[count];
          count++;
        }
      }
    }
 
   cv::imshow("Win",image);
   cv::waitKey(1);
 
  }
 
   return 1;
}

以上就是python和C++共享内存传输图像的示例的详细内容,更多关于python和c++传输图像的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python 中 Virtualenv 和 pip 的简单用法详解
Aug 18 Python
Python基础学习之常见的内建函数整理
Sep 06 Python
使用pandas中的DataFrame数据绘制柱状图的方法
Apr 10 Python
python3处理含有中文的url方法
May 10 Python
将Dataframe数据转化为ndarry数据的方法
Jun 28 Python
Django+Xadmin构建项目的方法步骤
Mar 06 Python
在Python中过滤Windows文件名中的非法字符方法
Jun 10 Python
python3+PyQt5 使用三种不同的简便项窗口部件显示数据的方法
Jun 17 Python
Python 函数用法简单示例【定义、参数、返回值、函数嵌套】
Sep 20 Python
python多维数组分位数的求取方式
Mar 03 Python
在django中使用post方法时,需要增加csrftoken的例子
Mar 13 Python
Django自关联实现多级联动查询实例
May 19 Python
安装Anaconda3及使用Jupyter的方法
Oct 27 #Python
Python通过yagmail实现发送邮件代码解析
Oct 27 #Python
关于Python不换行输出和不换行输出end=““不显示的问题(亲测已解决)
Oct 27 #Python
Python字符串查找基本操作代码案例
Oct 27 #Python
Python爬取豆瓣数据实现过程解析
Oct 27 #Python
UI自动化定位常用实现方法代码示例
Oct 27 #Python
基于python获取本地时间并转换时间戳和日期格式
Oct 27 #Python
You might like
海河写的 Discuz论坛帖子调用js的php代码
2007/08/23 PHP
php 过滤危险html代码
2009/06/29 PHP
js保存当前路径(cookies记录)
2010/12/14 Javascript
关于jquery ajax 调用带参数的webservice返回XML数据一个小细节
2012/07/31 Javascript
jq选项卡鼠标延迟的插件实例
2013/05/13 Javascript
浏览器页面区域大小的js获取方法
2013/09/21 Javascript
原生js实现淘宝首页点击按钮缓慢回到顶部效果
2014/04/06 Javascript
jQuery响应鼠标事件并隐藏与显示input默认值
2014/08/24 Javascript
node.js文件上传处理示例
2016/10/27 Javascript
JS实现HTML标签转义及反转义
2020/04/14 Javascript
vue中如何引入jQuery和Bootstrap
2017/04/10 jQuery
使用Node.js搭建静态资源服务详细教程
2017/08/02 Javascript
jQuery绑定事件方法及区别(bind,click,on,live,one)
2017/08/14 jQuery
微信小程序 上传头像的实例详解
2017/10/27 Javascript
利用nvm管理多个版本的node.js与npm详解
2017/11/02 Javascript
利用canvas中toDataURL()将图片转为dataURL(base64)的方法详解
2017/11/20 Javascript
jQuery实现每隔一段时间自动更换样式的方法分析
2018/05/03 jQuery
jquery实现简单自动轮播图效果
2020/07/29 jQuery
关于你不想知道的所有Python3 unicode特性
2014/11/28 Python
python下MySQLdb用法实例分析
2015/06/08 Python
Python实现保证只能运行一个脚本实例
2015/06/24 Python
Python中for循环和while循环的基本使用方法
2015/08/21 Python
python 删除字符串中连续多个空格并保留一个的方法
2018/12/22 Python
Python3 SSH远程连接服务器的方法示例
2018/12/29 Python
Flask框架学习笔记之表单基础介绍与表单提交方式
2019/08/12 Python
Python命令行参数解析工具 docopt 安装和应用过程详解
2019/09/26 Python
使用python实现男神女神颜值打分系统(推荐)
2019/10/31 Python
pandas实现excel中的数据透视表和Vlookup函数功能代码
2020/02/14 Python
Python 自由定制表格的实现示例
2020/03/20 Python
python中urllib.request和requests的使用及区别详解
2020/05/05 Python
python3通过qq邮箱发送邮件以及附件
2020/05/20 Python
Trina Turk官网:美国时装和泳装品牌
2018/06/10 全球购物
SHEIN美国:购买时髦的女性服装
2020/12/02 全球购物
比较一下entity bean和session bean
2013/12/27 面试题
2015年小学一年级班主任工作总结
2015/05/21 职场文书
python实战之90行代码写个猜数字游戏
2021/04/22 Python