从Python到C++和B的管道图像

2024-04-25 02:14:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在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是空的。你知道吗


Tags: 代码name图像datasizestringincludemain
1条回答
网友
1楼 · 发布于 2024-04-25 02:14:53
<代码>中,C++阅读器调用^ {},而应该打开由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));
}

相关问题 更多 >