【问题标题】:How can I send an image over a socket from C# to Python?如何通过套接字从 C# 向 Python 发送图像?
【发布时间】:2021-10-28 08:07:35
【问题描述】:

我正在尝试从手机上的摄像头拍摄图像并使用套接字将其发送到 Python 服务器。我使用 EncodePNG() 将图像转换为字节,然后添加为我的缓冲区生成一个标头,以告诉服务器缓冲区的主体有多大。

在客户端:

byte[] body = tex.EncodeToPNG(); // tex is the texture I convert to PNG
byte[] header = Encoding.UTF8.GetBytes(body.Length.ToString().PadLeft(6, '0'));
byte[] buff = new byte[body.Length + header.Length];

header.CopyTo(buff, 0);
body.CopyTo(buff, header.Length);
                    
stream.BeginWrite(buff, 0, buff.Length, null, null);

在 Python 服务器上,我正在接收标头,获取正文长度,然后尝试接收图像数据。

    headerBytes = client.recv(6)
    bodyLen = int(headerBytes.decode('utf-8'))


    e = 0
    data = ''
    while e < bodyLen:
        d = str(client.recv(size))
        e += len(d)
        data += d
        
     nparr = np.fromstring(data, np.uint8)
     frame = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
     cv2.imshow('frame', frame)

我收到异常 OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-85db8uu_\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor',这似乎是图像数据错误。

我已经有一段时间了,并尝试了我可以在其他答案中找到的所有内容,希望能指出正确的方向!谢谢!

【问题讨论】:

    标签: python c# sockets unity3d tcp


    【解决方案1】:

    看来OpenCV imshow 需要BGR 中的图像,所以你可以先尝试将其从RGB 转换为BGR。

    ...
    frameGBR = cv2.cvtColor(frame , cv2.COLOR_RGB2BGR)
    cv2.imshow('frame', frameGBR)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-17
      • 2013-03-24
      • 2013-12-31
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      相关资源
      最近更新 更多