[英]Pipe image from python to C++ and back
我需要在Python中讀取圖像(使用OpenCV),將其通過管道傳輸到C ++程序,然后再通過管道傳輸回Python。 到目前為止,這是我的代碼:
C ++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cv.h>
#include <highgui.h>
#include <cstdio>
#include <sys/stat.h>
using namespace std;
using namespace cv;
int main(int argc, char *argv[]) {
const char *fifo_name = "fifo";
mknod(fifo_name, S_IFIFO | 0666, 0);
ifstream f(fifo_name);
string line;
getline(f, line);
auto data_size = stoi(line);
char *buf = new char[data_size];
f.read(buf, data_size);
Mat matimg;
matimg = imdecode(Mat(1, data_size, CV_8UC1, buf), CV_LOAD_IMAGE_UNCHANGED);
imshow("display", matimg);
waitKey(0);
return 0;
}
蟒蛇
import os
import cv2
fifo_name = 'fifo'
def main():
data = cv2.imread('testimage.jpg').tobytes()
try:
os.mkfifo(fifo_name)
except FileExistsError:
pass
with open(fifo_name, 'wb') as f:
f.write('{}\n'.format(len(data)).encode())
f.write(data)
if __name__ == '__main__':
main()
當C ++嘗試打印到圖像時,將引發異常。 我已經調試了代碼, buf
已填充,但是matimg
為空。
在代碼中,C ++讀取器調用mknod
,而它應該只打開由Python編寫器創建的現有命名管道。
如果讀者嘗試打開該管道時不存在該管道,則它可能會失敗,也可能會繼續嘗試以超時重新打開命名管道。 例如:
const char *fifo_name = "fifo";
std::ifstream f;
for(;;) { // Wait till the named pipe is available.
f.open(fifo_name, std::ios_base::in);
if(f.is_open())
break;
std::this_thread::sleep_for(std::chrono::seconds(3));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.