-
Notifications
You must be signed in to change notification settings - Fork 1
/
Endpoint.py
76 lines (62 loc) · 2.56 KB
/
Endpoint.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# This file is a class stream wrapper meant to read in a video stream from a raspberry pi and return the frames.
# This file works in conjunction with piVideoStream.py.
# The ip address and connection port should be passed to constructor.
# Endpoint.py
import io
import socket
import struct
from PIL import Image
import numpy as np
import cv2
import math
class Endpoint():
def __init__(self, host='', port=30000):
# Create server socket
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Listen on all host, port
self.server_socket.bind((host, port))
# Queue at most 1 connection
self.server_socket.listen(1)
# Accept a single connection and make a file-like object out of it
self.connection = self.server_socket.accept()[0].makefile('rb')
# Width and height of the video stream from the PI
self.imW, self.imH = 640, 480
# Construct a stream to hold the image data and read the image
# data from the connection. Probably are better ways, but this works for now
self.image_stream = io.BytesIO()
print("Successfully Established connection with Pi")
# Returns (true, frame) on success
# (false, None) on failure
def read(self):
# Read the length of the image as a 32-bit unsigned int.
image_len = struct.unpack('<L', self.connection.read(struct.calcsize('<L')))[0]
if image_len == False:
return (False, None)
# TODO: make thread-safe queue later
self.image_stream = io.BytesIO()
image = None
try:
# reading jpeg image from binary stream
self.image_stream.write(self.connection.read(image_len))
# reconstruct image with pillow
image = Image.open(self.image_stream)
except:
# if reading raw images: yuv or rgb
image = Image.frombytes('L', (self.imW, self.imH), self.image_stream.read())
# Rewind the stream
self.image_stream.seek(0)
#Convert to cv2 usable image
npImage = np.array(image)
return (True, npImage)
# Detects if socket stream still open by checking file status
def isOpened(self):
try:
return self.connection.readable()
except Exception as e:
return False
# Wraps up sockets, call this before closing program.
# Would put in constructor, but have to replicate cv2 behaviour
def release(self):
print("release\n")
self.connection.close()
self.server_socket.close()