解决pycocotools的安装问题:No module named pycocotools

一、问题解决过程

为了实现目标检测模型fast_rcnn,准备使用coco数据集进行模型的训练,这里需要导入coco数据集,并且进行数据集处理。

import torch
import torchvision
import torch.utils.data
from pycocotools.coco import COCO


def convert_to_coco_api(ds):
    coco_ds = COCO()
    # annotation IDs need to start at 1, not 0
    ann_id = 1
    dataset = {'images': [], 'categories': [], 'annotations': []}
    categories = set()
    for img_idx in range(len(ds)):
        # find better way to get target
        hw, targets = ds.coco_index(img_idx)
        image_id = targets["image_id"].item()
        img_dict = {}
        img_dict['id'] = image_id
        img_dict['height'] = hw[0]
        img_dict['width'] = hw[1]
        dataset['images'].append(img_dict)
        bboxes = targets["boxes"]
        bboxes[:, 2:] -= bboxes[:, :2]
        bboxes = bboxes.tolist()
        labels = targets['labels'].tolist()
        areas = targets['area'].tolist()
        iscrowd = targets['iscrowd'].tolist()
        num_objs = len(bboxes)
        for i in range(num_objs):
            ann = {}
            ann['image_id'] = image_id
            ann['bbox'] = bboxes[i]
            ann['category_id'] = labels[i]
            categories.add(labels[i])
            ann['area'] = areas[i]
            ann['iscrowd'] = iscrowd[i]
            ann['id'] = ann_id
            dataset['annotations'].append(ann)
            ann_id += 1
    dataset['categories'] = [{'id': i} for i in sorted(categories)]
    coco_ds.dataset = dataset
    coco_ds.createIndex()
    return coco_ds


def get_coco_api_from_dataset(dataset):
    for _ in range(10):
        if isinstance(dataset, torchvision.datasets.CocoDetection):
            break
        if isinstance(dataset, torch.utils.data.Subset):
            dataset = dataset.dataset
    if isinstance(dataset, torchvision.datasets.CocoDetection):
        return dataset.coco
    return convert_to_coco_api(dataset)

运行出现 在这里插入图片描述
可以得出当前环境没有 pycocotools 模块 故需要

pip install pycocotools

------报错了-------
解决pycocotools的安装问题:No module named pycocotools_第1张图片
然后查询有一种从gitee上下载的方式

pip install git+https://gitee.com/pursuit_zhangyu/cocoapi.git#subdirectory=PythonAPI

------报错了-------
解决pycocotools的安装问题:No module named pycocotools_第2张图片
上面报错信息发现是缺少Cython模块,那就下载Cython模块

pip install Cython

然后在进行上一步的操作

pip install git+https://gitee.com/pursuit_zhangyu/cocoapi.git#subdirectory=PythonAPI

------还是不行-------

最后发现linux下载是上面的操作,因为我是windous应该按照下面的指令

pip install pycocotools-windows

解决pycocotools的安装问题:No module named pycocotools_第3张图片
成功!!

解决pycocotools的安装问题:No module named pycocotools_第4张图片

你可能感兴趣的:(目标检测,深度学习,计算机视觉)