RaCamera.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. # -*- coding:UTF-8 -*-
  2. import cv2
  3. import threading
  4. import time
  5. from picamera import PiCamera
  6. from datetime import datetime
  7. import os
  8. import subprocess
  9. import json
  10. import signal
  11. class RaCamera:
  12. camera_active = False
  13. __recording_active = False
  14. camera_recording = False
  15. __frame = None
  16. __recordingThread=None
  17. __writer=None
  18. #recording_path="/home/admin/Video/"
  19. video_resulution_x = 1920
  20. video_resulution_y = 1080
  21. video_fps = 8.0
  22. video_duration = 30
  23. def __init__(self, Components):
  24. """
  25. Initialisiert das RaCamera
  26. :param Components: RaComponents Element
  27. :type Components: RaComponents
  28. """
  29. self.components = Components
  30. def startCamera(self):
  31. if self.camera_active==True:
  32. return
  33. print("Start Camera")
  34. self.camera_active = True
  35. self.__cameraThread = threading.Thread(target = self.threadCamera)
  36. self.lock = threading.Lock()
  37. print("- Starting Thread")
  38. self.__cameraThread.start()
  39. time.sleep(0.2)
  40. def stopCamera(self):
  41. if self.camera_active==False:
  42. return
  43. print("Stop Camera")
  44. self.camera_active = False
  45. print("- Wait for Thread ending")
  46. self.__cameraThread.join()
  47. print("- Stop recording")
  48. self.stopRecording()
  49. self.__frame = None
  50. def makePhoto(self, filename="test.jpg"):
  51. camera = PiCamera()
  52. camera.start_preview()
  53. sleep(5)
  54. camera.capture(filename)
  55. camera.stop_preview()
  56. def startRecording(self):
  57. if self.camera_recording == True:
  58. print("Recording already started")
  59. return
  60. print("Start Recording")
  61. self.camera_recording = True
  62. #self.startCamera()
  63. self.lock = threading.Lock()
  64. self.__recordingThread = threading.Thread(target = self.treadRecording)
  65. self.__recordingThread.start()
  66. def stopRecording(self):
  67. if self.camera_recording==False:
  68. print("Recording already stopped")
  69. return
  70. print("Stop Recording")
  71. if self.__recording_active == True:
  72. os.killpg(os.getpgid(self.record_process.pid), signal.SIGTERM)
  73. self.__recording_active = False
  74. self.camera_recording = False
  75. self.__recordingThread.join()
  76. def getFrame(self):
  77. return self.__frame
  78. def isActive(self):
  79. return self.camera_active
  80. def isRecording(self):
  81. return self.camera_recording
  82. def treadRecording__old(self):
  83. with self.lock:
  84. while self.camera_recording == True:
  85. startDate = datetime.today()
  86. startTime = time.perf_counter()
  87. ##fourcc = cv2.VideoWriter_fourcc(*'X264')
  88. #fourcc = cv2.VideoWriter_fourcc(*'mp4v')
  89. ##fourcc = cv2.VideoWriter_fourcc(*'xvid')
  90. ##fourcc = cv2.VideoWriter_fourcc(*'XVID')
  91. ##fourcc = cv2.VideoWriter_fourcc(*'MJPG')
  92. ##fourcc = cv2.VideoWriter_fourcc(*'DIVX')
  93. ##fourcc = cv2.VideoWriter_fourcc(*'WMV1')
  94. ##fourcc = cv2.VideoWriter_fourcc(*'WMV1')
  95. ##fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
  96. filename = startDate.strftime("%Y-%m-%d_%H-%M-%S") + ".mp4"
  97. #print("- Video File Recording: "+self.recording_path+filename)
  98. #print("- FPS: "+str(self.video_fps))
  99. #print("- Resolution: "+str(self.video_resulution_x)+"x"+str(self.video_resulution_y))
  100. #
  101. #self.__writer = cv2.VideoWriter(self.recording_path+filename, fourcc, self.video_fps, (self.video_resulution_x, self.video_resulution_y))
  102. #self.__recording_active = True
  103. #
  104. #while self.camera_recording == True and self.__recording_active == True and time.perf_counter() - startTime < self.video_duration:
  105. # time.sleep(1)
  106. #
  107. #print("- Video File closing")
  108. #self.__recording_active = False
  109. #time.sleep(0.5)
  110. #self.__writer.release()
  111. #if os.path.isfile(self.recording_path+filename) == False:
  112. # print("NO VIDEO FILE FOUND")
  113. def treadRecording(self):
  114. maxVids = 5
  115. with self.lock:
  116. while self.camera_recording == True:
  117. startDate = datetime.today()
  118. startTime = time.perf_counter()
  119. filename = "/"+startDate.strftime("%Y-%m-%d_%H-%M-%S") + ".h264"
  120. # Record CommandLine
  121. # raspivid -o myvid.h264 -w 1280 -h 720 -b 8000000
  122. # -w, --width : Set image width <size>. Default 1920
  123. # -h, --height : Set image height <size>. Default 1080
  124. # -b, --bitrate : Set bitrate. Use bits per second
  125. # (e.g. 10MBits/s would be -b 10000000)
  126. # -o, --output : Output filename <filename>
  127. # -v, --verbose : Output verbose information during run
  128. # -t, --timeout : Duration of video (in ms)
  129. # -d, --demo : Demo mode(cycle through range of camera
  130. # options, no capture)
  131. # -fps, --framerate : Specify the frames per second to record
  132. # -e, --penc : Display preview image *after* encoding
  133. # (shows compression artifacts)
  134. # -p, --preview : Preview window settings <'x,y,w,h'>
  135. # -f, --fullscreen : Fullscreen preview mode
  136. # -n, --nopreview : Do not display a preview window
  137. # -sh, --sharpness : Set image sharpness (-100 to 100)
  138. # -co, --contrast : Set image contrast (-100 to 100)
  139. # -br, --brightness : Set image brightness (0 to 100)
  140. # -sa, --saturation : Set image saturation (-100 to 100)
  141. # -ISO, --ISO : Set capture ISO
  142. # -vs, --vstab : Turn on video stablisation
  143. # -ev, --ev : Set EV compensation
  144. # -ex, --exposure : Set exposure mode (see Notes)
  145. # -awb, --awb : Set AWB mode (see Notes)
  146. # -ifx, --imxfx : Set image effect (see Notes)
  147. # -cfx, --colfx : Set colour effect (U:V)
  148. # -mm, --metering : Set metering mode (see Notes)
  149. # -rot, --rotation : Set image rotation (0, 90, 180, 270)
  150. # -hf, --hflip : Set horizontal flip
  151. # -vf, --vflip : Set vertical flip
  152. width = 1920
  153. height = 1080
  154. duration = 30000
  155. video_dir = "./"
  156. with open("config.json", "r") as file:
  157. cfg = json.load(file)
  158. if "dir" in cfg["recording"]:
  159. video_dir = cfg["recording"]["dir"]
  160. video_config = [
  161. "raspivid",
  162. "-o " + video_dir + filename,
  163. "-n"
  164. ]
  165. self.appendRecordingConfig(cfg,video_config, "hf", "hflip", "bool")
  166. self.appendRecordingConfig(cfg,video_config, "vf", "vflip", "bool")
  167. self.appendRecordingConfig(cfg,video_config, "w", "width", "int", width)
  168. self.appendRecordingConfig(cfg,video_config, "h", "height", "int", height)
  169. self.appendRecordingConfig(cfg,video_config, "fps", "fps", "int")
  170. self.appendRecordingConfig(cfg,video_config, "b", "bitrate", "int")
  171. self.appendRecordingConfig(cfg,video_config, "t", "duration", "int", duration)
  172. self.appendRecordingConfig(cfg,video_config, "sh", "sharpness", "int")
  173. self.appendRecordingConfig(cfg,video_config, "co", "contrast", "int")
  174. self.appendRecordingConfig(cfg,video_config, "br", "brightness", "int")
  175. self.appendRecordingConfig(cfg,video_config, "sa", "saturation", "int")
  176. self.appendRecordingConfig(cfg,video_config, "vs", "stabilation", "bool")
  177. self.appendRecordingConfig(cfg,video_config, "ev", "EV", "int")
  178. self.appendRecordingConfig(cfg,video_config, "ex", "exposure", "string")
  179. self.appendRecordingConfig(cfg,video_config, "awb", "awb", "string")
  180. self.appendRecordingConfig(cfg,video_config, "ifx", "imxfx", "string")
  181. self.appendRecordingConfig(cfg,video_config, "cfx", "colfx", "string")
  182. self.appendRecordingConfig(cfg,video_config, "mm", "metering", "string")
  183. self.appendRecordingConfig(cfg,video_config, "rot", "rotation", "int")
  184. self.appendRecordingConfig(cfg,video_config, "fli", "flicker", "int")
  185. self.appendRecordingConfig(cfg,video_config, "ss", "shutterspeed", "int")
  186. self.appendRecordingConfig(cfg,video_config, "drc", "dynamicRangeCompression", "int")
  187. #if("hflip" in cfg["recording"]):
  188. # if(cfg["recording"]["hflip"]==True):
  189. # video_config.append("-hf")
  190. #if("vflip" in cfg["recording"]):
  191. # if(cfg["recording"]["vflip"]==True):
  192. # video_config.append("-vf")
  193. #if("duration" in cfg["recording"]):
  194. # if(cfg["recording"]["duration"]!="" and cfg["recording"]["duration"]!=False):
  195. # duration = cfg["recording"]["duration"]
  196. #video_config.append("-t "+duration)
  197. #if("width" in cfg["recording"]):
  198. # if(cfg["recording"]["width"]!="" and cfg["recording"]["width"]!=False):
  199. # width = cfg["recording"]["width"]
  200. #video_config.append("-w "+width)
  201. #if("height" in cfg["recording"]):
  202. # if(cfg["recording"]["height"]!="" and cfg["recording"]["height"]!=False):
  203. # height = cfg["recording"]["height"]
  204. #video_config.append("-h "+height)
  205. #if("fps" in cfg["recording"]):
  206. # if(cfg["recording"]["fps"]!="" and cfg["recording"]["fps"]!=False):
  207. # video_config.append("-fps "+cfg["recording"]["fps"])
  208. #if("bitrate" in cfg["recording"]):
  209. # if(cfg["recording"]["bitrate"]!="" and cfg["recording"]["bitrate"]!=False):
  210. # video_config.append("-b "+cfg["recording"]["bitrate"])
  211. #if("sharpness" in cfg["recording"]):
  212. # if(cfg["recording"]["sharpness"]!="" and cfg["recording"]["sharpness"]!=False):
  213. # video_config.append("-sh "+cfg["recording"]["sharpness"])
  214. #if("contrast" in cfg["recording"]):
  215. # if(cfg["recording"]["contrast"]!="" and cfg["recording"]["contrast"]!=False):
  216. # video_config.append("-co "+cfg["recording"]["contrast"])
  217. #if("brightness" in cfg["recording"]):
  218. # if(cfg["recording"]["brightness"]!="" and cfg["recording"]["brightness"]!=False):
  219. # video_config.append("-br "+cfg["recording"]["brightness"])
  220. #if("saturation" in cfg["recording"]):
  221. # if(cfg["recording"]["saturation"]!="" and cfg["recording"]["saturation"]!=False):
  222. # video_config.append("-sa "+cfg["recording"]["saturation"])
  223. #if("stabilation" in cfg["recording"]):
  224. # if(cfg["recording"]["stabilation"]==True):
  225. # video_config.append("-vs")
  226. #if("exposure" in cfg["recording"]):
  227. # if(cfg["recording"]["exposure"]!="" and cfg["recording"]["exposure"]!=False):
  228. # video_config.append("-ex "+cfg["recording"]["exposure"])
  229. #if("awb" in cfg["recording"]):
  230. # if(cfg["recording"]["awb"]!="" and cfg["recording"]["awb"]!=False):
  231. # video_config.append("-awb "+cfg["recording"]["awb"])
  232. #if("imxfx" in cfg["recording"]):
  233. # if(cfg["recording"]["imxfx"]!="" and cfg["recording"]["imxfx"]!=False):
  234. # video_config.append("-ifx "+cfg["recording"]["imxfx"])
  235. #if("metering" in cfg["recording"]):
  236. # if(cfg["recording"]["metering"]!="" and cfg["recording"]["metering"]!=False):
  237. # video_config.append("-mm "+cfg["recording"]["metering"])
  238. #if("rotation" in cfg["recording"]):
  239. # if(cfg["recording"]["rotation"]!="" and cfg["recording"]["rotation"]!=False):
  240. # video_config.append("-rot "+cfg["recording"]["rotation"])
  241. print("StartRecording")
  242. print(video_config)
  243. cmd = ' '.join(video_config)
  244. print(cmd)
  245. self.__recording_active = True
  246. self.record_process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
  247. p_status = self.record_process.communicate()
  248. self.__recording_active = False
  249. maxVids-=1
  250. if maxVids==0:
  251. self.__recording_active = False
  252. self.camera_recording = False
  253. def appendRecordingConfig(self, cfg, video_config, argument:str, propertyName: str, t : str = "string", default = ""):
  254. if t=="string" or t=="s" or t=="str":
  255. if propertyName in cfg["recording"]:
  256. v = cfg["recording"][propertyName]
  257. if isinstance(v, str)==True:
  258. if v!="":
  259. video_config.append("-"+argument+" "+v)
  260. if isinstance(v, int):
  261. video_config.append("-"+argument+" "+str(v))
  262. if isinstance(v, float):
  263. video_config.append("-"+argument+" "+str(v))
  264. if isinstance(v, bool):
  265. if v==True:
  266. video_config.append("-"+argument+" 1")
  267. return
  268. elif t=="int" or t=="i" or t=="integer":
  269. if propertyName in cfg["recording"]:
  270. v = cfg["recording"][propertyName]
  271. if isinstance(v, int)==True:
  272. video_config.append("-"+argument+" "+str(v))
  273. if isinstance(v, float)==True:
  274. video_config.append("-"+argument+" "+str(v))
  275. elif isinstance(v, str)==True:
  276. video_config.append("-"+argument+" "+v)
  277. elif isinstance(v, bool)==True:
  278. if v==True:
  279. video_config.append("-"+argument+" 1")
  280. return
  281. elif t=="bool" or t=="b" or b=="boolean":
  282. if propertyName in cfg["recording"]:
  283. v = cfg["recording"][propertyName]
  284. if isinstance(v, bool)==True:
  285. if v==True:
  286. video_config.append("-"+argument)
  287. elif isinstance(v, int)==True:
  288. if v>0:
  289. video_config.append("-"+argument)
  290. return
  291. elif isinstance(v, float)==True:
  292. if v>0:
  293. video_config.append("-"+argument)
  294. return
  295. elif isinstance(v, str)==True:
  296. if v!="":
  297. video_config.append("-"+argument)
  298. return
  299. if isinstance(default, str)==True:
  300. if default!="":
  301. video_config.append("-"+argument+" "+default)
  302. elif isinstance(default, int):
  303. video_config.append("-"+argument+" "+str(default))
  304. elif isinstance(default, float):
  305. video_config.append("-"+argument+" "+str(default))
  306. elif isinstance(default, bool):
  307. if default==True:
  308. video_config.append("-"+argument)
  309. def threadCamera(self):
  310. with self.lock:
  311. print("Video Res: " + str(self.video_resulution_x) + "x"+str(self.video_resulution_y))
  312. cap = cv2.VideoCapture(0)
  313. cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.video_resulution_x)
  314. cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.video_resulution_y)
  315. #cap.set(cv2.CAP_PROP_FPS, self.video_fps)
  316. if not cap.isOpened():
  317. print("Cannot open camera")
  318. self.camera_active = False
  319. return
  320. success,image = cap.read()
  321. #camera = PiCamera()
  322. #camera.resolution = (self.video_resulution_x, self.video_resulution_y)
  323. #camera.contrast = 10
  324. #camera.image_effect = "watercolor"
  325. while self.camera_active:
  326. ret, frame = cap.read()
  327. #cv2.imread("Frame", frame)
  328. if ret:
  329. self.__frame = frame
  330. #if self.__recording_active==True:
  331. #self.__writer.write(frame)
  332. print("- Release Camera")
  333. cap.release()
  334. cv2.destroyAllWindows()