class DarknetYolov4:
def __init__(self,configPath,weightPath,metaPath,thresh):
# Import the global variables. This lets us instance Darknet once, then just call performDetect() again without instancing again
global metaMain, netMain, altNames # pylint: disable=W0603
assert 0 < thresh < 1, "Threshold should be a float between zero and one (non-inclusive)"
if not os.path.exists(configPath):
raise ValueError("Invalid config path `" + os.path.abspath(configPath) + "`")
if not os.path.exists(weightPath):
raise ValueError("Invalid weight path `" + os.path.abspath(weightPath) + "`")
if not os.path.exists(metaPath):
raise ValueError("Invalid data file path `" + os.path.abspath(metaPath) + "`")
if netMain is None:
netMain = load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1
if metaMain is None:
metaMain = load_meta(metaPath.encode("ascii"))
if altNames is None:
# In Python 3, the metafile default access craps out on Windows (but not Linux)
# Read the names file and create a list to feed to detect
try:
with open(metaPath) as metaFH:
metaContents = metaFH.read()
import re
match = re.search("names *= *(.*)$", metaContents, re.IGNORECASE | re.MULTILINE)
if match:
result = match.group(1)
else:
result = None
try:
if os.path.exists(result):
with open(result) as namesFH:
namesList = namesFH.read().strip().split("\n")
altNames = [x.strip() for x in namesList]
except TypeError:
pass
except Exception:
pass
self.netMain=netMain
self.metaMain=metaMain
self.thresh=thresh
def getdetresults(self,imagePath):
def createdictlist(dictlist, key, newlist):
if key in dictlist.keys():
dictlist[key].append(newlist)
else:
dictlist[key] = [newlist]
netMain, metaMain, thresh = self.netMain, self.metaMain, self.thresh
detections = detect(netMain, metaMain, imagePath.encode("ascii"), thresh)
detresults={}
for detection in detections:
label = detection[0]
confidence = detection[1]
bounds = detection[2]
yExtent = int(bounds[3])
xEntent = int(bounds[2])
# Coordinates are around the center
xCoord = int(bounds[0] - bounds[2] / 2)
yCoord = int(bounds[1] - bounds[3] / 2)
scorex1y1x2y2=[round(confidence,2),xCoord, yCoord,xCoord + xEntent, yCoord + yExtent]
createdictlist(detresults, label, scorex1y1x2y2)
return detresults