title: send image opencv c++ to python
body: <p>I open the picture with python, send it to the C ++ function for processing, and return the picture. How to correctly get a picture from a c ++ function?</p>
  
  <h3>Segmentation error</h3>
  
  <p>Code example:</p>
  
  <h1>C++</h1>
  
  <pre><code>// t_lib.cpp 
  #include "opencv2/opencv.hpp"
  
  extern "C" unsigned char*  getfg(int rows,int cols, unsigned char* fdata)
  //extern "C" void getfg(int rows,int cols, unsigned char* fdata)
  {
      cv::Mat frame = cv::Mat(rows, cols, CV_8UC3, (void *) fdata);
      // Work 
      //cv::imshow("Display window C++", frame);
      //cv::waitKey(0);
  
      // do something
  
      return frame.data; //fdata;
  }
  </code></pre>
  
  <h1>Python 2.7</h1>
  
  <pre><code># test.py
  import cv2
  import numpy as np
  import ctypes
  lib = ctypes.cdll.LoadLibrary('./lib.so')
  
  def getfg(img):
      ptr = lib.getfg(img.shape[0], img.shape[1], img.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte)))
      buf = (ctypes.c_ubyte * img.shape[0] * img.shape[1]  * 3).from_address(ptr)
      res = np.ndarray(buffer=buf, dtype=np.uint8, shape=(img.shape[0], img.shape[1], 3), order="C")
      return res
  
  f = cv2.imread("sample.jpg")
  #gray_image = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
  AS = getfg(f)
  print AS.shape
  #np.array(AS)[0]
  cv2.imshow("Window Python", AS)
  cv2.waitKey(0)
  </code></pre>
  
  <p>Compilation:</p>
  
  <pre><code>g++ -c -fPIC t_lib.cpp -o lib -lX11 $(pkg-config opencv --cflags --libs) -I/usr/include/python2.7 -I/usr/lib/python2.7;
  
  g++ -shared -Wl,-soname,lib.so -o lib.so lib -lopencv_core -lopencv_highgui -lopencv_imgproc
  </code></pre>
  
  <p>command for see opencv libs:</p>
  
  <pre>pkg-config opencv --cflags --libs</pre>
  
  <p>output:</p>
  
  <pre>-I/usr/include/opencv -lopencv_shape -lopencv_stitching 
  -lopencv_superres -lopencv_videostab -lopencv_aruco 
  -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib
  -lopencv_datasets -lopencv_dpm -lopencv_face 
  -lopencv_freetype -lopencv_fuzzy -lopencv_hdf 
  -lopencv_line_descriptor -lopencv_optflow -lopencv_video 
  -lopencv_plot -lopencv_reg -lopencv_saliency -lopencv_stereo 
  -lopencv_structured_light -lopencv_phase_unwrapping -lopencv_rgbd 
  -lopencv_viz -lopencv_surface_matching -lopencv_text 
  -lopencv_ximgproc -lopencv_calib3d -lopencv_features2d 
  -lopencv_flann -lopencv_xobjdetect -lopencv_objdetect 
  -lopencv_ml -lopencv_xphoto -lopencv_highgui 
  -lopencv_videoio -lopencv_imgcodecs -lopencv_photo 
  -lopencv_imgproc -lopencv_core
  </pre>
  
  <p><strong>version c++ OpenCV 3.2.0</strong></p>