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 相关文章推荐
如何搜索查找并解决Django相关的问题
Jun 30 Python
跟老齐学Python之for循环语句
Oct 02 Python
python通过pil模块将raw图片转换成png图片的方法
Mar 16 Python
Django2.1集成xadmin管理后台所遇到的错误集锦(填坑)
Dec 20 Python
python 将对象设置为可迭代的两种实现方法
Jan 21 Python
Python Numpy计算各类距离的方法
Jul 05 Python
PyTorch中Tensor的维度变换实现
Aug 18 Python
Python pickle模块实现对象序列化
Nov 22 Python
python装饰器使用实例详解
Dec 14 Python
python环境下安装opencv库的方法
Mar 05 Python
Python开发入门——迭代的基本使用
Sep 03 Python
python中subplot大小的设置步骤
Jun 28 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 批量更新网页内容实现代码
2010/01/05 PHP
Windows下XDebug 手工配置与使用说明
2010/07/11 PHP
php若干单维数组遍历方法的比较
2011/09/20 PHP
PHP判断图片格式的七种方法小结
2013/06/03 PHP
php中操作memcached缓存进行增删改查数据的实现代码
2014/08/15 PHP
php运行时动态创建函数的方法
2015/03/16 PHP
jQuery 1.0.2
2006/10/11 Javascript
JS模拟多线程
2007/02/07 Javascript
JavaScript 异步方法队列链实现代码分析
2010/06/05 Javascript
JQuery最佳实践之精妙的自定义事件
2010/08/11 Javascript
jQuery的Scrollify插件实现滑动到页面下一节点
2015/07/05 Javascript
JavaScript 七大技巧(二)
2015/12/13 Javascript
a标签跳转到指定div,jquery添加和移除class属性的实现方法
2016/10/10 Javascript
微信小程序开发(一) 微信登录流程详解
2017/01/11 Javascript
Angular.js自定义指令学习笔记实例
2017/02/24 Javascript
前端必备插件之纯原生JS的瀑布流插件Macy.js
2017/11/22 Javascript
Vue拖拽组件开发实例详解
2018/05/11 Javascript
webpack的CSS加载器的使用
2018/09/11 Javascript
React降级配置及Ant Design配置详解
2018/12/27 Javascript
js字符串处理之绝妙的代码
2019/04/05 Javascript
详解如何使用router-link对象方式传递参数?
2019/05/02 Javascript
React优化子组件render的使用
2019/05/12 Javascript
详解python的数字类型变量与其方法
2016/11/20 Python
布隆过滤器的概述及Python实现方法
2019/12/08 Python
python下载的库包存放路径
2020/07/27 Python
python文件排序的方法总结
2020/09/13 Python
CSS3中currentColor关键字的妙用
2016/02/27 HTML / CSS
amazeui 验证按钮扩展的实现
2020/08/21 HTML / CSS
中国酒类在线零售网站:酒仙网
2016/08/20 全球购物
吉力贝官方网站:Jelly Belly
2019/03/11 全球购物
一篇.NET面试题
2014/09/29 面试题
生物专业个人自荐信范文
2013/11/29 职场文书
教师绩效工资方案
2014/02/01 职场文书
大学生求职简历自我评价
2015/03/02 职场文书
学校证明范文
2015/06/24 职场文书
解决numpy数组互换两行及赋值的问题
2021/04/17 Python