gpt4 book ai didi

python - 将图像从 python 传输到 C++ 并返回

转载 作者:行者123 更新时间:2023-11-30 04:46:01 29 4
gpt4 key购买 nike

我需要在 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;
}

python

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));
}

关于python - 将图像从 python 传输到 C++ 并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57004024/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com