python cv2 img encode and call clib
shm_input.c
1 int shm_send_pic(char* buf,int size) 2 { 3 if((buf == NULL) || (size <= 0)) 4 { 5 printf("para error\n"); 6 return -1; 7 } 8 9 int shmid = shmget(SHM_KEY,SHM_SIZE,IPC_CREAT|0664); 10 if(-1 == shmid) 11 { 12 printf("shmget fail\n"); 13 return -1; 14 } 15 16 void* ptr = shmat(shmid,NULL,0); 17 if(((void*)-1) == ptr) 18 { 19 printf("shmat fail\n"); 20 return -1; 21 } 22 23 int* pi = ptr; 24 *pi = size; 25 26 memcpy(ptr+sizeof(int),buf,size); 27 28 return 0; 29 }
gcc -o libc_send_pic.so -shared -fPIC shm_input.c
pytest.py
#!/usr/bin/python3 import cv2 import numpy as np import ctypes img = cv2.imread(picPath); img_encode = cv2.imencode(".jpg" , img)[1]; data_encode = np.array(img_encode); data_encode_c = data_encode.ctypes.data_as(ctypes.c_void_p); data_len = len(data_encode); loadLibrary = ctypes.cdll.LoadLibrary; cLib = loadLibrary("./libc_send_pic.so"); cLib.shm_send_pic(data_encode_c , data_len);
1.the first sizeof(int) bytes of the data should be the length of the follow data,and the rest of them are the data of the picture
2.you can write a ctest.c to get the share memory and write the data into a file , then change the file externsion to "jpg" to verify the method

浙公网安备 33010602011771号