AO656
2021-05-21 01:12
采纳率: 90.9%
浏览 289

如何使用python的socket传输numpy格式的图片?

我想用socket在两台机器之间传输图片

cilent

import socket
import cv2
from PIL import ImageGrab
import numpy as np
HOST = '127.0.0.1'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
img=ImageGrab.grab()
img_np=np.array(img)
frame=cv2.cvtColor(img_np,cv2.COLOR_BGR2RGB)
s.send(str(frame).encode("utf-8"))
cv2.destroyAllWindows()
s.close()

serve

import socket
import threading
import cv2
import numpy as np
HOST = '0.0.0.0'  # 本地localhost
PORT = 50007
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
def tcp(a):
    while 1:
        data = a.recv(102400)
        data=data.decode("utf-8")
        data=np.array(data)
        if not data:
            break
        cv2.imshow('screen',data)
        cv2.waitKey(0)
    a.close()
while 1:
    conn, addr = s.accept()#接受连接
    print('Connected by', addr)
    t= threading.Thread(target=tcp,args=(conn,))#创建线程
    t.setDaemon(True)#设置为后台线程,这里默认是False,设置为True之后则主线程不用等待子线程
    t.start()
    continue

输出后两端的frame和data数据和类型都一模一样,但为什么用imshow时报

cv2.error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'imshow'
> Overload resolution failed:
>  - mat data type = 19 is not supported
>  - Expected Ptr<cv::cuda::GpuMat> for argument 'mat'
>  - Expected Ptr<cv::UMat> for argument 'mat'
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新