Smart Parking System using Python and OpenCV
Last Updated :
08 Jul, 2024
To set up a parking lot camera for our project, Here we have used a downloaded video and converted it into an image. This setup allows us to simulate a real parking lot scenario for analysis. This approach enables us to experiment and develop our parking lot monitoring system without needing access to a real parking lot.
This article's main goal is to walk you through one of the simplest methods for creating a smart parking system with just a webcam and a few lines of Python code.
Sample Video: Link
Parking VideoThe Selector Image to choose the location
We must construct the selector first. First, we import the necessary modules. Following that, we can set to work generating the image from which the parking spaces will be chosen. To do that, we can save the initial frame that the webcam captures, and utilize the image to choose the locations. The following code works like this:
- Opens the video stream in a variable; and determines if the stream was opened successfully.
- Writes the first frame into frame.jpg.
- The stream is released and all windows are closed.
- The new saved picture is read in another variable.
Python
import cv2, csv, time
video = cv2.VideoCapture('Location to Video')
source, image = video.read()
# Save the image fot ROI Selection
cv2.imwrite("frame.jpg", image)
video.release()
cv2.destroyAllWindows()
Having saved the first frame in the image variable, we can now utilize the selectROIs function to identify our parking spaces. Regions of interest, or ROIs, are parts of the image to which various functions and filters will be applied in order to obtain the desired results.
Using the selectROIs function once more, this will yield a list (type: numpy.ndarray) with the numbers we require to put together photos using their borders as our ROIs.
Python
import cv2, csv, time
video = cv2.VideoCapture('Data/lot.mp4')
source, image = video.read()
cv2.imwrite("frame.jpg", image)
video.release()
cv2.destroyAllWindows()
image = cv2.imread("frame.jpg")
# Need to resixe the image
height, width, layers = image.shape
image = cv2.resize(image, (int(width * 0.35), int(height * 0.35)))
r = cv2.selectROI('Selector', image, showCrosshair=False, fromCenter=False)
rlist = list(r)
with open('Data/rois1.csv', 'a', newline='') as outf:
csvw = csv.writer(outf)
csvw.writerow(rlist)
We'll save our list in the "r" variable. The following are the arguments passed to the cv2.selectROIs function:
- We will be able to select the ROIs using a window called "Selector."
- The variable img holds the image that we wish to choose.
- showCrosshair = Flase eliminates the selection's inner center lines. Since there is no effect on the outcome, this can be set to True.
- fromCenter = False is a crucial setting since it would have made correct selection much more difficult if it had been set to True.
It's time to enter all of the parking spaces that have been chosen into a.csv file. Once we get the correct data, we may save it in the.csv file that we will use in the future.
Applying selector algorithm on all parking slotsThe Detector to process the Image
After parking spaces have been chosen, it's time to process the images. The method I used to tackle this was:
- From the.csv file, obtain the coordinates.
- Construct a new picture using it.
- Use the Canny function that OpenCV offers.
- Within the new image, count the white pixels.
- Determine the range of pixels that would be occupied.
- On the live feed, draw a rectangle in either red or green.
Step 1: We must define a function for each of these operations so that it may be used at each location. This is how the function looks like:
Python
def drawRectangle(image, a, b, c, d, low_threshold, high_threshold, min_pix, max_pix):
sub_image = image[b:b + d, a:a + c]
edges = cv2.Canny(sub_image, low_threshold, high_threshold)
pix = cv2.countNonZero(edges)
if pix in range(min_pix, max_pix):
cv2.rectangle(image, (a, b), (a + c, b + d), (0, 255, 0), 3)
Spots.location += 1
else:
cv2.rectangle(image, (a, b), (a + c, b + d), (0, 0, 255), 3)
Now that we have the function, all we need to do is apply it to each set of coordinates in the.csv file.
First of all, we have several parameters that would be useful if we could change them in real time while the script is running, preferably via a GUI. To accomplish this, we need to construct a few track bars. Fortunately, OpenCV allows us to do so without requiring additional libraries.
Step 2: First, we need a callback function that does nothing but serves as a parameter when producing track bars with OpenCV. Actually, the callback parameter has a specific purpose, but we do not use it here.
Python
Step 3: Now we need to make the track bars. To accomplish this, we will use the cv2.namedWindow and cv2.createTrackbar functions.
Python
cv2.namedWindow('parameters')
cv2.createTrackbar('Threshold1', 'parameters', 186, 700, callback)
cv2.createTrackbar('Threshold2', 'parameters', 122, 700, callback)
cv2.createTrackbar('Min pixels', 'parameters', 100, 1500, callback)
cv2.createTrackbar('Max pixels', 'parameters', 534, 1500, callback)
Step 4: Now that we've constructed the GUI for operating the parameters, there's just one thing remaining. This represents the number of available spots in the image. This is defined in the drawRectangle as spots.loc. This is a static variable that must be defined at the start of the program. This variable is static because we want the outcome of every drawRectangle function we call to be written to the same global variable rather than a different variable for each function. This ensures that the returned number of available spaces does not exceed the actual amount.
Python
class Spots:
location = 0
Step 5: Now that we're almost there, all we need to do is extract the data from the.csv file, convert it all to integers, and run our created functions in an infinite loop.
Python
while video.isOpened():
Spots.location = 0
source, image = video.read()
if not source:
break
height, width, layers = image.shape
image = cv2.resize(image, (int(width * 0.35), int(height * 0.35)))
min_pix = cv2.getTrackbarPos('Min pixels', 'parameters')
max_pix = cv2.getTrackbarPos('Max pixels', 'parameters')
low_threshold = cv2.getTrackbarPos('Threshold1', 'parameters')
high_threshold = cv2.getTrackbarPos('Threshold2', 'parameters')
for i in range(roi_data.shape[0]):
drawRectangle(image, roi_data.iloc[i, 0], roi_data.iloc[i, 1], roi_data.iloc[i, 2], roi_data.iloc[i, 3],
low_threshold, high_threshold, min_pix, max_pix)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(image, 'Available Spots: ' + str(Spots.location),
(10, 30), font, 1, (0, 255, 0), 3)
cv2.imshow('Frame', image)
canny = cv2.Canny(image, low_threshold, high_threshold)
cv2.imshow('Canny', canny)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video.release()
cv2.destroyAllWindows()
Understanding the Loop in Our Script
- First, we set the number of available places to 0 to avoid adding numbers for each frame.
- Then we start two streams: the original image and the transformed image. This helps develop a better understanding of how this script functions and how the image is processed.
- After that, we must obtain the values of the parameters set in the parameters GUI we generated for each iteration. This is accomplished using the cv2.getTrackbarPos function.
- The most crucial portion now takes place: the drawRectangle function is applied to all of the coordinates collected by the Selector script.
What remains is to write the number of available spots on the resulting image, display the Canny function and result.
Output Video
Conclusion
Smart parking is a popular topic these days, and there are numerous implementations that can lead to a well-functioning system. I am aware that this is not ideal there are many alternatives that are more tuned and can operate in a variety of situations.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read