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中threading模块join函数用法实例分析
Jun 04 Python
Python输出汉字字库及将文字转换为图片的方法
Jun 04 Python
python的pdb调试命令的命令整理及实例
Jul 12 Python
python保存网页图片到本地的方法
Jul 24 Python
python对列进行平移变换的方法(shift)
Jan 10 Python
Python脚本利用adb进行手机控制的方法
Jul 08 Python
基于python求两个列表的并集.交集.差集
Feb 10 Python
Python可变对象与不可变对象原理解析
Feb 25 Python
Python json读写方式和字典相互转化
Apr 18 Python
django 利用Q对象与F对象进行查询的实现
May 15 Python
python des,aes,rsa加解密的实现
Jan 16 Python
Python实现列表拼接和去重的三种方式
Jul 02 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写入WRITE编码为UTF8的文件的实现代码
2008/07/07 PHP
php中url函数介绍及使用示例
2014/02/13 PHP
php微信公众开发之获取周边酒店信息的方法
2014/12/22 PHP
详解PHP匿名函数与注意事项
2016/03/29 PHP
php实现购物车功能(以大苹果购物网为例)
2017/03/09 PHP
使弱类型的语言JavaScript变强势
2009/06/22 Javascript
js异步加载的三种解决方案
2013/03/04 Javascript
JS限制Textarea文本域字符个数的具体实现
2013/08/02 Javascript
js取值中form.all和不加all的区别介绍
2014/01/20 Javascript
jQuery中parents()方法用法实例
2015/01/07 Javascript
原生js和jquery实现图片轮播淡入淡出效果
2015/04/23 Javascript
JS不用正则验证输入的字符串是否为空(包含空格)的实现代码
2016/06/14 Javascript
终于实现了!精彩的jquery弹幕效果
2016/07/18 Javascript
javascript将中国数字格式转换成欧式数字格式的简单实例
2016/08/02 Javascript
JavaScript递归操作实例浅析
2016/10/31 Javascript
实现两个文本框同时输入的实例
2017/09/25 Javascript
详解webpack import()动态加载模块踩坑
2018/07/17 Javascript
Vue指令v-for遍历输出JavaScript数组及json对象的常见方式小结
2019/02/11 Javascript
vue.js this.$router.push获取不到params参数问题
2020/03/03 Javascript
如何配置vue.config.js 处理static文件夹下的静态文件
2020/06/19 Javascript
Python使用cookielib模块操作cookie的实例教程
2016/07/12 Python
Python错误: SyntaxError: Non-ASCII character解决办法
2017/06/08 Python
Python实现模拟分割大文件及多线程处理的方法
2017/10/10 Python
python执行使用shell命令方法分享
2017/11/08 Python
Pandas之ReIndex重新索引的实现
2019/06/25 Python
Python netmiko模块的使用
2020/02/14 Python
Python3爬虫中Ajax的用法
2020/07/10 Python
Python机器学习工具scikit-learn的使用笔记
2021/01/28 Python
CSS3转换功能transform主要属性值分析及实现分享
2012/05/06 HTML / CSS
HTML5实践-图片设置成灰度图
2012/11/12 HTML / CSS
法国二手MacBook销售网站:Okamac
2019/03/18 全球购物
中国汽车租赁行业头部企业:一嗨租车
2019/05/16 全球购物
全球烹饪课程的领先预订平台:Cookly
2020/01/28 全球购物
公司合作协议范文
2014/10/01 职场文书
药店收银员岗位职责
2015/04/07 职场文书
Python中super().__init__()测试以及理解
2021/12/06 Python