labelme使用代码
时间: 2025-05-03 12:40:01 浏览: 28
### LabelMe 使用代码示例与教程
#### 安装与配置
LabelMe 是一种用于图像标注的强大工具,其源码托管于多个平台。安装过程可以通过官方文档或社区分享的资源完成。例如,在 Linux 或其他支持 Python 的环境中,可以克隆项目的 Git 仓库并设置虚拟环境来运行该工具[^1]。
以下是基于 `LabelMe` 工具的一个基本安装流程:
```bash
# 克隆项目到本地
git clone https://gitcode.com/gh_mirrors/la/LabelMeAnnotationTool.git
# 创建并激活虚拟环境
python3 -m venv labelme-env
source labelme-env/bin/activate
# 进入目录并安装依赖项
cd LabelMeAnnotationTool
pip install -r requirements.txt
```
#### 启动与基础操作
通过命令行可以直接启动 LabelMe 并加载指定图片文件进行标注。假设当前工作目录下有一张名为 `apc2016_obj4.jpg` 的图片,则可通过以下方式打开它:
```bash
labelme apc2016_obj4.jpg
```
此命令会自动调用默认配置文件 `/home/hsh/.labelmerc` 来初始化程序参数[^2]。
#### 自定义标签集
为了提高效率和一致性,推荐预先定义好目标类别列表保存在一个文本文件中(如 `labels.txt`),每行代表一类对象名称。这样做的好处是可以减少手动输入错误以及加快后续数据处理速度。一个典型的例子可能看起来像这样[^3]:
```
__ignore__
_background_
dog
cat
bird
...
```
当再次执行 `labelme` 命令时,这些预设好的分类选项将会显示出来供用户快速选择应用至相应区域上。
#### 示例脚本展示如何批量导出JSON格式的数据为PNG掩模图象形式。
下面给出了一段简单的Python脚本来实现这一功能:
```python
import os.path as osp
from glob import glob
from labelme.utils import json_to_dataset
def main():
input_dir = 'input/jsons' # JSON files directory path.
output_dir = 'output/masks/' # Output masks directory.
if not osp.exists(output_dir):
os.makedirs(output_dir)
json_files = glob(osp.join(input_dir, '*.json'))
for json_file in json_files:
base_name = osp.splitext(osp.basename(json_file))[0]
out_img_path = osp.join(output_dir, f"{base_name}.png")
try:
img_arr = json_to_dataset(json_file)
cv2.imwrite(out_img_path, img_arr.astype('uint8') * 255)
print(f'Successfully converted {json_file} to mask.')
except Exception as e:
print(e)
if __name__ == '__main__':
main()
```
以上代码片段展示了如何利用 `labelme` 提供的功能模块将存储有标注信息的 `.json` 文件转换成像素级语义分割所需的二值化蒙版图像.
阅读全文
相关推荐

















