Evertise
26 Jan 2023, 03:24 GMT+10
Systems for detecting and counting vehicles are crucial components of a smart transportation system, especially when it comes to traffic control. Roads will be monitored by this vision-based technology, which will then identify and count different types of vehicles.
A Vehicle Detection software seeks to provide details about;
1. Counting vehicle
2. speed measurement for vehicles
3. Identifying accidents on the road
4. Forecasting traffic flow, etc.
In this article, we'll code a system for counting and detecting vehicles. It will be sufficient to function for both still images and moving pictures. For the same, we'll be using OpenCV for carrying out all image processing operations and for detecting and counting cars and buses using a haar cascade classifier. However, you can also create your own haar cascade classifier.
Prerequisites For Vehicle Detection Software
An image-processing library is OpenCV. It is intended to address issues with computer vision. A C/C++ library called OpenCV has been enhanced by Python.
The Python programming language uses the NumPy library to provide multi-dimensional arrays, matrices, etc. It is a free and open-source Python library for numbers.
NumPy offers the following;
1. program integration tools for C/C++ and Fortran
2. specialized operations
3. a strong item for an N-dimensional array.
4. features such as useful Fourier transform, random number generation, and more.
1. # Import libraries
2. from PIL import the Image
3. import cv2
4. import NumPy as np
5. import requests
Coding Vehicle Detection Software By Using Open CV - Image
You require to extract an Image to work on then using the NumPy array start converting and resizing it.
image = Image.open(requests.get('https://a57.foxnews.com/media.foxbusiness.com/BrightCove/854081161001/201805/2879/931/524/854081161001_5782482890001_5782477388001-vs.jpg', stream=True).raw)
image = image.resize((450,250))
image_arr = np.array(image)
image
Now, you need a greyscale converted Image for getting better output.
grey = cv2.cvtColor(image_arr,cv2.COLOR_BGR2GRAY)
Image.fromarray(grey)
After this, we'll use GaussianBlur to clean out the image's noise. One image processing approach is a gaussian blur. It is frequently used in visual design as well to lessen noise and smooth the image so that further preprocessing would produce better results. Gaussian blur approach also lessens the image's details while minimizing image noise. Here, we'll use the GaussianBlur function to implement this preprocessing method ().
blur = cv2.GaussianBlur(grey,(5,5),0)
Image.fromarray(blur)
Here, we'll enlarge the picture. Dilation is one of the morphological strategies in which we attempt to fill the pixels with the element, often referred to as kernels or the structured pieces, to fill the remaining spaces in the images as needed.
dilated = cv2.dilate(blur,np.ones((3,3)))
Image.fromarray(dilated)
We will now use the kernel to conduct a morphology transformation. Here, we're employing a morphology-Ex approach, which instructs the function to perform certain image processing tasks. The second argument concerns the necessary procedures, and you might require circular or elliptical-shaped kernels. The get structuring element method will be used to implement the morphology-Ex method in OpenCV.
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2))
closing = cv2.morphologyEx(dilated, cv2.MORPH_CLOSE, kernel)
Image.fromarray(closing)
To detect autos, we now require a car cascade. Therefore, we must first upload these to Collaborate (if you are doing it in Collab, add the cascade files within the same folder if you are doing it locally) and provide the path car cascade src. Here, we'll train the photos from the pre-trained XML file using OpenCV's preset CascadeClassifier function (Cascade file - car). To utilize detectMultiScale, we must detect numerous items, such as vehicles.
car_cascade_src = 'cars.xml'
car_cascade = cv2.CascadeClassifier(car_cascade_src)
cars = car_cascade.detectMultiScale(closing, 1.1, 1)
cars
The results of car cascade;
array([[376, 1, 22, 22],
[307, 4, 27, 27],
[196, 10, 28, 28],
[ 35, 2, 30, 30],
[150, 163, 68, 68],
[318, 121, 82, 82],
[101, 3, 43, 43],
[317, 66, 66, 66],
[274, 20, 38, 38],
[256, 52, 79, 79],
[245, 24, 20, 20],
[250, 35, 25, 25],
[ 63, 40, 22, 22],
[209, 88, 54, 54],
[ 13, 25, 43, 43],
[384, 84, 59, 59],
[145, 91, 53, 53],
[ 52, 44, 39, 39],
[237, 38, 49, 49],
[362, 43, 46, 46],
[268, 106, 60, 60]], dtype=int32)
We'll create a rectangle around any cars we identify using the contours that were previously returned. Here, we will observe that it will draw a red-bound rectangle around each car it finds.
cnt = 0
for (x,y,w,h) in cars:
cv2.rectangle(image_arr,(x,y),(x+w,y+h),(255,0,0),2)
cnt += 1
print(cnt, " cars found")
Image.fromarray(image_arr)
After this, the number of cars will appear on your screen depending on how many cars your Image shows.
Coding Vehicle Detection Software By Using Open CV - Video
The vehicle detection and counting will now be done in a video. We require the cv2.VideoWriter() method to generate the output video from frames or images. The first parameter is the path with the extension; the second is the codec for the output format; and finally, the parameters for frames per second, height, and width are required.
cascade_src = 'cars.xml'
video_src = 'Cars.mp4'
cap = cv2.VideoCapture(video_src)
car_cascade = cv2.CascadeClassifier(cascade_src)
video = cv2.VideoWriter('result.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, (450,250))
Now, we'll take a frame at a time from the input video, convert it to grayscale, and use a technique called car cascade to identify every vehicle in that frame. In the end, this film was created utilizing video. and the write() method. This video will be saved to the specified path by release().
Wrapping It Up!
We began by extracting the image that we would be working with before carrying out various operations. We learned how to utilize the haar cascade, which is used to detect objects, and how to use several haar cascades to detect cars. For other object detection, there are other pre-trained haar cascades that you can employ.
We have a broad reach because the haar cascade is used for object detection. It can be used to detect items, and we can design a unique haar cascade for particular objects.
Get a daily dose of Texas Guardian news through our daily email, its complimentary and keeps you fully up to date with world and business news as well.
Publish news of your business, community or sports group, personnel appointments, major event and more by submitting a news release to Texas Guardian.
More InformationWell-traveled coach Rick Pitino could be on the move again. Pitino, who is listed by NCAA Statistics to have a ...
The Detroit Lions are signing free-agent safety C.J. Gardner-Johnson to a one-year, $8 million deal, multiple media outlets reported Sunday ...
Sophomore Ryan Nembhard poured in a career-high 30 points and No. 6 seed Creighton converted all 22 of its free ...
The New York Rangers remained red-hot Sunday night when they rode a six-goal first period to a 7-0 rout of ...
De'Veon Smith's 1-yard touchdown run late in the third quarter vaulted the Arlington Renegades to a 12-10 win over the ...
Drew Timme recorded 28 points and eight rebounds and No. 3 Gonzaga reached the Sweet 16 for the eighth consecutive ...
BEIJING, China: Following the inability of China Huarong Asset Management Co Ltd to release financial reporting obligations in 2020, China ...
ZURICH, Switzerland - Depositors will be fully protected, shareholders will have their equity dwarfed, while bond holders will be largely ...
HANOI, Vietnam: SpaceX, Netflix and Boeing will join what is described as the "biggest-ever" U.S. business mission to meet in ...
TAIPEI, Taiwan: Reuters reported that after winning an order to manufacture wireless AirPods earphones for Apple for the first time, ...
TAIPEI, Taiwan: The founder of chip manufacturer TSMC, Morris Chang, said that he supports the efforts of the US to ...
MOSCOW, Russia: State run news agency TASS has reported that Russia's Industry and Trade Minister Denis Manturov said that Japanese ...