python - 通过套接字在 python 中读取 opencv 图像

标签 python c++ sockets opencv

我正在尝试读取从 C++ 发送的 python 套接字中的 opencv 图像。

我能够将图像读入另一个 c++ 程序或 VB 程序并构建图像,但使用 python 我不明白发生了什么。

我发送 mat.data 的发送代码:

char *start_s = "<S><size>43434234<cols>64<rows>64<SE>";//plus I send the image size, cols, rows, which varies, not like the static char string shown
char *end_e = "<E>";
cv::Mat image_send = some_mat;
iResult = send( ConnectSocket, start_s, (int)strlen(start_s), 0 );
iResult = send( ConnectSocket, (const char *) image_send.data, i_buffer_size, 0 );
iResult = send( ConnectSocket, end_e, (int)strlen(end_e), 0 );

这是我用 python 尝试过的方法,但还没有成功。 image_cols 和 Image_rows 是从套接字中过滤出来的,这里没有显示,只有来自 c++ mat 的 image_mat.data 在我试图放入图像的套接字中:

data = conn.recv(4757560)
        if(i_Read_Image == 2) & (image_cols != 0) & (image_rows != 0):
            print ("Entering")
            #print(data)
            data2 = np.fromstring(data, dtype='uint8')
            img_np = cv2.imdecode(data2,cv2.IMREAD_COLOR )
            cv2.imshow('image',img_np)
            cv2.waitKey(0)

            #Also tried this
            #img = Image.new('RGB', (image_cols, image_rows))
            #img.putdata(data)

        #img5 = np.reshape(data2,(image_rows,image_cols))
        i_Read_Image = 0

最佳答案

在评论的帮助下,我得到了一个可行的答案。原始图像在单个数组 RGB 中,这需要重新整形并放入“RGB”图像中,可以在一行中完成:

img = Image.fromarray(data2.reshape(image_rows,image_cols,3), 'RGB')

并且当从套接字读取 opencv 数据数组时:这是可行的:

data = conn.recv(567667)
if(i_Read_Image == 2) & (image_cols != 0) & (image_rows != 0):
    data2 = np.fromstring(data, dtype='uint8')
    img = Image.fromarray(data2.reshape(image_rows,image_cols,3), 'RGB')
    img.show()

关于python - 通过套接字在 python 中读取 opencv 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47936365/

相关文章:

windows - 套接字泄漏在netstat和tcpview中未显示的Windows中

python - 如果标题中的所有单词 : match

python - 获取 .py 源文件的位置

c++ - 如何在没有调试符号和优化的情况下创建 cmake 构建配置?

C++ 指针片段

java - 在java上打开与一台服务器的两个端口连接

python - Numpy 点操作未使用所有 cpu 内核

python - 与python列表: are they or are they not iterators?混淆

c++ - 如何从编号的txt文件中读取? (data1.txt、data2.txt 等)

ruby-on-rails - Rails 5 应用程序(Action Cable)作为 Socket.io 服务器和客户端