# 解析XML文件 with open(src_xml_path) as fid: xml_str = fid.read().encode('utf-8') xml = etree.fromstring(xml_str) data = parse_xml_to_dict(xml)['annotation']
if 'object' in data.keys(): for obj in data['object']: if obj['name'] == class_sub: copy(src_img_path, dst_img_path) copy(src_xml_path, dst_xml_path) break
# XML解析函数 def parse_xml_to_dict(xml): """将XML文件解析成字典形式 Args: xml: 使用lxml.etree解析的XML树 Returns: 包含XML内容的Python字典 """ if len(xml) == 0: return {xml.tag: xml.text} result = {} for child in xml: child_result = parse_xml_to_dict(child) if child.tag != 'object': result[child.tag] = child_result[child.tag] else: if child.tag not in result: result[child.tag] = [] result[child.tag].append(child_result[child.tag]) return {xml.tag: result} ```
for label, dets in enumerate(detections): if label != target_idx: continue for bbox in dets: score = bbox[-1] if score > score_thresh: x0, y0, x1, y1 = [int(i) for i in bbox[:4]] all_box.append([label, x0, y0, x1, y1, score]) ```
### 3. 可视化特定类别的标注框
为了更直观地展示特定类别的标注框,可以在图像上叠加这些框。以下是代码示例:
```python import cv2 as cv
for file in os.listdir(os.path.join(origin_folder, 'xml_tmp')): file_path = os.path.join(origin_folder, 'xml_tmp', file) img_path = os.path.join(origin_folder, 'img_tmp', file.replace('xml', 'jpg')) img = cv.imread(img_path)
with open(file_path) as fid: xml_str = fid.read().encode('utf-8') xml = etree.fromstring(xml_str) data = parse_xml_to_dict(xml)['annotation']
if 'object' in data.keys(): for obj in data['object']: if obj['name'] == class_sub: xmin = int(float(obj['bndbox']['xmin'])) xmax = int(float(obj['bndbox']['xmax'])) ymin = int(float(obj['bndbox']['ymin'])) ymax = int(float(obj['bndbox']['ymax'])) cv.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 0, 255), 1)