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读取网页内容的方法
Jul 30 Python
使用Python生成随机密码的示例分享
Feb 18 Python
利用python获取某年中每个月的第一天和最后一天
Dec 15 Python
Python列表切片用法示例
Apr 19 Python
Python实现判断给定列表是否有重复元素的方法
Apr 11 Python
详解TensorFlow查看ckpt中变量的几种方法
Jun 19 Python
python实现图片筛选程序
Oct 24 Python
python使用mitmproxy抓取浏览器请求的方法
Jul 02 Python
python实现将视频按帧读取到自定义目录
Dec 10 Python
Python基于paramunittest模块实现excl参数化
Apr 26 Python
Python pygame实现中国象棋单机版源码
Jun 20 Python
Python matplotlib多个子图绘制整合
Apr 13 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实现弹出消息提示框的两种方法
2013/12/17 PHP
PHP file_get_contents函数读取远程数据超时的解决方法
2015/05/13 PHP
php轻量级的性能分析工具xhprof的安装使用
2015/08/12 PHP
如何在旧的PHP系统中使用PHP 5.3之后的库
2015/12/02 PHP
Laravel5.* 打印出执行的sql语句的方法
2017/07/24 PHP
使用Java实现简单的server/client回显功能的方法介绍
2013/05/03 Javascript
面向对象设计模式的核心法则
2013/11/10 Javascript
JavaScript中按位“异或”运算符使用介绍
2014/03/14 Javascript
jQuery 过滤方法filter()选择具有特殊属性的元素
2014/06/15 Javascript
JS获取当前网页大小以及屏幕分辨率等
2014/09/05 Javascript
javascript学习笔记(四)function函数部分
2014/09/30 Javascript
JavaScript版的TwoQueues缓存模型
2014/12/29 Javascript
Nodejs中调用系统命令、Shell脚本和Python脚本的方法和实例
2015/01/01 NodeJs
js判断手机和pc端选择不同执行事件的方法
2015/01/30 Javascript
JS实现网页游戏中滑块响应鼠标点击移动效果
2015/10/19 Javascript
JS验证邮件地址格式方法小结
2015/12/01 Javascript
Jquery插件仿百度搜索关键字自动匹配功能
2016/05/11 Javascript
javascript实现简易计算器的代码
2016/05/31 Javascript
JS检测页面中哪个HTML标签触发点击事件的方法
2016/06/17 Javascript
javascript事件冒泡简单示例
2016/06/20 Javascript
JavaScript动态数量的文件上传控件
2016/11/18 Javascript
React学习之事件绑定的几种方法对比
2017/09/24 Javascript
vue+axios实现post文件下载
2019/09/25 Javascript
举例讲解Python中is和id的用法
2015/04/03 Python
Python自动发送邮件的方法实例总结
2018/12/08 Python
python脚本执行CMD命令并返回结果的例子
2019/08/14 Python
django前端页面下拉选择框默认值设置方式
2020/08/09 Python
Django实现微信小程序支付的示例代码
2020/09/03 Python
iRobot官网:改变生活的家用机器人品牌
2016/09/20 全球购物
大学校庆策划书
2014/01/31 职场文书
函授药学自我鉴定
2014/02/07 职场文书
家长寄语大全
2014/04/02 职场文书
2014年秋季开学寄语
2014/08/02 职场文书
甘南现象心得体会
2014/09/11 职场文书
测量员岗位职责
2015/02/14 职场文书
2015年乡镇发展党员工作总结
2015/03/31 职场文书