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 多进程通信模块的简单实现
Feb 20 Python
Python面向对象特殊成员
Apr 24 Python
python实现RabbitMQ的消息队列的示例代码
Nov 08 Python
win7 x64系统中安装Scrapy的方法
Nov 18 Python
python+selenium实现QQ邮箱自动发送功能
Jan 23 Python
Python3 pip3 list 出现 DEPRECATION 警告的解决方法
Feb 16 Python
Python使用sqlalchemy模块连接数据库操作示例
Mar 13 Python
Python网络爬虫之爬取微博热搜
Apr 18 Python
基于Python 中函数的 收集参数 机制
Dec 21 Python
Python如何通过百度翻译API实现翻译功能
Apr 02 Python
jupyter lab的目录调整及设置默认浏览器为chrome的方法
Apr 10 Python
python程序需要编译吗
Jun 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
php学习 函数 课件
2008/06/15 PHP
利用yahoo汇率接口实现实时汇率转换示例 汇率转换器
2014/01/14 PHP
PHP也能干大事 随机函数
2015/04/14 PHP
用JavaScript实现仿Windows关机效果
2007/03/10 Javascript
AMD异步模块定义介绍和Require.js中使用jQuery及jQuery插件的方法
2014/06/06 Javascript
javaScript中两个等于号和三个等于号之间的区别介绍
2014/06/27 Javascript
angularjs指令中的compile与link函数详解
2014/12/06 Javascript
Bootstrap响应式侧边栏改进版
2016/09/17 Javascript
JS框架之vue.js(深入三:组件1)
2016/09/29 Javascript
Javascript 实现微信分享(QQ、朋友圈、分享给朋友)
2016/10/21 Javascript
js无提示关闭浏览器窗口的两种方法分析
2016/11/06 Javascript
详解JavaScript树结构
2017/01/09 Javascript
jquery实现全选、全不选以及单选功能
2017/03/23 jQuery
Bootstrap图片轮播效果详解
2017/10/17 Javascript
iview table高度动态设置方法
2018/03/14 Javascript
vue.js前后端数据交互之提交数据操作详解
2018/04/24 Javascript
vue-test-utils初使用详解
2019/05/23 Javascript
使用axios请求接口,几种content-type的区别详解
2019/10/29 Javascript
解决vue的touchStart事件及click事件冲突问题
2020/07/21 Javascript
Python使用scrapy采集时伪装成HTTP/1.1的方法
2015/04/08 Python
Python程序员面试题 你必须提前准备!(答案及解析)
2018/01/23 Python
python实现flappy bird游戏
2018/12/24 Python
Python 多个图同时在不同窗口显示的实现方法
2019/07/07 Python
如何将tensorflow训练好的模型移植到Android (MNIST手写数字识别)
2020/04/22 Python
python不同系统中打开方法
2020/06/23 Python
解决Windows下python和pip命令无法使用的问题
2020/08/31 Python
css3中用animation的steps属性制作帧动画
2019/04/25 HTML / CSS
英国音乐设备和乐器商店:Gear4music
2017/10/16 全球购物
中英双版中文教师求职信
2013/10/27 职场文书
诉讼授权委托书
2014/10/15 职场文书
党员思想汇报材料
2014/12/19 职场文书
针对吵架老公保证书
2015/05/08 职场文书
第一军规观后感
2015/06/12 职场文书
实验室安全管理制度
2015/08/05 职场文书
Pycharm远程调试和MySQL数据库授权问题
2022/03/18 MySQL
使用Python解决图表与画布的间距问题
2022/04/11 Python