def YOLO(self): # 此函数用于darknet所需文件的路径声明&打开摄像头等功能 global metaMain, netMain, altNames # darknet框架自带变量,将其声明为全局变量 ############################################################################################################################# # 更改以下三个配置文件&查看一个配置文件,重要!!! ############################################################################################################################# configPath = "./yolov3-tiny.cfg" # 配置cfg文件的路径 weightPath = "./yolov3-tiny_final.weights" # 配置weight文件的路径 metaPath = "./voc.data" # 配置data文件的路径(切忌查看data文件内定义的name文件的路径&内容是否与实际相对应) if not os.path.exists(configPath): # 判断cfg文件是否存在 raise ValueError("Invalid config path `" + os.path.abspath(configPath) + "`") # 若不存在,则报错 if not os.path.exists(weightPath): # 判断weight文件是否存在 raise ValueError("Invalid weight path `" + os.path.abspath(weightPath) + "`") # 若不存在,则报错 if not os.path.exists(metaPath): # 判断data文件是否存在 raise ValueError("Invalid data file path `" + os.path.abspath(metaPath) + "`") # 若不存在,则报错 if netMain is None: # 判断netMain是否为None netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 导入weight模型文件 if metaMain is None: # 判断netMain是否为None metaMain = darknet.load_meta(metaPath.encode("ascii")) # 导入data配置文件 if altNames is None: # 判断netMain是否为None 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.cap = cv2.VideoCapture( "rtsp:192.168.1.211/user=admin&password=&channel=1&stream=0.sdp?" ) # 设定USB摄像头端口为0,使用opencv打开摄像头 if self.cap.isOpened() == 0: # 判断USB摄像头是否被打开,如果未打开,则更换摄像头端口 self.cap = cv2.VideoCapture(1) # 更换USB摄像头端口为1 self.cap.set(3, 768) # 设定摄像头视频流尺寸 self.cap.set(4, 1024) # 设定摄像头视频流尺寸 print( "Starting the YOLO loop...") # 在终端打印此消息,便于调试;此位置代表摄像头已被打开,即将进入YOLO检测环节 self.camera_state = 1 # 设定摄像头状态为1,便于Log档记录 # Create an image we reuse for each detect self.darknet_image = darknet.make_image(darknet.network_width(netMain), darknet.network_height(netMain), 3) self.camera_state = 1 # 设定摄像头状态为1,便于Log档记录
def load_network(self, configPath, weightPath, metaPath): ''' Initializes the darknet ''' 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) + "`") netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 metaMain = darknet.load_meta(metaPath.encode("ascii")) # Create an image we reuse for each detect darknet_image = darknet.make_image(darknet.network_width(netMain), darknet.network_height(netMain), 3) return netMain, metaMain, darknet_image
def __init__(self, videoPth, saveImgFolder='', duration=None): self.video = VideoFileClip(videoPth) if duration is not None: self.video = self.video.subclip(duration[0], duration[1]) self._saveImgFolder = saveImgFolder # Load yolo self.netMain = load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) self.metaMain = load_meta(metaPath.encode("ascii")) altNames = None 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") self.altNames = [x.strip() for x in namesList] except TypeError: pass except Exception: pass
def configure(config_path, weights_path, meta_path): # As we are modifying them from darknet global netMain, metaMain, altNames if not os.path.exists(config_path): raiseInvalidFile("config", os.path.abspath(config_path)) if not os.path.exists(weights_path): raiseInvalidFile("weights", os.path.abspath(weights_path)) if not os.path.exists(meta_path): raiseInvalidFile("meta", os.path.abspath(meta_path)) # Load YOLO network netMain = darknet.load_net_custom(config_path.encode("ascii"), weights_path.encode("ascii"), 0, 1) # batch size = 1 # Load data file to YOLO network metaMain = darknet.load_meta(meta_path.encode("ascii")) meta_file_content = open(meta_path, "r").read() match = re.search("labels *= *(.*)$", meta_file_content, re.IGNORECASE | re.MULTILINE) # If names file found return it as a string list if match: names_filename = match.group(1) if os.path.exists(names_filename): names_file = open(names_filename, "r") names = names_file.read().strip().split("\n") altNames = [x.strip() for x in names]
def load_network(): ''' Initializes the darknet ''' # use ros param for it configPath = "./cfg/yolov3-tiny.cfg" weightPath = "./yolov3-tiny.weights" metaPath = "./cfg/coco.data" 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) + "`") netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 metaMain = darknet.load_meta(metaPath.encode("ascii")) # Create an image we reuse for each detect darknet_image = darknet.make_image(darknet.network_width(netMain), darknet.network_height(netMain), 3) return netMain, metaMain, darknet_image
def load_network_meta(cfg_path, weights_path, meta_path): net = darknet.load_net_custom( to_str(cfg_path, True), to_str(weights_path, True), 0, 1) # batch size = 1 meta = darknet.load_meta(to_str(meta_path, True)) darknet.altNames = load_name_list(to_str(meta_path)) return net, meta
def init_detector(self): self.net_main = darknet.load_net_custom( self.config_path.encode("ascii"), self.weight_path.encode("ascii"), 0, 1) # batch size = 1 self.meta_main = darknet.load_meta(self.meta_path.encode("ascii")) try: with open(self.meta_path) as metaFH: metaContents = metaFH.read() 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") self.alt_names = [x.strip() for x in namesList] except TypeError: pass except Exception: pass self.darknet_image = darknet.make_image( darknet.network_width(self.net_main), darknet.network_height(self.net_main), 3)
def __init__(self, augmentation=None, *args, **kwargs): print("coin worker created", flush=True) sys.path.append(Config.DARKNET_PATH) import darknet sys.path.pop() self.dn = darknet self.net_main = darknet.load_net_custom( Config.config_path.encode("ascii"), Config.weight_path.encode("ascii"), 0, 1) self.meta_main = darknet.load_meta(Config.meta_path.encode("ascii")) with open(Config.meta_path) as metaFH: meta_contents = metaFH.read() import re match = re.search("names *= *(.*)$", meta_contents, re.IGNORECASE | re.MULTILINE) result = match.group(1) if match else None if os.path.exists(result): with open(result) as namesFH: names_list = namesFH.read().strip().split("\n") self.alt_names = [x.strip() for x in names_list] print( f"({self.dn.network_width(self.net_main)} {self.dn.network_height(self.net_main)}" ) self.darknet_image = darknet.make_image( darknet.network_width(self.net_main), darknet.network_height(self.net_main), 3) self.augmentation = augmentation if augmentation is not None else lambda x: x
def initYOLO(self): if not os.path.exists(self.configPath): raise ValueError("Invalid config path `" + os.path.abspath(self.configPath)+"`") if not os.path.exists(self.weightPath): raise ValueError("Invalid weight path `" + os.path.abspath(self.weightPath)+"`") if not os.path.exists(self.metaPath): raise ValueError("Invalid data file path `" + os.path.abspath(self.metaPath)+"`") if self.netMain is None: self.netMain = darknet.load_net_custom(self.configPath.encode( "ascii"), self.weightPath.encode("ascii"), 0, 1) # batch size = 1 if self.metaMain is None: self.metaMain = darknet.load_meta(self.metaPath.encode("ascii")) if self.altNames is None: try: with open(self.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") self.altNames = [x.strip() for x in namesList] except TypeError: pass except Exception: pass
def __init__(self, model_weights, model_cfg, obj_data, classes): print(model_cfg, model_weights) self.net = load_net_custom(model_cfg.encode("ascii"), model_weights.encode("ascii"), 0, 1) self.meta = load_meta(obj_data.encode("ascii")) self.class_id = {k:i for i, k in enumerate(classes)} self.classes = classes
def __init__(self, db): # db is optional self.db = db self.flag = db.flag self.example_thread = threading.Thread(target=self.__main) self.definer = ['red_light', 'arrow_light', 'green_light', 'traffic_light'] # Define all 14 traffic signs used self.separate = ['red_light', 'green_light'] self.sign = {key: [0, 0] for key in self.definer} # Initialize a dict for each type to store a counter and precision checker # ---*Class*-------------------------------------------------------------------------------------------------------------------------------------------------------------------- # | intersection | left | right | workers | bike | crosswalk | school | speed_bump | parking | bus | red_light | green_light | # ---*Counter*------------------------------------------------------------------------------------------------------------------------------------------------------------------ # | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | # ---*Precision*---------------------------------------------------------------------------------------------------------------------------------------------------------------- # | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | # ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ # YOLO config global metaMain, netMain, altNames configPath = "custom_traffic/yolov3-t4.cfg" weightPath = "backup/yolov3-t4_best(tl).weights" metaPath = "custom_traffic/obj.data" 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 = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if metaMain is None: metaMain = darknet.load_meta(metaPath.encode("ascii")) if altNames is None: 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
def __init__(self, db): # db is optional self.db = db self.flag = db.flag self.YOLO = threading.Thread(target=self.__main) self.definer = [ "Narrow", "U-Turn", "Target_Car", "Parking", "CrossWalk", "red", "green" ] # Define all traffic signs used self.sign = { key: [0, 0] for key in self.definer } # Initialize a dict for each type to store a counter and precision checker # YOLO config global metaMain, netMain, altNames configPath = "C:\\Users\\HEVEN\\darknet\\build\\darknet\\x64\\needed_files\\pams19\\yolov3.cfg" weightPath = "C:\\Users\\HEVEN\\darknet\\build\\darknet\\x64\\needed_files\\pams19\\yolov3_last.weights" metaPath = "C:\\Users\\HEVEN\\darknet\\build\\darknet\\x64\\needed_files\\pams19\\obj.data" 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 = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if metaMain is None: metaMain = darknet.load_meta(metaPath.encode("ascii")) if altNames is None: 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
def __init__(self): global metaMain, netMain, altNames configPath = "./cfg/yolov3-tiny.cfg" weightPath = "./yolov3-tiny.weights" metaPath = "./cfg/coco.data" 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: self.netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if metaMain is None: self.metaMain = darknet.load_meta(metaPath.encode("ascii")) if altNames is None: 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") self.altNames = [x.strip() for x in namesList] except TypeError: pass except Exception: pass self.out = cv2.VideoWriter("output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 10.0, (darknet.network_width(self.netMain), darknet.network_height(self.netMain))) print("Starting the YOLO loop...") # Create an image we reuse for each detect self.darknet_image = darknet.make_image( darknet.network_width(self.netMain), darknet.network_height(self.netMain), 3) self.video = cv2.VideoCapture(0) self.video.set(3, 1280) self.video.set(4, 720)
def __init__(self): configPath = "./yolov4-helmet-detection.cfg" weightPath = "./yolov4-helmet-detection.weights" metaPath = "./yolov4-helmet-detection.data" self.netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 self.metaMain = darknet.load_meta(metaPath.encode("ascii")) # flask/CUDA issue: https://github.com/AlexeyAB/darknet/issues/6844 # use lock to fix multithread issue self.lock = threading.Lock()
def initialize_network(self, cfg_path, weights_path, meta_path): if not os.path.exists(cfg_path): raise ValueError("Invalid config path `" + os.path.abspath(cfg_path) + "`") else: self.cfg_path = cfg_path if not os.path.exists(weights_path): raise ValueError("Invalid weight path `" + os.path.abspath(weights_path) + "`") else: self.weights_path = weights_path if not os.path.exists(meta_path): raise ValueError("Invalid data file path `" + os.path.abspath(meta_path) + "`") else: self.meta_path = meta_path if self.netMain is None: self.netMain = darknet.load_net_custom( self.cfg_path.encode("ascii"), self.weights_path.encode("ascii"), 0, 1) # batch size = 1 if self.metaMain is None: self.metaMain = darknet.load_meta(self.meta_path.encode("ascii")) self.net_width = darknet.network_width(self.netMain) self.net_height = darknet.network_height(self.netMain) #self.darknet_image = darknet.make_image(self.net_width, self.net_height, self.net_channels) self.darknet_image = darknet.make_image(640, 480, 3) #Changed if self.altNames is None: try: with open(self.meta_path) 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") self.altNames = [x.strip() for x in namesList] except TypeError: pass except Exception: pass #Initializing ros Node rospy.init_node('listener', anonymous=True)
def init_darknet(self): config_path = "marvel_cfg/yolov3-marvel.cfg" weight_path = "marvel_weights/yolov3-marvel_final.weights" meta_path = "marvel_cfg/marvel.data" self.darknet_net = darknet.load_net_custom(config_path.encode("ascii"), weight_path.encode("ascii"), 0, 1) self.darknet_net_w = darknet.network_width(self.darknet_net) self.darknet_net_h = darknet.network_height(self.darknet_net) self.darknet_meta = darknet.load_meta(meta_path.encode("ascii")) self.darknet_img = darknet.make_image(self.darknet_net_w, self.darknet_net_h, 3)
def set_darknet(self): """Si weight_influence_test, teste tous les yolov3-tiny_3l_22_xxxxxxx.weights du dossier backup free_network = lib.api_free_network free_network.argtypes = [c_void_p] adapté à ce script: free_network = darknet.lib.api_free_network free_network.argtypes = [c_void_p] """ configPath = self.CONF['play_letters']['configpath'] if not self.test: weightPath = self.CONF['play_letters']['weightpath'] else: weightPath = self.weights metaPath = self.CONF['play_letters']['metapath'] self.netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) self.metaMain = darknet.load_meta(metaPath.encode("ascii")) with open(metaPath) as metaFH: metaContents = metaFH.read() 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") self.altNames = [x.strip() for x in namesList] except TypeError: print("Erreur self.altNames") if self.gpu: self.free_network = darknet.lib.api_free_network # Create an image we reuse for each detect self.darknet_image = darknet.make_image(\ darknet.network_width(self.netMain), darknet.network_height(self.netMain), 3)
def performDetect(darknet_path, configPath, weightPath, metaPath, imagePath, thresh=0.25): sys.path.append(darknet_path) import darknet global metaMain, netMain, altNames 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) + "`") # 默认batch为1 netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) metaMain = darknet.load_meta(metaPath.encode("ascii")) if altNames is None: 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 as e: print(e) # 判断图片路径是否存在 if not os.path.exists(imagePath): raise ValueError("Invalid image path `" + os.path.abspath(imagePath) + "`") # 开始预测 detections = darknet.detect(netMain, metaMain, imagePath.encode("ascii"), thresh) return detections
def validateYOLO(configPath, weightPath, metaPath): """ Validates the YOLO paths and throws errors if error exists Parameters ---------------- configPath: str Path to the config to evaluate. Raises ValueError if not found weightPath: str Path to the weight to evaluate. Raises ValueError if not found weightPath: str Path to the meta to evaluate. Raises ValueError if not found """ global metaMain, netMain, altNames 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 = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if metaMain is None: metaMain = darknet.load_meta(metaPath.encode("ascii")) if altNames is None: 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
def Detector(): global metaMain, netMain, altNames configPath = "./yolov3.cfg" weightPath = "./yolov3.weights" metaPath = "./data/obj.data" 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 = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if metaMain is None: metaMain = darknet.load_meta(metaPath.encode("ascii")) if altNames is None: 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 darknet_image = darknet.make_image(darknet.network_width(netMain), darknet.network_height(netMain), 3) for i in range(0, len(list_img)): path = './data/dataset/' + list_img[i] # detections = (darknet.performDetect(path, 0.25, configPath, weightPath, metaPath, False, False)) detections = darknet.detect(netMain, metaMain, path.encode("ascii"), 0.25) SuperResolution(list_img[i], preprocess(path, detections))
def __init__(self): self.definer = [ 'u-turn', 'crosswalk', 'narrow', 'tracking', 'parking', 'red', 'green' ] # Define all traffic signs used self.sign = { key: [0, 0] for key in self.definer } # Initialize a dict for each type to store a counter and precision checker # YOLO config global metaMain, netMain, altNames configPath = "pams19/yolov3.cfg" weightPath = "backup/backup-pams/yolov3_final.weights" metaPath = "pams19/obj.data" 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 = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if metaMain is None: metaMain = darknet.load_meta(metaPath.encode("ascii")) if altNames is None: 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
def YOLO(): #global pipeline, config #pipeline = rs.pipeline() #config = rs.config() #config.enable_stream(rs.stream.color, 1280, 720, rs.format.bgr8, 30) #pipeline.start(config) global metaMain, netMain, altNames configPath = "./cfg/yolov3-obj.cfg" weightPath = "yolo-obj_last.weights" metaPath = "./data/obj.data" 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 = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if metaMain is None: metaMain = darknet.load_meta(metaPath.encode("ascii")) if altNames is None: 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 global darknet_image darknet_image = darknet.make_image(darknet.network_width(netMain), darknet.network_height(netMain), 3)
def InitialiseYOLO(): print('YOLO Init') global metaMain, netMain, altNames, darknet_image #configPath = "./cfg/yolov4.cfg" configPath = "/var/darknet/cfg/yolov3.cfg" #weightPath = "./yolov4.weights" weightPath = "/var/darknet/cfg/yolov3.weights" #metaPath = "./cfg/coco.data" metaPath = "/var/darknet/cfg/coco.data" 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 = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if metaMain is None: metaMain = darknet.load_meta(metaPath.encode("ascii")) if altNames is None: 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 darknet_image = darknet.make_image(darknet.network_width(netMain), darknet.network_height(netMain), 3) return netMain, metaMain
def load_model(darknet_path, configPath, weightPath, metaPath, thresh=0.25): sys.path.append(darknet_path) import darknet global metaMain, netMain, altNames 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) + "`") # 默认batch为1 netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) metaMain = darknet.load_meta(metaPath.encode("ascii")) return netMain, metaMain, thresh, darknet_path
def __init__(self, configPath="cfg/yolo-obj.cfg", weightPath="weights/yolo-obj_final.weights", metaPath="cfg/obj.data", gpu_id=1): self.metaMain, self.netMain, self.altNames, self.dark = None, None, None, darknet # self.logger = setup_logger(log_level=logging.CRITICAL) if HAS_GPU: set_gpu(gpu_id) 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 self.netMain is None: self.netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if self.metaMain is None: self.metaMain = darknet.load_meta(metaPath.encode("ascii")) if self.altNames is None: 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") self.altNames = [x.strip() for x in namesList] except TypeError: pass except Exception: pass self.size = (self.dark.network_width(self.netMain), self.dark.network_height(self.netMain)) self._seconds = 0
def load_model(metaMain, netMain, altNames, version): if version == 1: configPath = "./cfg/yolov4.cfg" else: configPath = "./cfg/small_yolov4.cfg" weightPath = "./weights/yolov4.weights" metaPath = "./cfg/coco.data" 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 = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if metaMain is None: metaMain = darknet.load_meta(metaPath.encode("ascii")) if altNames is None: 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 # Create an image we reuse for each detect darknet_image = darknet.make_image(darknet.network_width(netMain), darknet.network_height(netMain), 3) return darknet_image, metaMain, netMain, altNames
def detect_people(image): inputi = image config_file = 'cfg/yolov4.cfg' weights_file = 'yolov4.weights' data_file = 'data/coco.data' height, width, _ = image.shape network = darknet.load_net_custom(config_file.encode('ascii'), weights_file.encode('ascii'), 0, 1) meta = darknet.load_meta(data_file.encode('ascii')) darknet_image = darknet.make_image(darknet.network_width(network), darknet.network_height(network), 3) image = cv2.resize( image, (darknet.network_width(network), darknet.network_height(network)), interpolation=cv2.INTER_LINEAR) wi = darknet.network_width(network) he = darknet.network_height(network) darknet.copy_image_from_bytes(darknet_image, image.tobytes()) results = darknet.detect_image(network, meta, darknet_image, thresh=0.25) for result in results: item, confidence, bounding_box = result item = item.decode('utf-8') if item == 'person': print(f'{item} {confidence}') result = convert(bounding_box[0], bounding_box[1], bounding_box[2], bounding_box[3]) # xc + rx(xo -xc) rx = width / wi ry = height / he xmin = result[0] * rx ymin = result[1] * ry xmax = result[2] * rx ymax = result[3] * ry cv2.rectangle(inputi, (int(xmin), int(ymin)), (int(xmax), int(ymax)), (0, 255, 0), 1) cv2.putText(inputi, item, (int(xmin), int(ymin) - 5), cv2.FONT_HERSHEY_SIMPLEX, .4, (0, 255, 0), 1) result = cv2.cvtColor(inputi, cv2.COLOR_BGR2RGB) return result
def __init__(self, configPath="", weightPath="", classPath=""): 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(classPath): raise ValueError("Invalid classes file path `" + os.path.abspath(classPath) + "`") self.net = dk.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) self.class_names = YOLO.getClass(classPath) self.darknet_image = dk.make_image(dk.network_width(self.net), dk.network_height(self.net), 3) self.thresh = 0.5 self.colors = self.getColors()
def __init__(self): self.avm_img_sub = rospy.Subscriber("avm_usb_cam/image_raw", Image, self.image_callback) self.parking_cand_pub = rospy.Publisher('/parking_cands', PoseArray, queue_size=1) self.metaMain = None self.netMain = None self.altNames = None self.image = None configPath = "./yolo-obj_onlyFree.cfg" weightPath = "./yolo-obj_parking.weights" #ms: loading the weight file # weightPath = "./yolo-obj_low_dimension.weights"#ms: the size of input has to be (224,224) metaPath = "./obj.data" if self.netMain is None: self.netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if self.metaMain is None: self.metaMain = darknet.load_meta(metaPath.encode("ascii")) if self.altNames is None: 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") self.altNames = [x.strip() for x in namesList] except TypeError: pass except Exception: pass self.darknet_image = darknet.make_image( darknet.network_width(self.netMain), darknet.network_height(self.netMain), 3)
def __init__(self, metaPath, configPath, weightPath, namesPath, gpu_id=2): ''' :param metaPath: ***.data 存储各种参数 :param configPath: ***.cfg 网络结构文件 :param weightPath: ***.weights yolo的权重 :param namesPath: ***.data中的names路径,这里是便于读取使用 :param gpu_id: gpu id ''' # 设置gpu darknet.set_gpu(gpu_id) # 网络 self.netMain = darknet.load_net_custom(configPath.encode("ascii"), weightPath.encode("ascii"), 0, 1) # batch=1 # 各种参数 self.metaMain = darknet.load_meta(metaPath.encode("ascii")) # 读取标签类别名称列表 self.names = self.read_names(namesPath) # 每类颜色肯定一致,但是每次执行不一定都一样 self.colors = self.color()
def YOLO(): global metaMain, netMain, altNames configPath = "./cfg/yolov3.cfg" weightPath = "./yolov3.weights" metaPath = "./cfg/coco.data" 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 = darknet.load_net_custom(configPath.encode( "ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1 if metaMain is None: metaMain = darknet.load_meta(metaPath.encode("ascii")) if altNames is None: 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 #cap = cv2.VideoCapture(0) cap = cv2.VideoCapture("test.mp4") cap.set(3, 1280) cap.set(4, 720) out = cv2.VideoWriter( "output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 10.0, (darknet.network_width(netMain), darknet.network_height(netMain))) print("Starting the YOLO loop...") # Create an image we reuse for each detect darknet_image = darknet.make_image(darknet.network_width(netMain), darknet.network_height(netMain),3) while True: prev_time = time.time() ret, frame_read = cap.read() frame_rgb = cv2.cvtColor(frame_read, cv2.COLOR_BGR2RGB) frame_resized = cv2.resize(frame_rgb, (darknet.network_width(netMain), darknet.network_height(netMain)), interpolation=cv2.INTER_LINEAR) darknet.copy_image_from_bytes(darknet_image,frame_resized.tobytes()) detections = darknet.detect_image(netMain, metaMain, darknet_image, thresh=0.25) image = cvDrawBoxes(detections, frame_resized) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) print(1/(time.time()-prev_time)) cv2.imshow('Demo', image) cv2.waitKey(3) cap.release() out.release()