я вручную создал файл XML с желаемыми аннотациями/координатами пикселей набора данных изображения, поэтому я хочу проанализировать эти аннотации в один объект аннотации. Это мой XML-файл:
<?xml version='1.0' encoding='ISO-8859-1'?>
<?xml-stylesheet type='text/xsl' href='image_metadata_stylesheet.xsl'?>
<images>
<image file='pngCA43_01.jpg'>
<box top='673' left='92' width='875' height='508'/>
</image>
<image file='pngCA43_02.jpg'>
<box top='680' left='79' width='885' height='501'/>
</image>
<image file='pngCA43_03.jpg'>
<box top='677' left='86' width='876' height='501'/>
</image>
<image file='pngCA43_04.jpg'>
<box top='675' left='84' width='878' height='505'/>
</image>
<image file='pngCA43_05.jpg'>
<box top='658' left='87' width='879' height='511'/>
</image>
И так продолжается 1000 строк. Я хочу получить доступ к параметрам файла, сверху, слева, ширины и высоты в одном цикле. Это мой код Python:
import xml.etree.ElementTree as ET
class Annotation():
name = ""
top = 0
left = 0
width = 0
height = 0
def __init__(self, name, top, left, width, height):
self.name = name
self.top = top
self.left = left
self.width = width
self.height = height
annotations = []
root_xml = ET.parse("xml/idcard.xml").getroot()
i = 1
for type_tag in root_xml.iter("box"):
name = type_tag.get('file')
top = type_tag.get('top')
left = type_tag.get('left')
width = type_tag.get('width')
height = type_tag.get('height')
print(f'{i}. Name: {name} Top: {top} Left: {left} Width: {width} Height: {height}\n')
annotationObject = Annotation(name, top, left, width, height)
annotations.append(annotationObject)
i += 1
Этот фрагмент дает вывод:
1. Name: None Top: 673 Left: 92 Width: 875 Height: 508
2. Name: None Top: 680 Left: 79 Width: 885 Height: 501
3. Name: None Top: 677 Left: 86 Width: 876 Height: 501
4. Name: None Top: 675 Left: 84 Width: 878 Height: 505
5. Name: None Top: 658 Left: 87 Width: 879 Height: 511
«Файл» родительского узла (имя изображения) отсутствует, так как я перебираю узел блока. Однако, когда я заменяю root_xml.iter("box")
на root_xml.iter()
, выводится:
1. Name: None Top: None Left: None Width: None Height: None
2. Name: pngCA43_01.jpg Top: None Left: None Width: None Height: None
3. Name: None Top: 673 Left: 92 Width: 875 Height: 508
4. Name: pngCA43_02.jpg Top: None Left: None Width: None Height: None
5. Name: None Top: 680 Left: 79 Width: 885 Height: 501
6. Name: pngCA43_03.jpg Top: None Left: None Width: None Height: None
Я могу работать с этим, используя 2 разных цикла и получая имя из одного цикла и другие атрибуты из второго цикла, но я уверен, что должен быть способ сделать это, спасибо за помощь :) Берегите себя!
Обновлено: термины о XML могли быть неправильными, я впервые работаю с XML.
См. ниже (найдите все элементы изображения и используйте класс данных для аннотации)
import xml.etree.ElementTree as ET
from dataclasses import dataclass
XML = '''<images>
<image file='pngCA43_01.jpg'>
<box top='673' left='92' width='875' height='508'/>
</image>
<image file='pngCA43_02.jpg'>
<box top='680' left='79' width='885' height='501'/>
</image>
<image file='pngCA43_03.jpg'>
<box top='677' left='86' width='876' height='501'/>
</image>
<image file='pngCA43_04.jpg'>
<box top='675' left='84' width='878' height='505'/>
</image>
<image file='pngCA43_05.jpg'>
<box top='658' left='87' width='879' height='511'/>
</image>
</images>'''
@dataclass
class Annotation:
name: str
top: int
left: int
width: int
height: int
root = ET.fromstring(XML)
annotations = [Annotation(i.attrib['file'], int(i.find('box').attrib['top']), int(i.find('box').attrib['left']),
int(i.find('box').attrib['width'])
, int(i.find('box').attrib['height'])) for i in root.findall('.//image')]
print(annotations)
выход
[Annotation(name='pngCA43_01.jpg', top=673, left=92, width=875, height=508), Annotation(name='pngCA43_02.jpg', top=680, left=79, width=885, height=501), Annotation(name='pngCA43_03.jpg', top=677, left=86, width=876, height=501), Annotation(name='pngCA43_04.jpg', top=675, left=84, width=878, height=505), Annotation(name='pngCA43_05.jpg', top=658, left=87, width=879, height=511)]