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

问题描述 投票:1回答:1

我试图在从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
python c++ sockets opencv
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.