python读写txt标注文件
时间: 2023-10-04 16:09:49 浏览: 93
python 读取、写入txt文件的示例
读取txt标注文件:
```python
# 打开文件
with open("标注文件.txt", "r") as f:
lines = f.readlines()
annotations = []
for line in lines:
# 分割每行
parts = line.split()
# 获取标注信息
annotation = {
"filename": parts[0],
"xmin": int(parts[1]),
"ymin": int(parts[2]),
"xmax": int(parts[3]),
"ymax": int(parts[4]),
"class": parts[5]
}
annotations.append(annotation)
```
写入txt标注文件:
```python
annotations = [
{
"filename": "image1.jpg",
"xmin": 10,
"ymin": 20,
"xmax": 100,
"ymax": 200,
"class": "car"
},
{
"filename": "image2.jpg",
"xmin": 50,
"ymin": 100,
"xmax": 200,
"ymax": 300,
"class": "person"
}
]
# 打开文件
with open("标注文件.txt", "w") as f:
for annotation in annotations:
# 构造每行内容
line = "{} {} {} {} {} {}\n".format(annotation["filename"], annotation["xmin"], annotation["ymin"], annotation["xmax"], annotation["ymax"], annotation["class"])
# 写入文件
f.write(line)
```
阅读全文