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 random模块(获取随机数)常用方法和使用例子
May 13 Python
python中MySQLdb模块用法实例
Nov 10 Python
Perl中著名的Schwartzian转换问题解决实现
Jun 02 Python
pytorch + visdom 处理简单分类问题的示例
Jun 04 Python
python遍历文件夹找出文件夹后缀为py的文件方法
Oct 21 Python
判断python对象是否可调用的三种方式及其区别详解
Jan 31 Python
python 列表输出重复值以及对应的角标方法
Jun 11 Python
使用Tensorflow实现可视化中间层和卷积层
Jan 24 Python
pygame实现弹球游戏
Apr 14 Python
Pycharm IDE的安装和使用教程详解
Apr 30 Python
如何利用python检测图片是否包含二维码
Oct 15 Python
PO模式在selenium自动化测试框架的优势
Mar 20 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中将一段数据存到一个txt文件中并显示其内容
2014/08/15 PHP
php使用unset()删除数组中某个单元(键)的方法
2015/02/17 PHP
十个PHP高级应用技巧果断收藏
2015/09/25 PHP
php防止CC攻击代码 php防止网页频繁刷新
2015/12/21 PHP
jqGrid增加时--判断开始日期与结束日期(实例解析)
2013/11/08 Javascript
IE中JS跳转丢失referrer问题的2个解决方法
2014/07/18 Javascript
学习JavaScript设计模式之责任链模式
2016/01/18 Javascript
JavaScript中文件上传API详解
2016/04/01 Javascript
使用jQuery加载html页面到指定的div实现方法
2016/07/13 Javascript
jQuery Select下拉框操作小结(推荐)
2016/07/22 Javascript
VUE实现一个分页组件的示例
2017/09/13 Javascript
Nuxt.js实战详解
2018/01/18 Javascript
vue悬浮可拖拽悬浮按钮的实例代码
2019/08/20 Javascript
[04:52]2015国际邀请赛LGD战队晋级之路
2015/08/14 DOTA
用Python代码来解图片迷宫的方法整理
2015/04/02 Python
简单介绍使用Python解析并修改XML文档的方法
2015/10/15 Python
python递归查询菜单并转换成json实例
2017/03/27 Python
TensorFlow搭建神经网络最佳实践
2018/03/09 Python
python 实现将字典dict、列表list中的中文正常显示方法
2018/07/06 Python
Python框架Flask的基本数据库操作方法分析
2018/07/13 Python
Django中使用第三方登录的示例代码
2018/08/20 Python
Python 按字典dict的键排序,并取出相应的键值放于list中的实例
2019/02/12 Python
python从zip中删除指定后缀文件(推荐)
2019/12/05 Python
Python中remove漏删和索引越界问题的解决
2020/03/18 Python
英国最大的滑板品牌选择:Route One
2019/09/22 全球购物
汽车工程专业应届生求职信
2013/10/19 职场文书
工厂保安员岗位职责
2014/01/31 职场文书
求职毕业生自荐书
2014/02/08 职场文书
模具专业自荐信
2014/05/29 职场文书
中药学自荐信
2014/06/15 职场文书
2014年护理部工作总结
2014/11/14 职场文书
委托书的样本
2015/01/28 职场文书
面试通知短信
2015/04/20 职场文书
2016年寒假社会实践活动心得体会
2015/10/09 职场文书
phpQuery解析HTML乱码问题(补充官网未列出的乱码解决方案)
2021/04/01 PHP
教你做个可爱的css滑动导航条
2021/06/15 HTML / CSS