基于python的网络图片传输

文章目录


基于互联网的图片传输非常普遍,最常见的是通过先把图片压缩成jpeg,再通过socket发送到客户端,下面直接上代码。

  • socket
    • send
    • recv
  • imencode
  • imdecode

server

#!/usr/bin/env python3
#-*- coding: utf -*-
import socket
import cv2

s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))

camera = cv2.VideoCapture(0)
if camera.isOpened():
    success, frame = camera.read()

s.listen(5)
c, addr = s.accept()

while True:
    success, frame = camera.read()
    result, img_code = cv2.imencode('.jpg', frame)
    buffer = frame.tobytes()
    c.send(buffer)

c.close()  # 关闭连接

client

#!/usr/bin/env python3
#-*- coding: utf -*-
import socket
import cv2
import numpy as np

s = socket.socket()
host = socket.gethostname()
port = 12345

s.connect((host, port))

while True:
    data = s.recv(921600)
    buffer = np.frombuffer(data, np.uint8)
    frame = buffer.reshape(480, 640, 3)
    frame2 = cv2.flip(frame, 1)
    cv2.imshow('image', frame2)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()
s.close()

–end

猜你喜欢

转载自blog.csdn.net/tianzong2019/article/details/123063114