树莓派/PC实现实时摄像头数据共享(Python—picamera)

上次实验使用Python—OpenCV实现,发现传输效果并不是很理想,接下来使用Python和picamera实现树莓派/PC实时摄像头数据共享,主要也可分为服务器和客户端两部分。

服务器(PC/树莓派)Demo如下:

  1. import numpy as np
  2. import cv2
  3. import socket
  4. class VideoStreamingTest(object):
  5. def __init__(self, host, port):
  6. self.server_socket = socket.socket()
  7. self.server_socket.bind((host, port))
  8. self.server_socket.listen(0)
  9. self.connection, self.client_address = self.server_socket.accept()
  10. self.connection = self.connection.makefile('rb')
  11. self.host_name = socket.gethostname()
  12. self.host_ip = socket.gethostbyname(self.host_name)
  13. self.streaming()
  14. def streaming(self):
  15. try:
  16. print("Host: ", self.host_name + ' ' + self.host_ip)
  17. print("Connection from: ", self.client_address)
  18. print("Streaming...")
  19. print("Press 'q' to exit")
  20. # need bytes here
  21. stream_bytes = b' '
  22. while True:
  23. stream_bytes += self.connection.read(1024)
  24. first = stream_bytes.find(b'\xff\xd8')
  25. last = stream_bytes.find(b'\xff\xd9')
  26. if first != -1 and last != -1:
  27. jpg = stream_bytes[first:last + 2]
  28. stream_bytes = stream_bytes[last + 2:]
  29. image = cv2.imdecode(np.frombuffer(jpg, dtype=np.uint8),
  30. cv2.IMREAD_COLOR)
  31. cv2.imshow('image', image)
  32. if cv2.waitKey(1) & 0xFF == ord('q'):
  33. break
  34. finally:
  35. self.connection.close()
  36. self.server_socket.close()
  37. if __name__ == '__main__':
  38. # host, port
  39. h, p = "192.168.0.4", 8000
  40. VideoStreamingTest(h, p)

客户端(树莓派)Demo如下:

  1. import io
  2. import socket
  3. import struct
  4. import time
  5. import picamera
  6. # create socket and bind host
  7. client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  8. client_socket.connect(('192.168.2.104', 8000))
  9. connection = client_socket.makefile('wb')
  10. try:
  11. with picamera.PiCamera() as camera:
  12. camera.resolution = (320, 240) # pi camera resolution
  13. camera.framerate = 15 # 15 frames/sec
  14. time.sleep(2) # give 2 secs for camera to initilize
  15. start = time.time()
  16. stream = io.BytesIO()
  17. # send jpeg format video stream
  18. for foo in camera.capture_continuous(stream, 'jpeg', use_video_port = True):
  19. connection.write(struct.pack('<L', stream.tell()))
  20. connection.flush()
  21. stream.seek(0)
  22. connection.write(stream.read())
  23. if time.time() - start > 600:
  24. break
  25. stream.seek(0)
  26. stream.truncate()
  27. connection.write(struct.pack('<L', 0))
  28. finally:
  29. connection.close()
  30. client_socket.close()

无论是运行速度还是画质都是比较理想的。

树莓派与PC视频数据传输 最优方法:https://blog.csdn.net/m0_38106923/article/details/86562451

关注公众号,发送关键字:Java车牌识别,获取项目源码。