-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parking.py
89 lines (64 loc) · 2.79 KB
/
Parking.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from typing import List
import cv2
import numpy as np
from Car import Car
from Point import Point
from Slot import Slot
class Parking:
def __init__(self, id, img_path: str, rows: int, columns: int):
self.id = id
self.img = cv2.imread(img_path)
self.rows = rows
self.columns = columns
self.width = self.img.shape[1]
self.height = self.img.shape[0]
self.matrix = self.calc_matrix()
# def width(self):
# return int(self.img.shape[1])
#
# def height(self):
# return self.img.shape[0]
def calc_matrix(self):
# compute perspective matrix
input = np.float32([[7, 104], [348, 38], [472, 118], [42, 248]])
output = np.float32([[0, 0], [self.width - 1, 0], [self.width - 1, self.height - 1], [0, self.height - 1]])
return cv2.getPerspectiveTransform(input, output)
def coords_parking(self) -> List[Slot]:
width_parking = self.width / self.columns
height_parking = self.height / self.rows
slots = []
id = 0
for row in np.arange(self.rows):
for column in np.arange(self.columns):
point_upper_left = Point(column * width_parking, row * height_parking)
point_lower_right = Point(point_upper_left.x + width_parking, point_upper_left.y + height_parking)
slots.append(Slot(id, point_upper_left, point_lower_right))
id += 1
return slots
def transform_cars(self, cars: List[Car]) -> List[Point]:
centers = [car.center() for car in cars]
new_centers = []
for point in centers:
new_point = np.array([point.x, point.y], dtype=np.float32)
pts = new_point.reshape(-1, 1, 2).astype(np.float32)
transformed_arr = cv2.perspectiveTransform(pts, self.matrix)
new_centers.append(Point(transformed_arr[0][0][0], transformed_arr[0][0][1]))
return new_centers
def get_slots_occupied(self, cars: List[Car]):
slots = self.coords_parking()
transformed_centers = self.transform_cars(cars)
slots_occupied = []
for slot in slots:
res = False
for center in transformed_centers:
res |= slot.check_occupied(center)
slots_occupied.append(res)
slot.isOccupied = res
return slots_occupied
def draw_transformed_img(self):
# do perspective transformation setting area outside input to black
imgOutput = cv2.warpPerspective(self.img, self.matrix, (self.width, self.height), cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT,
borderValue=(0, 0, 0))
# save the warped output
cv2.imwrite('parking_warped.jpg', imgOutput)