本文主要是介绍yolov3spp配置文件解析函数parse_model_cfg(path:str),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
parse_model_cfg(path:str)(代码来源B站霹雳吧啦Wz)
def parse_model_cfg(path: str):# 检查文件是否存在if not path.endswith(".cfg") or not os.path.exists(path):raise FileNotFoundError("the cfg file not exist...")# 读取文件信息with open(path, "r") as f:lines = f.read().split("\n")# 去除空行和注释行lines = [x for x in lines if x and not x.startswith("#")]# 去除每行开头和结尾的空格符lines = [x.strip() for x in lines]mdefs = [] # module definitionsfor line in lines:if line.startswith("["): # this marks the start of a new blockmdefs.append({})mdefs[-1]["type"] = line[1:-1].strip() # 记录module类型# 如果是卷积模块,设置默认不使用BN(普通卷积层后面会重写成1,最后的预测层conv保持为0)if mdefs[-1]["type"] == "convolutional":mdefs[-1]["batch_normalize"] = 0else:key, val = line.split("=")key = key.strip()val = val.strip()if key == "anchors":# anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326val = val.replace(" ", "") # 将空格去除mdefs[-1][key] = np.array([float(x) for x in val.split(",")]).reshape((-1, 2)) # np anchorselif (key in ["from", "layers", "mask"]) or (key == "size" and "," in val):mdefs[-1][key] = [int(x) for x in val.split(",")]else:# TODO: .isnumeric() actually fails to get the float caseif val.isnumeric(): # return int or float 如果是数值的情况mdefs[-1][key] = int(val) if (int(val) - float(val)) == 0 else float(val)else:mdefs[-1][key] = val # return string 是字符的情况# check all fields are supportedsupported = ['type', 'batch_normalize', 'filters', 'size', 'stride', 'pad', 'activation', 'layers', 'groups','from', 'mask', 'anchors', 'classes', 'num', 'jitter', 'ignore_thresh', 'truth_thresh', 'random','stride_x', 'stride_y', 'weights_type', 'weights_normalization', 'scale_x_y', 'beta_nms', 'nms_kind','iou_loss', 'iou_normalizer', 'cls_normalizer', 'iou_thresh', 'probability']# 遍历检查每个模型的配置for x in mdefs[1:]: # 0对应net配置# 遍历每个配置字典中的key值for k in x:if k not in supported:raise ValueError("Unsupported fields:{} in cfg".format(k))return mdefs
通过上面的解析函数,将my_yolov3.cfg文件中的每一个结构解析成列表中的每一个元素(mdefs的格式是[{},{}…]),列表中的每一个元素是以字典的形式存在的(如下图)
字典中包含着网络每一个模块中的详细信息
加油!
这篇关于yolov3spp配置文件解析函数parse_model_cfg(path:str)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!