nicla_receiver.py
Go to the documentation of this file.
1 # BSD 3-Clause License
2 import socket
3 import numpy as np
4 import cv2
5 from pydub import AudioSegment
6 import argparse
7 
8 import NiclaReceiverUDP
9 
10 parser = argparse.ArgumentParser(
11  description="Read nicla data and show accordingly to the data type (no ros version)"
12 )
13 parser.add_argument("--ip", type=str, required=True)
14 parser.add_argument("--port", type=int, default=8002)
15 parser.add_argument("--packet_size", type=int, default=65540)
16 parser.add_argument("--audio_buffer", type=int, default=100)
17 args = parser.parse_args()
18 
19 FLAG = 1
20 accumulated_audio_data = []
21 
22 # image window init
23 cv2.namedWindow("niclabox", cv2.WINDOW_NORMAL)
24 
25 nicla_receiver_udp = NiclaReceiverUDP.NiclaReceiverUDP(
26  args.ip, args.port, args.packet_size, args.audio_buffer
27 )
28 
29 
30 def run():
31  global FLAG
32 
33  nicla_receiver_udp.receive()
34 
35  # Print distance
36  distance = int.from_bytes(nicla_receiver_udp.distance, "big")
37  print("Distance (mm): ", distance)
38 
39  if nicla_receiver_udp.image:
40  # Show image with numpy OpenCV
41  image = cv2.imdecode(
42  np.frombuffer(nicla_receiver_udp.image, np.uint8), cv2.IMREAD_COLOR
43  )
44  cv2.namedWindow("niclabox", cv2.WINDOW_NORMAL)
45  cv2.imshow("niclabox", image)
46  if cv2.waitKey(1) == ord("q"): # Press Q to exit
47  exit(0)
48 
49  # uncomment to output to a file without using numpy and OpenCV
50  # distance_file = open("distance.txt", "w")
51  # distance_file.write(str(distance))
52  # distance_file.close()
53  # picture_file = open("picture.jpg", "wb")
54  # picture_file.write(picture)
55  # picture_file.close()
56 
57  # Audio
58  if len(nicla_receiver_udp.audio_deque) >= args.audio_buffer:
59 
60  print("saving recordings!")
61 
62  audio_data = [
63  nicla_receiver_udp.audio_deque.popleft()
64  for _ in range(len(nicla_receiver_udp.audio_deque))
65  ]
66 
67  accumulated_audio_data = []
68  for i in audio_data:
69  accumulated_audio_data.append(np.frombuffer(i, dtype=np.int16))
70 
71  pcm_data = np.concatenate(accumulated_audio_data)
72 
73  # Create an AudioSegment from the PCM data
74  audio_segment = AudioSegment(
75  pcm_data.tobytes(), frame_rate=16000, sample_width=2, channels=1
76  )
77 
78  # Export AudioSegment to an MP3 file
79  audio_segment.export("recording.mp3", format="mp3")
80 
81  FLAG = 0
82 
83 
84 if __name__ == "__main__":
85 
86  nicla_receiver_udp.connect()
87 
88  while True:
89  try:
90  run()
91 
92  except OSError as e:
93  print("Error: ", e)
94  pass # try again
95 
96  except KeyboardInterrupt:
97  print("Closing!")
nicla_receiver.run
def run()
Definition: nicla_receiver.py:30


nicla_vision_ros
Author(s): Davide Torielli , Damiano Gasperini , Edoardo Del Bianco , Federico Rollo
autogenerated on Sat Nov 16 2024 03:38:18