| import cv2 |
| import math |
| import numpy as np |
|
|
| from Constants import Constants |
| from EnumParkingStatus import EnumParkingStatus |
|
|
|
|
| class StatusInferEngine(): |
| def __init__(self, jsonEditor): |
| self.jsonEditor = jsonEditor |
|
|
| def inferUnknownStatus(self): |
| self._loadUnknownAnnotations() |
| self._computeStatus() |
|
|
| def _computeStatus(self): |
| for imgId, listSpaces in self.dictSpaces.items(): |
| for space in listSpaces: |
| status = int(space[Constants.JSON_PARKING_STATUS_ID_KEY]) |
| if (status == EnumParkingStatus.UNKNOWN.value): |
| spacePosition = space[Constants.JSON_SEGMENTATION_KEY] |
| npSpace = np.array([spacePosition]) |
| npSpace.shape = (4,2) |
| centroid = self._computeCentroidSpace(npSpace) |
| if (imgId in self.dictSegs): |
| list = self.dictSegs[imgId] |
| idx, mindDist = self._getMinimumDistance(centroid, list) |
| if (cv2.pointPolygonTest(np.array([npSpace]), list[idx], measureDist = False) > 0): |
| space[Constants.JSON_PARKING_STATUS_ID_KEY] = EnumParkingStatus.OCCUPIED_NEED_VAL.value |
| else: |
| space[Constants.JSON_PARKING_STATUS_ID_KEY] = EnumParkingStatus.EMPTY_NEED_VAL.value |
| else: |
| space[Constants.JSON_PARKING_STATUS_ID_KEY] = EnumParkingStatus.EMPTY_NEED_VAL.value |
|
|
| def _loadUnknownAnnotations(self): |
| self.dictSpaces = {} |
| self.dictSegs = {} |
| for annot in self.jsonEditor.json[Constants.JSON_ANNOTATIONS_KEY]: |
| tipo = int(annot[Constants.JSON_LINK_CATEG_KEY]) |
| imgId = annot[Constants.JSON_LINK_IMAGE_ID_KEY] |
| if(tipo == Constants.JSON_PARKING_SPACE_KEY): |
| if imgId not in self.dictSpaces: |
| self.dictSpaces[imgId] = [] |
| self.dictSpaces[imgId].append(annot) |
| elif(tipo == Constants.JSON_VEHICLE_KEY): |
| if imgId not in self.dictSegs: |
| self.dictSegs[imgId] = [] |
| self.dictSegs[imgId].append(self._computeCentroidVehicle(annot)) |
|
|
| def _getMinimumDistance(self, centroidParkingSpace, listCentroids): |
| idx = 0 |
| minDist = math.sqrt((listCentroids[0][0] - centroidParkingSpace[0])**2 + (listCentroids[0][1] - centroidParkingSpace[1])**2) |
| i = 1 |
| while(i < len(listCentroids)): |
| dist = math.sqrt((listCentroids[i][0] - centroidParkingSpace[0])**2 + (listCentroids[i][1] - centroidParkingSpace[1])**2) |
| if(dist < minDist): |
| minDist = dist |
| idx = i |
| i += 1 |
| return idx, minDist |
|
|
| def _computeCentroidVehicle(self, annotation): |
| segmentation = annotation[Constants.JSON_SEGMENTATION_KEY] |
| cX = 0 |
| cY = 0 |
| for seg in segmentation: |
| |
| npArray = np.array([seg], dtype=int) |
| npArray.shape = (-1,2) |
| moments = cv2.moments(npArray) |
| cX += int(moments["m10"] / moments["m00"]) |
| cY += int(moments["m01"] / moments["m00"]) |
|
|
| numSegs = len(segmentation) |
| return (cX/numSegs,cY/numSegs) |
|
|
| def _computeCentroidSpace(self, arrayNumPy): |
| moments = cv2.moments(arrayNumPy) |
| cX = int(moments["m10"] / moments["m00"]) |
| cY = int(moments["m01"] / moments["m00"]) |
| return (cX, cY) |