{"id":83213,"date":"2021-07-13T09:00:15","date_gmt":"2021-07-13T03:30:15","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=83213"},"modified":"2021-07-13T09:00:15","modified_gmt":"2021-07-13T03:30:15","slug":"opencv-vehicle-detection-classification-counting","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/","title":{"rendered":"Vehicle Counting, Classification &amp; Detection using OpenCV &amp; Python"},"content":{"rendered":"<p>Today, we\u2019re going to build an advanced vehicle detection and classification project using OpenCV. We\u2019ll use the YOLOv3 model with OpenCV-python. Open-CV is a real-time computer vision library of Python. We can use YOLO directly with OpenCV.<\/p>\n<h3>What is YOLO?<\/h3>\n<p><strong>YOLO<\/strong> stands for <strong>You Only Look Once<\/strong>. It is a real-time object recognition algorithm. It can classify and localize multiple objects in a single frame. YOLO is a very fast and accurate algorithm for its simpler network architecture.<\/p>\n<h3>How does YOLO work?<\/h3>\n<p>YOLO works using mainly these techniques.<\/p>\n<p><strong>1. Residual Blocks<\/strong> &#8211; Basically, it divides an image into NxN grids.<\/p>\n<p><strong>2. Bounding Box regression<\/strong> &#8211; Each grid cell is sent to the model. Then YOLO determines the probability of the cell contains a certain class and the class with the maximum probability is chosen.<\/p>\n<p><strong>3. Intersection Over Union (IOU) &#8211;<\/strong> IOU is a metric that evaluates intersection between the predicted bounding box and the ground truth bounding box. A Non-max suppression technique is applied to eliminate the bounding boxes that are very close by performing the IoU with the one having the highest class probability among them.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/intersection-over-union.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-83298\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/intersection-over-union.jpg\" alt=\"intersection over union\" width=\"666\" height=\"182\" \/><\/a><\/p>\n<p>Here is the combination of these 3 techniques.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/yolo-design.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-83305\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/yolo-design.jpg\" alt=\"yolo design\" width=\"1200\" height=\"800\" \/><\/a><\/p>\n<h3>YOLO Architecture :<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/yolo-architecture.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-83302\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/yolo-architecture.jpg\" alt=\"yolo architecture\" width=\"1050\" height=\"476\" \/><\/a><\/p>\n<ul>\n<li>The YOLO network has 24 convolutional layers followed by 2 fully connected layers. The convolutional layers are pre-trained on the ImageNet classification task at half the resolution (224 \u00d7 224 input image) and then double the resolution for detection.<\/li>\n<li>The layers Alternating 1 \u00d7 1 reduction layer and 3&#215;3 convolutional layer to reduce the feature space from preceding layers.<\/li>\n<li>The last 4 layers are added to train the network for object detection.<\/li>\n<li>The last layer predicts the object class probability and the bounding box probability.<\/li>\n<\/ul>\n<p>We\u2019ll use OpenCV\u2019s DNN module to work with YOLO directly. DNN means Deep Neural Network. OpenCV has a built-in function to perform DNN algorithms.<\/p>\n<h3>OpenCV Vehicle Detection and Classification Project<\/h3>\n<p>In this project, we\u2019ll detect and classify cars, HMV ( Heavy Motor Vehicle) , LMV (Light Motor Vehicle) on the road, and count the number of vehicles traveling through a road. And the data will be stored to analyze different vehicles that travel through the road.<\/p>\n<p>We\u2019ll create two programs to do this project. The first one will be the tracker for vehicle detection using OpenCV that keeps track of each and every detected vehicle on the road and the 2nd one will be the main detection program.<\/p>\n<h3>Prerequisites for Vehicle Detection and Classification Project using OpenCV:<\/h3>\n<p>1. Python &#8211; 3.x (We used python 3.8.8 in this project)<br \/>\n2. OpenCV &#8211; 4.4.0<\/p>\n<ul>\n<li>It is strongly recommended to run DNN models on GPU.<\/li>\n<li>You can install OpenCV via \u201cpip install opencv-python opencv_contrib-python\u201d.<\/li>\n<\/ul>\n<p>3. Numpy &#8211; 1.20.3<br \/>\n4. YOLOv3 Pre-trained model weights and Config Files.<\/p>\n<h3>Download Vehicle Detection &amp; Classification Python OpenCV Code<\/h3>\n<p>Please download the source code of opencv vehicle detection &amp; classification: <a href=\"https:\/\/drive.google.com\/file\/d\/1jQPLyibctn8b333a91Lnt3Yl468_H62r\/view?usp=sharing\"><strong>Vehicle Detection and Classification OpenCV Code<\/strong><\/a><\/p>\n<h3>Tracker:<\/h3>\n<p>The tracker basically uses the Euclidean_distance concept to keep track of an object. It calculates the difference between two center points of an object in the current frame vs the previous frame, and if the distance is less than the threshold distance then it confirms that the object is the same object of the previous frame.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Euclidean-distance.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-83306\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/Euclidean-distance.jpg\" alt=\"Euclidean distance\" width=\"676\" height=\"463\" \/><\/a><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Import math\n\n      # Get center point of new object\n      for rect in objects_rect:\n          x, y, w, h, index = rect\n          cx = (x + x + w) \/\/ 2\n          cy = (y + y + h) \/\/ 2\n\n          # Find out if that object was detected already\n          same_object_detected = False\n          for id, pt in self.center_points.items():\n              dist = math.hypot(cx - pt[0], cy - pt[1])\n\n              if dist &lt; 25:\n                  self.center_points[id] = (cx, cy)\n                  # print(self.center_points)\n                  objects_bbs_ids.append([x, y, w, h, id, index])\n                  same_object_detected = True\n                  break\n<\/pre>\n<ul>\n<li>The math.hypot() method returns the Euclidean distance.<\/li>\n<li>Here we check if the distance is less than 25 then the object is the same object of the previous frame.<\/li>\n<\/ul>\n<p><strong>Vehicle Counter:<\/strong><\/p>\n<h3>Steps for Vehicle Detection and Classification using OpenCV:<\/h3>\n<p>1. Import necessary packages and Initialize the network.<br \/>\n2. Read frames from a video file.<br \/>\n3. Pre-process the frame and run the detection.<br \/>\n4. Post-process the output data.<br \/>\n5. Track and count all vehicles on the road<br \/>\n6. Save the final data to a CSV file.<\/p>\n<h4>Step 1 &#8211; Import necessary packages and Initialize the network:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import cv2\nimport csv\nimport collections\nimport numpy as np\nfrom tracker import *\n\n# Initialize Tracker\ntracker = EuclideanDistTracker()\n\n# Detection confidence threshold\nconfThreshold =0.1\nnmsThreshold= 0.2\n<\/pre>\n<ul>\n<li>First, we import all the necessary packages we need for the project.<\/li>\n<li>Then, we initialize the EuclideanDistTracker() object from the tracker program we\u2019ve created before and set the object as \u201ctracker\u201d.<\/li>\n<li>confThreshold and nmsThreshold are minimum confidence score threshold for detection and Non-Max suppression threshold respectively.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">  # Middle cross line position\nmiddle_line_position = 225   \nup_line_position = middle_line_position - 15\ndown_line_position = middle_line_position + 15\n<\/pre>\n<ul>\n<li>These line positions are the crossing line positions that will be used to count vehicles.<\/li>\n<\/ul>\n<p>Note: Modify middle_line_position according to your need.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Store Coco Names in a list\n\nclassesFile = \"coco.names\"\nclassNames = open(classesFile).read().strip().split('\\n')\nprint(classNames)\nprint(len(classNames))\n<\/pre>\n<ul>\n<li>YOLOv3 is trained on the COCO dataset, so we read the file that contains all the class names and store the names in a list.<\/li>\n<li>The COCO dataset contains 80 different classes.<\/li>\n<li>We need to detect only cars, motorbikes, buses, and trucks for this project, that\u2019s why the required_class_index contains the index of those classes from the coco dataset.<\/li>\n<\/ul>\n<p><strong>Output-<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/coco.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-83307\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/coco.png\" alt=\"coco\" width=\"1920\" height=\"1078\" \/><\/a><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">## Model Files\nmodelConfiguration = 'yolov3-320.cfg'\nmodelWeights = 'yolov3-320.weights'\n\n# configure the network model\nnet = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)\n\n# Configure the network backend\n\nnet.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\nnet.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n\n# Define random colour for each class\nnp.random.seed(42)\ncolors = np.random.randint(0, 255, size=(len(classNames), 3), dtype='uint8')\n<\/pre>\n<ul>\n<li>Configure the network using cv2.dnn.readNetFromDarknet() function.<\/li>\n<li>Here we\u2019re using GPU, that\u2019s why we set \u201cnet.setPreferableBackend\u201d as DNN_BACKEND_CUDA and net.setPreferableTarget as DNN_TARGET_CUDA.<\/li>\n<li>If you\u2019re using GPU, set the DNN backend as CUDA and if you\u2019re using CPU then you can comment out those lines.<\/li>\n<li>Using np.random.randint() function we generate a random color for each class in our dataset. We\u2019ll use these colors to draw the rectangles around the objects.<\/li>\n<li>random.seed() function saves the state of a random function so that it can generate some random number on every execution, even if it will generate the same random numbers in other machines too.<\/li>\n<\/ul>\n<h4>Step 2 &#8211; Read frames from a Video file:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Initialize the videocapture object\n      cap = cv2.VideoCapture('video.mp4')\n      def realTime():\nwhile True:\n    success, img = cap.read()\n    img = cv2.resize(img,(0,0),None,0.5,0.5)\n    ih, iw, channels = img.shape\n\n     # Draw the crossing lines\n\n    cv2.line(img, (0, middle_line_position), (iw, middle_line_position), \n(255, 0, 255), 1)\n    cv2.line(img, (0, up_line_position), (iw, up_line_position), (0, 0, 255), 1)\n    cv2.line(img, (0, down_line_position), (iw, down_line_position), (0, 0, 255), 1)\n\n    # Show the frames\n    cv2.imshow('Output', img)\n\n      if __name__ == '__main__':\n          realTime()\n<\/pre>\n<ul>\n<li>Read the video file through the videoCapture object and set the object as cap.<\/li>\n<li>cap.read() reads each frame from the capture object.<\/li>\n<li>Using cv2.reshape() we reduced our frame by 50 percent.<\/li>\n<li>Then using the cv2.line() function we draw the crossing lines in the frame.<\/li>\n<li>And finally, we used cv2.imshow() function to show the output image.<\/li>\n<\/ul>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/imshow-crossinglines.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-83308\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/imshow-crossinglines.png\" alt=\"imshow crossinglines\" width=\"1920\" height=\"1078\" \/><\/a><\/p>\n<h4>Step 3 &#8211; Pre-process the frame and run the detection:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">input_size = 320\n\n   blob = cv2.dnn.blobFromImage(img, 1 \/ 255, (input_size, input_size), [0, 0, 0], 1, crop=False)\n\n   # Set the input of the network\n   net.setInput(blob)\n   layersNames = net.getLayerNames()\n   outputNames = [(layersNames[i[0] - 1]) for i in net.getUnconnectedOutLayers()]\n   # Feed data to the network\n   outputs = net.forward(outputNames)\n  \n   # Find the objects from the network output\n   postProcess(outputs,img)\n<\/pre>\n<ul>\n<li>Our version of YOLO takes 320&#215;320 image objects as input. The input to the network is a blob object. The function dnn.blobFromImage() takes an image as input and returns a resized and normalized blob object.<\/li>\n<li>The net.forward() is used to feed the image to the network. And it returns an output.<\/li>\n<li>And finally, we call our custom postProcess() function to post-process the output.<\/li>\n<\/ul>\n<h4>Step 4 &#8211; Post-process the output data:<\/h4>\n<p>The network forward output contains 3 outputs. Each output object is a vector of length 85.<\/p>\n<ul>\n<li>4x the bounding box (centerX, centerY, width, height)<\/li>\n<li>1x box confidence<\/li>\n<li>80x class confidence<br \/>\nSo, let\u2019s define our post-processing function.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">detected_classNames = []\ndef postProcess(outputs,img):\n   global detected_classNames\n   height, width = img.shape[:2]\n    boxes = []\n    classIds = []\n    confidence_scores = []\n    detection = []\n    for output in outputs:\n        for det in output:\n            scores = det[5:]\n            classId = np.argmax(scores)\n            confidence = scores[classId]\n            if classId in required_class_index:\n                if confidence &gt; confThreshold:\n                    # print(classId)\n                    w,h = int(det[2]*width) , int(det[3]*height)\n                    x,y = int((det[0]*width)-w\/2) , int((det[1]*height)-h\/2)\n                    boxes.append([x,y,w,h])\n                    classIds.append(classId)\n                    confidence_scores.append(float(confidence))\n<\/pre>\n<ul>\n<li>First, we defined an empty list \u2018detected_classNames\u2019 where we\u2019ll store all the detected classes in a frame.<\/li>\n<li>Using two for loops we iterate through each vector of each output and collect confidence score and classId index.<\/li>\n<li>After that, we check if the class confidence score is greater than our defined confThreshold. Then we collect the information about the class and store the box coordinate points, class-Id, and Confidence score in three separate lists.<\/li>\n<\/ul>\n<p><strong>\u2192Non-Max Suppression:-<\/strong><\/p>\n<p>YOLO sometimes gives multiple bounding boxes for a single object, so we have to reduce the number of detection boxes and have to take the best detection box for each class.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">   # Apply Non-Max Suppression\n    indices = cv2.dnn.NMSBoxes(boxes, confidence_scores, confThreshold, \nnmsThreshold)\n    # print(classIds)\n    for i in indices.flatten():\n        x, y, w, h = boxes[i][0], boxes[i][1], boxes[i][2], boxes[i][3]\n        # print(x,y,w,h)\n\n        color = [int(c) for c in colors[classIds[i]]]\n        name = classNames[classIds[i]]\n        detected_classNames.append(name)\n\n\n        # Draw classname and confidence score \n        cv2.putText(img,f'{name.upper()} {int(confidence_scores[i]*100)}%',\n                  (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)\n\n        # Draw bounding rectangle\n        cv2.rectangle(img, (x, y), (x + w, y + h), color, 1)\n        detection.append([x, y, w, h, required_class_index.index(classIds[i])])\n<\/pre>\n<ul>\n<li>Using the NMSBoxes() method we reduce the number of boxes and take only the best detection box for the class.<\/li>\n<li>cv2.putText draws text in the frame.<\/li>\n<li>Using cv2.rectangle() we draw the bounding box around the detected object.<\/li>\n<\/ul>\n<h4>Step 5 &#8211; Track and count all vehicles on the road:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Update the tracker for each object\n    boxes_ids = tracker.update(detection)\n    for box_id in boxes_ids:\n        count_vehicle(box_id)\n<\/pre>\n<ul>\n<li>After getting all the detection, we keep track of those objects using the tracker object. The tracker.update() function keeps track of every detected object and updates the position of the objects.<\/li>\n<li>Count_vehicle is a custom function that counts the number of vehicles that crossed through the road.<\/li>\n<\/ul>\n<p><strong>The count_vehicle Function:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># List for store vehicle count information\ntemp_up_list = []\ntemp_down_list = []\n<\/pre>\n<p>Create two temporary empty lists to store the vehicles id\u2019s that enter the entry crossing line.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">up_list = [0, 0, 0, 0]\ndown_list = [0, 0, 0, 0]\n<\/pre>\n<p>Up_list and down_list are for counting those 4 vehicle classes in the up route and down route.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Function for count vehicle\ndef count_vehicle(box_id):\n\n    x, y, w, h, id, index = box_id\n\n    # Find the center of the rectangle for detection\n    center = find_center(x, y, w, h)\n    ix, iy = center\n<\/pre>\n<p>The find_center function returns the center point of a rectangle box.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Find the current position of the vehicle\n    if (iy &gt; up_line_position) and (iy &lt; middle_line_position):\n        if id not in temp_up_list:\n            temp_up_list.append(id)\n\n    elif iy &lt; down_line_position and iy &gt; middle_line_position:\n        if id not in temp_down_list:\n            temp_down_list.append(id)\n            \n    elif iy &lt; up_line_position:\n        if id in temp_down_list:\n            temp_down_list.remove(id)\n            up_list[index] = up_list[index]+1\n\n    elif iy &gt; down_line_position:\n        if id in temp_up_list:\n            temp_up_list.remove(id)\n            down_list[index] = down_list[index] + 1\n<\/pre>\n<ul>\n<li>In this part, we keep track of each vehicle position and their corresponding Ids.<\/li>\n<li>First, we check if the object is between the up-crossing line and middle crossing line, then the id of the object is temporality stored in up_list for up route vehicle counting. And we do the opposite for the down route vehicles also.<\/li>\n<li>And then we check if the object has crossed the down line or not. If the object crossed the down line then the id of the object is counted as an up route vehicle, and we add 1 with the particular type of class counter.<\/li>\n<li>We need only y coordinate points because we\u2019re counting vehicles on the Y-axis.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Draw circle in the middle of the rectangle\ncv2.circle(img, center, 2, (0, 0, 255), -1)  # end here\n# print(up_list, down_list)\n<\/pre>\n<p>Cv2.circle() draws a circle in the frame. In our case, we\u2019re drawing the center point of the car.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">  cv2.putText(img, \"Up\", (110, 20), cv2.FONT_HERSHEY_SIMPLEX, font_size, \nfont_color, font_thickness)\n    cv2.putText(img, \"Down\", (160, 20), cv2.FONT_HERSHEY_SIMPLEX, font_size, \nfont_color, font_thickness)\n    cv2.putText(img, \"Car:        \"+str(up_list[0])+\"     \"+ str(down_list[0]), (20, 40), \ncv2.FONT_HERSHEY_SIMPLEX, font_size, font_color, font_thickness)\n    cv2.putText(img, \"Motorbike:  \"+str(up_list[1])+\"     \"+ str(down_list[1]), (20, 60), \ncv2.FONT_HERSHEY_SIMPLEX, font_size, font_color, font_thickness)\n    cv2.putText(img, \"Bus:        \"+str(up_list[2])+\"     \"+ str(down_list[2]), (20, 80), \ncv2.FONT_HERSHEY_SIMPLEX, font_size, font_color, font_thickness)\n    cv2.putText(img, \"Truck:      \"+str(up_list[3])+\"     \"+ str(down_list[3]), (20, 100), \ncv2.FONT_HERSHEY_SIMPLEX, font_size, font_color, font_thickness)\n\n<\/pre>\n<p>Finally, draw the counts to show the vehicle counting on the frame in real-time.<\/p>\n<h3>Vehicle Detection, Counting and Classification Output<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/vehicle-detection-counting-classification-output.gif\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-83309\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/vehicle-detection-counting-classification-output.gif\" alt=\"vehicle detection counting classification output\" width=\"632\" height=\"388\" \/><\/a><\/p>\n<p><em>Video Source: YouTube<\/em><\/p>\n<h4>Step 6 &#8211; Save the final data to a CSV file:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Write the vehicle counting information in a file and save it\n\nwith open(\"data.csv\", 'w') as f1:\n    cwriter = csv.writer(f1)\n    cwriter.writerow(['Direction', 'car', 'motorbike', 'bus', 'truck'])\n    up_list.insert(0, \"Up\")\n    down_list.insert(0, \"Down\")\n    cwriter.writerow(up_list)\n    cwriter.writerow(down_list)\nf1.close()\n<\/pre>\n<ul>\n<li>With the open function, we opened a new file data.csv with write permission only.<\/li>\n<li>Then we write 3 rows, the first row contains class names and directions, and the 2nd and 3rd row contains up and down route counts respectively.<\/li>\n<li>The writerow() function writes a row to the file.<\/li>\n<\/ul>\n<h3>Now, let\u2019s do it for a single image:<\/h3>\n<p>It is not possible to count vehicles that travel through a road in a particular direction on a static image. Because it is a continuous process. But can classify and count the number of vehicles that are present on the road or an image. And later we can analyze the data.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">image_file = 'vehicle classification-image02.png'\ndef from_static_image(image):\n    img = cv2.imread(image)\n\n    blob = cv2.dnn.blobFromImage(img, 1 \/ 255, (input_size, input_size), [0, 0, 0], 1, \n   \t\t\t\t\t\t\t\tcrop=False)\n    # Set the input of the network\n    net.setInput(blob)\n    layersNames = net.getLayerNames()\n    outputNames = [(layersNames[i[0] - 1]) for i in net.getUnconnectedOutLayers()]\n    # Feed data to the network\n    outputs = net.forward(outputNames)\n\n    # Find the objects from the network output\n    postProcess(outputs,img)\n    # count the frequency of detected classes\n    frequency = collections.Counter(detected_classNames)\n    print(frequency)\n\n<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<p>Counter({&#8216;car&#8217;: 21, &#8216;truck&#8217;: 5})<\/p>\n<ul>\n<li>First we create a function that takes an image file as input.<\/li>\n<li>Using the cv2.imread() function we read the image.<\/li>\n<li>After that we repeat the exact same process as the previous step for detecting objects.<\/li>\n<li>Previously we stored all the detected objects in the \u2018detected_classNames\u2019 list. So using collections.Counter(detected_classNames) we calculate the frequency of the elements in the list. It returns a dictionary containing the element as key of the dictionary and frequency of the element as the value of that particular key.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">   # Draw counting texts in the frame\n    cv2.putText(img, \"Car:        \"+str(frequency['car']), (20, 40),\n \t\tcv2.FONT_HERSHEY_SIMPLEX, font_size, font_color, font_thickness)\n    cv2.putText(img, \"Motorbike:  \"+str(frequency['motorbike']), (20, 60), \ncv2.FONT_HERSHEY_SIMPLEX, font_size, font_color, font_thickness)\n    cv2.putText(img, \"Bus:        \"+str(frequency['bus']), (20, 80), \ncv2.FONT_HERSHEY_SIMPLEX, font_size, font_color, font_thickness)\n    cv2.putText(img, \"Truck:      \"+str(frequency['truck']), (20, 100), \ncv2.FONT_HERSHEY_SIMPLEX, font_size, font_color, font_thickness)\n\n    cv2.imshow(\"image\", img)\n    cv2.waitKey(0)\n\n    with open(\"static-data.csv\", 'a') as f1:\n        cwriter = csv.writer(f1)\n        cwriter.writerow([image, frequency['car'], frequency['motorbike'], frequency['bus'], \nfrequency['truck']])\n        f1.close()\n\nif __name__ == '__main__':\n    # realTime()\n    from_static_image(image_file)\n<\/pre>\n<ul>\n<li>After that we draw the counting texts on the frame .<\/li>\n<li>cv2.imshow() shows the output image in a new opencv window.<\/li>\n<li>cv2.waitKey(0) keeps the window open until any key is pressed.<\/li>\n<li>And finally, we save the data to a csv file.<\/li>\n<\/ul>\n<h3>Output of OpenCV Vehicle Detection and Counting Project:<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/opencv-vehicle-detection-counting-output.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-83310\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/07\/opencv-vehicle-detection-counting-output.png\" alt=\"opencv vehicle detection counting output\" width=\"1920\" height=\"1078\" \/><\/a><\/p>\n<p>We can see that all the vehicles are successfully detected and have the counting numbers for each detected class.<\/p>\n<h3>Summary<\/h3>\n<p>In this project, we\u2019ve built an advanced vehicle detection and classification system using OpenCV. We\u2019ve used the YOLOv3 algorithm along with OpenCV to detect and classify objects. And we learned about deep neural networks, file handling systems, and some advanced computer vision techniques.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Today, we\u2019re going to build an advanced vehicle detection and classification project using OpenCV. We\u2019ll use the YOLOv3 model with OpenCV-python. Open-CV is a real-time computer vision library of Python. We can use YOLO&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":83311,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[210],"tags":[2596,3594,204,3763,3764,3765],"class_list":["post-83213","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-machine-learning","tag-computer-vision","tag-computer-vision-python","tag-machine-learning-project","tag-opencv-vehicle-classification","tag-opencv-vehicle-counting","tag-opencv-vehicle-detection"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Vehicle Counting, Classification &amp; Detection using OpenCV &amp; Python - TechVidvan<\/title>\n<meta name=\"description\" content=\"Vehicle detection, classification &amp; counting system using the YOLO algorithm along with OpenCV to detect &amp; classify vehicles.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Vehicle Counting, Classification &amp; Detection using OpenCV &amp; Python - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Vehicle detection, classification &amp; counting system using the YOLO algorithm along with OpenCV to detect &amp; classify vehicles.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-13T03:30:15+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/vehicle-counting-classification-opencv-python.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"13 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Vehicle Counting, Classification &amp; Detection using OpenCV &amp; Python - TechVidvan","description":"Vehicle detection, classification & counting system using the YOLO algorithm along with OpenCV to detect & classify vehicles.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/","og_locale":"en_US","og_type":"article","og_title":"Vehicle Counting, Classification &amp; Detection using OpenCV &amp; Python - TechVidvan","og_description":"Vehicle detection, classification & counting system using the YOLO algorithm along with OpenCV to detect & classify vehicles.","og_url":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-07-13T03:30:15+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/vehicle-counting-classification-opencv-python.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"13 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Vehicle Counting, Classification &amp; Detection using OpenCV &amp; Python","datePublished":"2021-07-13T03:30:15+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/"},"wordCount":1792,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/vehicle-counting-classification-opencv-python.jpg","keywords":["computer vision","computer vision Python","machine learning project","opencv vehicle Classification","opencv vehicle Counting","opencv vehicle detection"],"articleSection":["Machine Learning Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/","url":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/","name":"Vehicle Counting, Classification &amp; Detection using OpenCV &amp; Python - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/vehicle-counting-classification-opencv-python.jpg","datePublished":"2021-07-13T03:30:15+00:00","description":"Vehicle detection, classification & counting system using the YOLO algorithm along with OpenCV to detect & classify vehicles.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/vehicle-counting-classification-opencv-python.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/vehicle-counting-classification-opencv-python.jpg","width":1200,"height":628,"caption":"vehicle counting classification opencv python"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/opencv-vehicle-detection-classification-counting\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Vehicle Counting, Classification &amp; Detection using OpenCV &amp; Python"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/83213","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=83213"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/83213\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/83311"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=83213"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=83213"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=83213"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}