Image transmission based on the Internet is very common. The most common way is to compress the image into jpeg first, and then send it to the client through the socket. The code is directly uploaded below.
- 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