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 Web框架Pylons中使用MongoDB的例子
Dec 03 Python
Python常用的爬虫技巧总结
Mar 28 Python
Python+django实现简单的文件上传
Aug 17 Python
python中将一个全部为int的list 转化为str的list方法
Apr 09 Python
基于python历史天气采集的分析
Feb 14 Python
python之信息加密题目详解
Jun 26 Python
利用python实现汉字转拼音的2种方法
Aug 12 Python
Python3安装pip工具的详细步骤
Oct 14 Python
Python之Django自动实现html代码(下拉框,数据选择)
Mar 13 Python
python matplotlib:plt.scatter() 大小和颜色参数详解
Apr 14 Python
Python如何利用正则表达式爬取网页信息及图片
Apr 17 Python
python用海龟绘图写贪吃蛇游戏
Jun 18 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 cout&amp;lt;&amp;lt;的一点看法
2010/01/24 PHP
php通用防注入程序 推荐
2011/02/26 PHP
最新最全PHP生成制作验证码代码详解(推荐)
2016/06/12 PHP
php array_values 返回数组的值实例详解
2016/11/17 PHP
PHP PDOStatement::getAttribute讲解
2019/02/01 PHP
Javascript客户端脚本的设计和应用
2006/08/21 Javascript
当jQuery1.7遇上focus方法的问题
2014/01/26 Javascript
JS的参数传递示例介绍
2014/02/08 Javascript
javascript实现链接单选效果的方法
2015/05/13 Javascript
JavaScript组成、引入、输出、运算符基础知识讲解
2016/12/08 Javascript
js 获取今天以及过去日期
2017/04/11 Javascript
Bootstrap布局之栅格系统学习笔记
2017/05/04 Javascript
vue事件修饰符和按键修饰符用法总结
2017/07/25 Javascript
Django中使用jquery的ajax进行数据交互的实例代码
2017/10/15 jQuery
浅谈Node.js CVE-2017-14849 漏洞分析(详细步骤)
2017/11/10 Javascript
C#实现将一个字符转换为整数
2017/12/12 Javascript
JS实现的base64加密解密操作示例
2018/04/18 Javascript
MVVM 双向绑定的实现代码
2018/06/21 Javascript
js常见遍历操作小结
2019/06/06 Javascript
微信小程序 腾讯地图SDK 获取当前地址实现解析
2019/08/12 Javascript
Layui 动态禁止select下拉的例子
2019/09/03 Javascript
[01:08:48]LGD vs OG 2018国际邀请赛淘汰赛BO3 第三场 8.25
2018/08/29 DOTA
Python读取ini文件、操作mysql、发送邮件实例
2015/01/01 Python
使用python从三个角度解决josephus问题的方法
2020/03/27 Python
Python3+Appium安装及Appium模拟微信登录方法详解
2021/02/16 Python
欧迪办公美国官网:Office Depot
2016/08/22 全球购物
春秋航空官方网站:Spring Airlines
2017/09/27 全球购物
名词解释WEB SERVICE,SOAP,UDDI,WSDL,JAXP,JAXM;JSWDL开发包的介绍。
2012/10/27 面试题
大整数数相乘的问题
2012/07/22 面试题
班级聚会策划书
2014/01/16 职场文书
见习期自我鉴定
2014/01/31 职场文书
会计学专业自荐信
2014/06/25 职场文书
淘宝客服工作职责
2014/07/11 职场文书
店铺转让协议书(2014版)
2014/09/23 职场文书
监察局领导班子四风问题整改措施思想汇报
2014/10/05 职场文书
体育运动会广播稿
2014/10/05 职场文书