【发布时间】:2019-07-12 09:22:37
【问题描述】:
我需要在 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是空的。
【问题讨论】: