Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

343 wiersze
16 KiB

  1. {
  2. "metadata": {
  3. "language_info": {
  4. "codemirror_mode": {
  5. "name": "ipython",
  6. "version": 3
  7. },
  8. "file_extension": ".py",
  9. "mimetype": "text/x-python",
  10. "name": "python",
  11. "nbconvert_exporter": "python",
  12. "pygments_lexer": "ipython3",
  13. "version": 3
  14. },
  15. "orig_nbformat": 2
  16. },
  17. "nbformat": 4,
  18. "nbformat_minor": 2,
  19. "cells": [
  20. {
  21. "cell_type": "code",
  22. "execution_count": null,
  23. "metadata": {},
  24. "outputs": [],
  25. "source": [
  26. "import argparse\n",
  27. "\n",
  28. "import cv2 as cv\n",
  29. "import numpy as np\n",
  30. "from tqdm import tqdm\n",
  31. "import os\n",
  32. "os.environ['DISPLAY'] = ':0'\n",
  33. "\n",
  34. "from config.config import PARAMS\n",
  35. "from src.numberPlateRoiDetection import NumberPlateROIDetection\n",
  36. "from src.objectDetection import ObjectDetection\n",
  37. "from src.ocrNumberPlate import get_number_plate_ocr_from_rois\n",
  38. "from src.parkingDetection import ParkingDetection\n",
  39. "from src.trackingManager import TrackerManager\n"
  40. ]
  41. },
  42. {
  43. "cell_type": "code",
  44. "execution_count": null,
  45. "metadata": {},
  46. "outputs": [],
  47. "source": [
  48. "class TrafficApp(object):\n",
  49. " def __init__(self,args):\n",
  50. " self.args = args\n",
  51. "\n",
  52. " #get Object Detection Up\n",
  53. " self.objectDetection = ObjectDetection(debug=args.debug,target=args.target)\n",
  54. " self.numberPlateDetection = NumberPlateROIDetection(args= args,algoType='NumberPlate')\n",
  55. " self.parkingDetection = None #intilize later when we will have height/width\n",
  56. " np.random.seed(41)\n",
  57. "\n",
  58. " #fix color\n",
  59. " self.colorToDisplay = {'numberplate':(0,255,255),'car':(0,255,0),'bus':(128,255,0),'truck':(0,0,255),'moterbike':(255,0,255),'ocr':(0,140,240)}\n",
  60. " if self.args.video is not None:\n",
  61. " self.vid_writer = None\n",
  62. " self.runVideoFlow()\n",
  63. "\n",
  64. " def runVideoFlow(self):\n",
  65. " frame_count = 0\n",
  66. " if args.video is not None:\n",
  67. " try:\n",
  68. " videoObj = cv.VideoCapture(args.video)\n",
  69. " imgH, imgW = None, None\n",
  70. " writer = None\n",
  71. " except:\n",
  72. " raise Exception('Video cannot be loaded! Please check the path provided!')\n",
  73. "\n",
  74. " finally:\n",
  75. " try:\n",
  76. " totalFrames = videoObj.get(cv.cv.CV_CAP_PROP_FRAME_COUNT)\n",
  77. " except:\n",
  78. " totalFrames = -1\n",
  79. "\n",
  80. " try:\n",
  81. " totalFrames = videoObj.get(cv.CAP_PROP_FRAME_COUNT)\n",
  82. " except:\n",
  83. " totalFrames = -1\n",
  84. " try:\n",
  85. " imgH = int(videoObj.get(cv.CAP_PROP_FRAME_HEIGHT))\n",
  86. " imgW = int(videoObj.get(cv.CAP_PROP_FRAME_WIDTH))\n",
  87. " TrackerManager.FrameHeight = imgH\n",
  88. " TrackerManager.FrameWidth = imgW\n",
  89. " print('Height, Width',imgH,imgW)\n",
  90. " if PARAMS._ALGO_MODE_PARKING:\n",
  91. " self.parkingDetection = ParkingDetection(imgW=imgW,imgH=imgH)\n",
  92. " self.parkingDetection.getParkingRegionMask()\n",
  93. " #videoObj.set(cv.CAP_PROP_POS_FRAMES, 225)\n",
  94. " except:\n",
  95. " imgH = -1\n",
  96. " imgW = -1\n",
  97. " raise ValueError('Issue with video')\n",
  98. " if self.args.debug:\n",
  99. " print('Frames-{},Height-{}, Width-{}'.format(totalFrames,imgH,imgW))\n",
  100. "\n",
  101. " if self.args.saveoutput and (imgH > 0 and imgW > 0):\n",
  102. " self.vid_writer = cv.VideoWriter(self.args.outputfile,\n",
  103. " cv.VideoWriter_fourcc(*\"MJPG\"), 30,\n",
  104. " (round(imgW),round(imgH)))\n",
  105. " \n",
  106. " progress_bar=tqdm(total = totalFrames)\n",
  107. " # start reading frame\n",
  108. " while True:\n",
  109. " grabbed, frame = videoObj.read()\n",
  110. " #frame[:,450:,:] = 0\n",
  111. " # end of frame\n",
  112. " if not grabbed:\n",
  113. " break\n",
  114. " frame_count +=1\n",
  115. "\n",
  116. " #print('Frame_count-',frame_count)\n",
  117. " #Use jump argument to skip frames.\n",
  118. " if (frame_count % self.args.jump == 0):\n",
  119. " \n",
  120. " # get object detection on this frame\n",
  121. " img_objectMarking, boxes, confidences, classids, idxs,status = self.objectDetection.run_object_detection(frame.copy(),imageH=imgH,imageW=imgW)\n",
  122. " '''Assign Trcakers'''\n",
  123. " object_detect_info = [boxes, confidences, classids, idxs, status]\n",
  124. " bbox_labels_tracking = self.parseObjDetectInfo(object_detect_info)\n",
  125. " TrackerManager.FrameCount = frame_count\n",
  126. " TrackerManager.manageTracker(bbox_labels_tracking)\n",
  127. "\n",
  128. " ''' Get Parking Status'''\n",
  129. " if PARAMS._ALGO_MODE_PARKING:\n",
  130. " self.parkingDetection.getParkingStatus(TrackerManager.TrackerList)\n",
  131. "\n",
  132. " '''Filter ROIs for Number Plate Detection'''\n",
  133. " tentative_numberplate_rios = self.objectDetection.filterRoiforNumberPlate(boxes, classids, idxs)\n",
  134. "\n",
  135. "\n",
  136. " ''' Get Number Plate ROI'''\n",
  137. " detected_np_info = self.numberPlateDetection.run_number_plate_detection_rois(image=frame.copy(),rois=tentative_numberplate_rios)\n",
  138. "\n",
  139. "\n",
  140. " ''' Get Number plate OCR '''\n",
  141. " number_plate_ocr_dict = get_number_plate_ocr_from_rois(frame.copy(),detected_np_info, False)\n",
  142. "\n",
  143. " #Display frame\n",
  144. " displayFrame = self.displayFrame(frame.copy(),detected_np_info,number_plate_ocr_dict,object_detect_info)\n",
  145. "\n",
  146. " winName = 'YOLOV3 Object Detection'\n",
  147. " cv.namedWindow(winName, cv.WINDOW_NORMAL)\n",
  148. " cv.imshow(winName, displayFrame)\n",
  149. " #cv.resizeWindow('objectDetection',680,420)\n",
  150. " if self.vid_writer:\n",
  151. " self.vid_writer.write(displayFrame.astype(np.uint8))\n",
  152. " c = cv.waitKey(1)\n",
  153. " if c & 0xFF == ord('q'):\n",
  154. " self.vid_writer.release()\n",
  155. " videoObj.release()\n",
  156. " break\n",
  157. " progress_bar.close()\n",
  158. " def parseObjDetectInfo(self,object_roi_info):\n",
  159. " boxes, confidences, classids, idxs, status = object_roi_info\n",
  160. " #[[list of bbox ][list of conf and labels]]\n",
  161. " bboxList =[]\n",
  162. " confidence_labels = []\n",
  163. " if len(idxs) > 0 and status:\n",
  164. " for i in idxs.flatten():\n",
  165. " # Get the bounding box coordinates\n",
  166. " if self.objectDetection.labels[classids[i]] not in PARAMS._TRACKER_OBJECT_LIST +\\\n",
  167. " PARAMS._YOLOV3_OD_NUMBER_PLATE_OBJECT_LIST:\n",
  168. " continue\n",
  169. " x, y = boxes[i][0], boxes[i][1]\n",
  170. " w, h = boxes[i][2], boxes[i][3]\n",
  171. " bboxList.append ([x,y,w,h])\n",
  172. " confidence_labels.append([confidences[i],self.objectDetection.labels[classids[i]]])\n",
  173. " return [bboxList,confidence_labels]\n",
  174. "\n",
  175. " def displayFrame(self,displayFrame,numberplate_roi,number_plate_ocr_dict,object_roi_info):\n",
  176. " debug = self.args.debug\n",
  177. " if PARAMS._ALGO_MODE_NUMBER_PLATE:\n",
  178. " #for nuber plate\n",
  179. " for idx,roiinfo in enumerate(numberplate_roi):\n",
  180. " conf, classID, roi = roiinfo\n",
  181. " x, y, w, h = roi\n",
  182. " cv.rectangle(displayFrame, (x, y), (x + w, y + h), self.colorToDisplay['numberplate'], 2)\n",
  183. " text = \"{}: {:.3f}\".format(self.numberPlateDetection.labels[classID], conf)\n",
  184. " #cv.putText(displayFrame, text, (x, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.5, self.colorToDisplay['numberplate'], 1)\n",
  185. "\n",
  186. " #add Number plate OCR\n",
  187. " if number_plate_ocr_dict[idx]:\n",
  188. " thickness = 4\n",
  189. " font_face = cv.FONT_HERSHEY_SIMPLEX\n",
  190. " font_scale = 1\n",
  191. " cv.putText(displayFrame, number_plate_ocr_dict[idx], (x, y-5), font_face, font_scale,\\\n",
  192. " self.colorToDisplay['ocr'], thickness)\n",
  193. "\n",
  194. " if False:\n",
  195. " #for objects\n",
  196. " boxes, confidences, classids, idxs, status = object_roi_info\n",
  197. " if len(idxs) > 0 and status:\n",
  198. " for i in idxs.flatten():\n",
  199. " # Get the bounding box coordinates\n",
  200. " x, y = boxes[i][0], boxes[i][1]\n",
  201. " w, h = boxes[i][2], boxes[i][3]\n",
  202. "\n",
  203. " # Get the unique color for this class\n",
  204. " if self.objectDetection.labels[classids[i]] in self.colorToDisplay:\n",
  205. " color = self.colorToDisplay[self.objectDetection.labels[classids[i]]]\n",
  206. " else:\n",
  207. " color = [int(c) for c in self.objectDetection.colors[classids[i]]]\n",
  208. " #color = (255,255,255)\n",
  209. " # Draw the bounding box rectangle and label on the image\n",
  210. " cv.rectangle(displayFrame, (x, y), (x + w, y + h), color, 2)\n",
  211. " text = \"{}: {:.3f}\".format(self.objectDetection.labels[classids[i]], confidences[i])\n",
  212. " cv.putText(displayFrame, text, (x, y - 5), cv.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)\n",
  213. "\n",
  214. "\n",
  215. " if True:\n",
  216. " if len(TrackerManager.DetectionWithNoTracker)>0:\n",
  217. " color = (0,0,0)\n",
  218. " for item in TrackerManager.DetectionWithNoTracker:\n",
  219. " bbox,(conf,label) = item\n",
  220. " x,y,w,h = bbox\n",
  221. " # Draw the bounding box rectangle and label on the image\n",
  222. " cv.rectangle(displayFrame, (x, y), (x + w, y + h), color, 2)\n",
  223. " if debug:\n",
  224. " text = \"NotTrack-{}: {:.3f}\".format(label,conf)\n",
  225. " cv.putText(displayFrame, text, (x, y - 5), cv.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)\n",
  226. "\n",
  227. " if PARAMS._ALGO_MODE_PARKING:\n",
  228. " cv.line(displayFrame,PARAMS._NO_PARAKING_LINE_POINT_1_XY,PARAMS._NO_PARAKING_LINE_POINT_2_XY,\\\n",
  229. " (0,0,255),3,2)\n",
  230. "\n",
  231. " if PARAMS._ALGO_MODE_KALMAN_TRCAKING:\n",
  232. " if len(TrackerManager.TrackerList) > 0:\n",
  233. " color = (0,255,0)\n",
  234. " for tracker in TrackerManager.TrackerList:\n",
  235. " bbox = tracker.curr_frame_predict_bbox\n",
  236. " x,y,w,h = np.int32(bbox)\n",
  237. " missframe = tracker.objectInfo.ObjectTrackerMissedFrame\n",
  238. " direction = 'XX' if tracker.objectInfo.ObjectDirection is None else tracker.objectInfo.ObjectDirection\n",
  239. " objectType = tracker.objectInfo.ObjectType\n",
  240. " objectID = tracker.objectID\n",
  241. " if not tracker.objectInfo.ObjectParkingStatus:\n",
  242. " cv.rectangle(displayFrame, (x, y), (x + w, y + h), color, 2)\n",
  243. " else:\n",
  244. " cv.rectangle(displayFrame, (x, y), (x + w, y + h), (0,0,0), 3)\n",
  245. "\n",
  246. " #update curr box by which it was updated\n",
  247. " if False:\n",
  248. " bbox_detect = tracker.curr_frame_update_bbox\n",
  249. " xp,yp,wp,hp = bbox_detect\n",
  250. " cv.rectangle(displayFrame, (xp, yp), (xp + wp, yp + hp), (0,255,255), 2)\n",
  251. " if debug:\n",
  252. " text = \"{}-f{}-{}\".format(objectID,missframe,direction)\n",
  253. " else:\n",
  254. " text = \"{}\".format(direction)\n",
  255. "\n",
  256. " if tracker.objectInfo.ObjectParkingStatus and PARAMS._ALGO_MODE_PARKING:\n",
  257. " if tracker.objectInfo.ObjectType in PARAMS._YOLOV3_OD_NUMBER_PLATE_OBJECT_LIST:\n",
  258. " text = \"{}\".format(PARAMS._PARKING_STRING)\n",
  259. " font_scale = 1.5\n",
  260. " font = cv.FONT_HERSHEY_SIMPLEX #PLAIN #cv.FONT_HERSHEY_SIMPLEX\n",
  261. " # set the rect bg - BLACK\n",
  262. " rect_bgr = (0,0,0)\n",
  263. " # get the width and height of the text box\n",
  264. " (text_width, text_height) = np.int32(cv.getTextSize(text, font, fontScale=font_scale, thickness=2)[0])\n",
  265. " # make the coords of the box with a small padding of two pixels\n",
  266. " box_coords = ((x, y), (x + text_width + 5, y - text_height - 5))\n",
  267. " cv.rectangle(displayFrame, box_coords[0], box_coords[1], rect_bgr, cv.FILLED)\n",
  268. " cv.putText(displayFrame, text, (x, y), font, fontScale=font_scale, color=(0, 0, 255),thickness=2)\n",
  269. " if True:\n",
  270. " imglogo = cv.imread(PARAMS.LOGO_FILE_PATH)\n",
  271. " logo = cv.resize(imglogo,dsize=(300,100),interpolation=cv.INTER_LINEAR)\n",
  272. " h,w,c = logo.shape\n",
  273. " H,W,C = displayFrame.shape\n",
  274. " displayFrame[0:h,W-w-10:W-10,:] = logo\n",
  275. "\n",
  276. " return displayFrame\n"
  277. ]
  278. },
  279. {
  280. "cell_type": "code",
  281. "execution_count": null,
  282. "metadata": {},
  283. "outputs": [],
  284. "source": []
  285. },
  286. {
  287. "cell_type": "code",
  288. "execution_count": null,
  289. "metadata": {},
  290. "outputs": [],
  291. "source": []
  292. },
  293. {
  294. "cell_type": "code",
  295. "execution_count": null,
  296. "metadata": {},
  297. "outputs": [],
  298. "source": []
  299. },
  300. {
  301. "cell_type": "code",
  302. "execution_count": null,
  303. "metadata": {},
  304. "outputs": [],
  305. "source": []
  306. },
  307. {
  308. "cell_type": "code",
  309. "execution_count": null,
  310. "metadata": {},
  311. "outputs": [],
  312. "source": []
  313. },
  314. {
  315. "cell_type": "code",
  316. "execution_count": null,
  317. "metadata": {},
  318. "outputs": [],
  319. "source": []
  320. },
  321. {
  322. "cell_type": "code",
  323. "execution_count": null,
  324. "metadata": {},
  325. "outputs": [],
  326. "source": []
  327. },
  328. {
  329. "cell_type": "code",
  330. "execution_count": null,
  331. "metadata": {},
  332. "outputs": [],
  333. "source": []
  334. },
  335. {
  336. "cell_type": "code",
  337. "execution_count": null,
  338. "metadata": {},
  339. "outputs": [],
  340. "source": []
  341. }
  342. ]
  343. }