-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket_main.py
67 lines (51 loc) · 1.82 KB
/
websocket_main.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
import asyncio
import base64
import datetime
import sys
import time
import cv2
import websockets
from turbojpeg import TurboJPEG
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FPS, 40)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 768)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 576)
JPEG = TurboJPEG()
async def take_img():
ret, frame = cap.read()
# jpeg = JPEG.encode(frame, quality=80, jpeg_subsample=2)
# encoded_frame = base64.b64encode(jpeg).decode('utf-8')
# encode the frame as a JPEG image
_, jpeg = cv2.imencode(".jpg", frame)
# convert the JPEG image to a base64-encoded string
jpeg_bytes = jpeg.tobytes()
b64_bytes = base64.b64encode(jpeg_bytes)
b64_string = b64_bytes.decode("utf-8")
size = round(sys.getsizeof(b64_bytes) / (1024 * 1024) * 100) / 100
print(f'size of img is {size}')
# send the base64-encoded string over the WebSocket
return b64_string
async def handler(websocket, path):
# handle incoming messages from the client
print("client connected")
try:
while True:
start_time = time.perf_counter()
data = await take_img()
end_time = time.perf_counter()
elapsed_time_ms = (end_time - start_time) * 1000
print(
f'take_img fn took {elapsed_time_ms:.2f} to execute')
timestamp = datetime.datetime.now(datetime.timezone.utc)
print(timestamp)
await websocket.send(str(f"{data}, {timestamp}"))
except websockets.exceptions.ConnectionClosed:
print('Client disconnected')
async def main():
# create a WebSocket server on localhost, port 8000
async with websockets.serve(handler, "", 8000):
print("WebSocket server started")
# keep the server running indefinitely
await asyncio.Future()
# start the event loop
asyncio.run(main())