tofManager.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. import etc_pb2 as etc
  2. import os, glog, numpy, cv2, SDK.ZX.tool, json, time
  3. import SDK.Vzense.VzenseDS_api as tof
  4. from ctypes import *
  5. class TofManager:
  6. def saveIrFrame2Image(self, path, name, frame):
  7. frametmp = numpy.ctypeslib.as_array(frame.pFrameData, (1, frame.dataLen))
  8. frametmp.dtype = numpy.uint8
  9. frametmp.shape = (frame.height, frame.width)
  10. if not os.path.exists(path):
  11. os.makedirs(path)
  12. filename = path + name
  13. cv2.imwrite(filename, frametmp, [cv2.IMWRITE_JPEG_QUALITY, 100])
  14. def saveDepthFrame2Image(self, path, name, frame):
  15. frametmp = numpy.ctypeslib.as_array(frame.pFrameData, (1, frame.width * frame.height * 2))
  16. frametmp.dtype = numpy.uint16
  17. frametmp.shape = (frame.height, frame.width)
  18. # convert ushort value to 0xff is just for display
  19. img = numpy.int32(frametmp)
  20. img = img * 255 / c_uint16(7495)
  21. img = numpy.clip(img, 0, 255)
  22. img = numpy.uint8(img)
  23. frametmp = cv2.applyColorMap(img, cv2.COLORMAP_RAINBOW)
  24. if not os.path.exists(path):
  25. glog.info(path + " not exists, mkdit it.")
  26. os.makedirs(path)
  27. filename = path + name
  28. cv2.imwrite(filename, frametmp, [cv2.IMWRITE_JPEG_QUALITY, 100])
  29. def savePointCloud(self, width, height, path, name, pointlist):
  30. file = open(path + name, "w")
  31. for i in range(width * height):
  32. if pointlist[i].z != 0 and pointlist[i].z != 65535:
  33. file.write("{0},{1},{2}\n".format(pointlist[i].x, pointlist[i].y, pointlist[i].z))
  34. file.close()
  35. def __init__(self):
  36. self.etc_file = os.path.dirname(os.path.abspath(__file__)) + "/etc/device.json"
  37. self.tofs_etc = {}
  38. self.updateTofsEtc()
  39. self.camera = tof.VzenseTofCam()
  40. self.camera_list = {}
  41. self.search_flag = False
  42. self.stepPath = ""
  43. self.stepIndex = 0
  44. self.liscenFunc = [["getCameraFrame", self.getCameraFrame],
  45. ["updateTofsEtc", self.updateTofsEtc],
  46. ["getCameraEtc", self.getCameraEtc],
  47. ["getAllCameraEtc", self.getAllCameraEtc],
  48. ["getCameraList", self.getCameraList],
  49. ["searchAllCamera", self.searchAllCamera],
  50. ["openCamera", self.openCamera],
  51. ["openAllCamera", self.openAllCamera],
  52. ["closeCamera", self.closeCamera],
  53. ["closeAllCamera", self.closeAllCamera],
  54. ["startCameraStream", self.startCameraStream],
  55. ["startAllCameraStream", self.startAllCameraStream],
  56. ["stopCamera", self.stopCamera],
  57. ["stopAllCameraStream", self.stopAllCameraStream],
  58. ["getCameraFrame", self.getCameraFrame],
  59. ["loopGetCameraFrame", self.loopGetCameraFrame],
  60. ["stepGetCameraFrame", self.stepGetCameraFrame]
  61. ]
  62. # self.t1 = threading(target=func, args=('第一个线程', 1))
  63. def test(self, data):
  64. glog.info(data)
  65. def exec(self, req_data):
  66. try:
  67. json_data = json.loads(req_data.statu)
  68. glog.info(json_data)
  69. if type(json_data) != dict:
  70. glog.warning("receive data not is dict")
  71. return
  72. for bind_func in self.liscenFunc:
  73. if json_data["func"] == bind_func[0] and type(json_data["params"]) == dict:
  74. bind_func[1](json_data["params"])
  75. return
  76. glog.warning(json_data["params"])
  77. except ValueError as e:
  78. glog.error(req_data.statu)
  79. def updateTofsEtc(self, receive_data=""):
  80. etc_proto = SDK.ZX.tool.getProtobufJsonConfig(self.etc_file, etc.DevicesConfig())
  81. for tof_etc in etc_proto.devices:
  82. self.tofs_etc[tof_etc.id] = tof_etc
  83. glog.info(self.tofs_etc)
  84. self.search_flag = False
  85. def getCameraEtc(self, receive_data=""):
  86. id = receive_data["id"]
  87. return self.tofs_etc[id]
  88. def getAllCameraEtc(self, receive_data=""):
  89. return self.tofs_etc
  90. def getCameraList(self, receive_data=""):
  91. return self.camera_list
  92. def searchAllCamera(self, receive_data=""):
  93. # 搜索相机,会确保配置中启用的相机全部搜索到
  94. camera_count = self.camera.VZ_GetDeviceCount()
  95. retry_count = 60
  96. device_ip_list = []
  97. while camera_count <= len(self.tofs_etc) and retry_count > 0:
  98. ret, deviceInfoList = self.camera.VZ_GetDeviceInfoList()
  99. retry_count = retry_count - 1
  100. camera_count = self.camera.VZ_GetDeviceCount()
  101. if camera_count > 0:
  102. device_ip_list = []
  103. for i in range(camera_count):
  104. device_ip_list.append(deviceInfoList[i].ip)
  105. find_device_count = 0
  106. for tof_etc in self.tofs_etc:
  107. if self.tofs_etc[tof_etc].enable is False:
  108. find_device_count = find_device_count + 1
  109. glog.info(self.tofs_etc[tof_etc].ipv4 + " not enable.")
  110. if find_device_count == len(self.tofs_etc):
  111. self.search_flag = True
  112. return self.search_flag
  113. continue
  114. if self.tofs_etc[tof_etc].ipv4.encode() not in device_ip_list:
  115. glog.info("find a device " + self.tofs_etc[tof_etc].ipv4 + " fulture.")
  116. break
  117. else:
  118. find_device_count = find_device_count + 1
  119. glog.info("find a device " + self.tofs_etc[tof_etc].ipv4 + " success.")
  120. if find_device_count == len(self.tofs_etc):
  121. self.search_flag = True
  122. return self.search_flag
  123. time.sleep(0.5)
  124. glog.info("scaning...... " + str(retry_count) + " already scanned" + str(camera_count) + " devices.")
  125. return self.search_flag
  126. def openCamera(self, receive_data=""):
  127. id = receive_data["id"]
  128. if id in self.camera_list:
  129. glog.info("camera " + self.tofs_etc[id].ipv4 + " already opend.")
  130. return tof.VzReturnStatus.VzRetOK
  131. if self.tofs_etc[id].enable is False:
  132. glog.warning(
  133. "this camera not enabled in etc fiile, if you want to enable it, please update the file, and then use func updateTofsEtc.")
  134. return tof.VzReturnStatus.VzRetOthers
  135. cam = tof.VzenseTofCam()
  136. ret = cam.VZ_OpenDeviceByIP(self.tofs_etc[id].ipv4.encode())
  137. if ret == 0:
  138. glog.info(self.tofs_etc[id].ipv4 + " open successful")
  139. self.camera_list[id] = cam
  140. else:
  141. glog.info(self.tofs_etc[id].ipv4 + ' VZ_OpenDeviceByIP failed: ' + str(ret))
  142. def openAllCamera(self, receive_data=""):
  143. for tof_etc in self.tofs_etc:
  144. if self.tofs_etc[tof_etc].enable is False:
  145. continue
  146. cam = tof.VzenseTofCam()
  147. ret = cam.VZ_OpenDeviceByIP(self.tofs_etc[tof_etc].ipv4.encode())
  148. if ret == 0:
  149. glog.info(self.tofs_etc[tof_etc].ipv4 + " open successful")
  150. self.camera_list[tof_etc] = cam
  151. else:
  152. glog.info(self.tofs_etc[tof_etc].ipv4 + ' VZ_OpenDeviceByIP failed: ' + str(ret))
  153. def closeCamera(self, receive_data=""):
  154. id = receive_data["id"]
  155. if (id not in self.camera_list):
  156. glog.info("camera " + self.tofs_etc[id].ipv4 + " already closed.")
  157. return tof.VzReturnStatus.VzRetOK
  158. ret = self.camera_list[id].VZ_CloseDevice()
  159. if ret == 0:
  160. del self.camera_list[id]
  161. glog.info("close device " + str(self.tofs_etc[id].ipv4) + " successful")
  162. else:
  163. glog.warning("VZ_CloseDevice " + str(self.tofs_etc[id].ipv4) + " failed: " + str(ret))
  164. return ret
  165. def closeAllCamera(self, receive_data=""):
  166. for id in self.camera_list:
  167. ret = self.camera_list[id].VZ_CloseDevice()
  168. if ret == 0:
  169. glog.info("close device " + str(self.tofs_etc[id].ipv4) + " successful")
  170. else:
  171. glog.warning("VZ_CloseDevice " + str(self.tofs_etc[id].ipv4) + " failed: " + str(ret))
  172. self.camera_list.clear()
  173. def startCameraStream(self, receive_data=""):
  174. id = receive_data["id"]
  175. if id in self.camera_list:
  176. ret = self.camera_list[id].VZ_StartStream()
  177. if ret == 0:
  178. glog.info(self.tofs_etc[id].ipv4 + " start stream successful")
  179. else:
  180. glog.info(self.tofs_etc[id].ipv4 + ' VZ_StartStream failed: ' + str(ret))
  181. else:
  182. glog.warning("camera " + self.tofs_etc[id].ip + "not open, please open this camera")
  183. def startAllCameraStream(self, receive_data=""):
  184. for id in self.camera_list:
  185. ret = self.camera_list[id].VZ_StartStream()
  186. if ret == 0:
  187. glog.info(self.tofs_etc[id].ipv4 + " start stream successful")
  188. else:
  189. glog.info(self.tofs_etc[id].ipv4 + ' VZ_StartStream failed: ' + str(ret))
  190. def stopCamera(self, receive_data=""):
  191. id = receive_data["id"]
  192. if id in self.camera_list:
  193. ret = self.camera_list[id].VZ_StopStream()
  194. if ret == 0:
  195. glog.info(self.tofs_etc[id].ipv4 + " stop stream successful")
  196. else:
  197. glog.info(self.tofs_etc[id].ipv4 + ' VZ_StopStream failed: ' + str(ret))
  198. else:
  199. glog.warning("camera " + self.tofs_etc[id].ip + "not open, please open this camera")
  200. def stopAllCameraStream(self, receive_data=""):
  201. for id in self.camera_list:
  202. ret = self.camera_list[id].VZ_StopStream()
  203. if ret == 0:
  204. glog.info(self.tofs_etc[id].ipv4 + " stop stream successful")
  205. else:
  206. glog.info(self.tofs_etc[id].ipv4 + ' VZ_StopStream failed: ' + str(ret))
  207. def getCameraFrame(self, receive_data=""):
  208. id, path, depth_name, ir_name, point_cloud_name = 0, "", "", "", ""
  209. if "id" not in receive_data or "path" not in receive_data:
  210. return
  211. id = receive_data["id"]
  212. path = receive_data["path"]
  213. if "depth_name" in receive_data:
  214. depth_name = receive_data["depth_name"]
  215. if "ir_name" in receive_data:
  216. ir_name = receive_data["ir_name"]
  217. if "point_cloud_name" in receive_data:
  218. point_cloud_name = receive_data["point_cloud_name"]
  219. if id == "" or path == "":
  220. return
  221. if id in self.camera_list:
  222. ret, frameready = self.camera_list[id].VZ_GetFrameReady(c_uint16(1000))
  223. if ret != 0:
  224. glog.error("VZ_GetFrameReady failed: %d", ret)
  225. return
  226. if frameready.depth and depth_name != "":
  227. ret, depthframe = self.camera_list[id].VZ_GetFrame(tof.VzFrameType.VzDepthFrame)
  228. if ret == 0:
  229. self.saveDepthFrame2Image(path, depth_name + ".jpg", depthframe)
  230. glog.info(self.tofs_etc[id].ipv4 + " depth frameindex: " + str(depthframe.frameIndex))
  231. if point_cloud_name != "":
  232. ret, pointlist = self.camera_list[id].VZ_ConvertDepthFrameToPointCloudVector(depthframe)
  233. if ret == 0:
  234. self.savePointCloud(depthframe.width, depthframe.height, path, point_cloud_name + ".txt",
  235. pointlist)
  236. else:
  237. glog.warning("VZ_ConvertDepthFrameToPointCloudVector error %d", ret)
  238. else:
  239. glog.warning("VZ_GetFrame error %d", ret)
  240. if frameready.ir and ir_name != "":
  241. ret, irframe = self.camera_list[id].VZ_GetFrame(tof.VzFrameType.VzIRFrame)
  242. if ret == 0:
  243. self.saveIrFrame2Image(path, ir_name + ".jpg", irframe)
  244. glog.info(self.tofs_etc[id].ipv4 + " ir frameindex: " + str(irframe.frameIndex))
  245. else:
  246. glog.warning("VZ_GetFrame error %d", ret)
  247. def loopGetCameraFrame(self, receive_data=""):
  248. path, times, interval = 0, 0, 0
  249. if "path" not in receive_data or "times" not in receive_data or "interval" not in receive_data:
  250. return
  251. times = receive_data["times"]
  252. interval = receive_data["interval"]
  253. if interval < 0.2:
  254. interval = 0.2
  255. while times:
  256. receive_data["depth_name"] = "Depth_" + str(receive_data["times"] - times + 1)
  257. receive_data["ir_name"] = "Ir_" + str(receive_data["times"] - times + 1)
  258. receive_data["point_cloud_name"] = "cloud_" + str(receive_data["times"] - times + 1)
  259. glog.info(receive_data)
  260. self.getCameraFrame(receive_data)
  261. times = times - 1
  262. time.sleep(interval)
  263. def stepGetCameraFrame(self, receive_data=""):
  264. if "path" not in receive_data or "id" not in receive_data:
  265. return
  266. if receive_data["path"] != self.stepPath:
  267. self.stepIndex = 0
  268. self.stepPath = receive_data["path"]
  269. receive_data["depth_name"] = "Depth_" + str(self.stepIndex)
  270. receive_data["ir_name"] = "Ir_" + str(self.stepIndex)
  271. receive_data["point_cloud_name"] = "cloud_" + str(self.stepIndex)
  272. self.getCameraFrame(receive_data)
  273. self.stepIndex = self.stepIndex + 1
  274. def getCameraFrameCloud(self, receive_data=""):
  275. id, path, depth_name, point_cloud_name = 0, "", "", ""
  276. if "id" not in receive_data or "path" not in receive_data:
  277. return
  278. id = receive_data["id"]
  279. path = receive_data["path"]
  280. if "depth_name" in receive_data:
  281. depth_name = receive_data["depth_name"]
  282. if "point_cloud_name" in receive_data:
  283. point_cloud_name = receive_data["point_cloud_name"]
  284. if id == "" or path == "":
  285. return
  286. if id in self.camera_list:
  287. ret, frameready = self.camera_list[id].VZ_GetFrameReady(c_uint16(1000))
  288. if ret != 0:
  289. glog.error("VZ_GetFrameReady failed: %d", ret)
  290. return
  291. if frameready.depth and depth_name != "":
  292. ret, depthframe = self.camera_list[id].VZ_GetFrame(tof.VzFrameType.VzDepthFrame)
  293. if ret == 0:
  294. self.saveDepthFrame2Image(path, depth_name + ".jpg", depthframe)
  295. glog.info(self.tofs_etc[id].ipv4 + " depth frameindex: " + str(depthframe.frameIndex))
  296. pointList = []
  297. if point_cloud_name != "":
  298. for h in range(190, 290):
  299. offset = h * depthframe.width
  300. for w in range(270, 370):
  301. depth = tof.VzDepthVector3()
  302. depth.depthX = w
  303. depth.depthY = h
  304. depth.depthZ = depthframe.pFrameData[offset + w]
  305. ret, point = self.camera_list[id].VZ_ConvertDepthToPointCloud(depth)
  306. pointList.append(point)
  307. # depthList.append(pt)
  308. # ret, pointlist = self.camera_list[id].VZ_ConvertDepthFrameToPointCloudVector(depthframe)
  309. if ret == 0:
  310. self.savePointCloud(depthframe.width, depthframe.height, path, point_cloud_name + ".txt",
  311. pointList)
  312. else:
  313. glog.warning("VZ_ConvertDepthFrameToPointCloudVector error %d", ret)
  314. else:
  315. glog.warning("VZ_GetFrame error %d", ret)
  316. def setCameraEtc(self, ip, tof_etc=etc.VzenseTofDevices()):
  317. glog.info("=======================")