def getPairs(id): label_root = kittiRoot + "instances/" + id image_root = label_root.replace('instances', 'images') image_list = make_dataset(image_root, suffix='.png') image_list.sort() label_list = make_dataset(label_root, suffix='.png') label_list.sort() imgs_list = [] # filter out images with no cars for ind, image_path in enumerate(image_list): label_path = label_list[ind] label = np.array(Image.open(label_path)) plt.imshow(label) plt.show() # for car #mask = np.logical_and(label >= label_id * 1000, label < (label_id + 1) * 1000) mask = np.logical_and(label > 0,label < 3) obj_ids = np.unique(label[mask]).tolist() if len(obj_ids) < 1: continue imgs_list.append('/'.join(image_path.split('/')[-2:])) return imgs_list
时间: 2024-02-26 10:55:14 浏览: 245
这段代码的作用是从指定路径下的标签图像和相应的原始图像中,筛选出含有车辆的图像,并返回这些图像的路径列表。具体实现过程如下:
1. 根据指定的参数 id,生成标签图像和原始图像的路径。
2. 分别读取标签图像和原始图像的路径列表,并按照文件名排序。
3. 构建一个空列表 imgs_list,用于存储含有车辆的图像路径。
4. 遍历原始图像路径列表,依次读取对应位置的标签图像和原始图像。
5. 对于每个原始图像,根据标签图像中像素的值,筛选出含有车辆的像素,并得到这些像素对应的车辆 ID。
6. 如果当前原始图像中不存在车辆,则直接跳过。
7. 否则,将当前原始图像的路径加入 imgs_list 中。
8. 最后,返回所有含有车辆的原始图像路径列表。
相关问题
def register_all_hrsid(root): from detectron2.data.datasets import register_coco_instances for name, split in product(["data"], ["1", "2", "3"]): # root/HRSID/annotations/train2017.json dataset_name = name + split dirname = os.path.join(root, name) json_file = os.path.join(dirname, "json") image_folder = os.path.join(dirname, "sliceData") # sliceData [.jpg , .tif] register_coco_instances(dataset_name, {}, os.path.join(json_file, f"{split}.json"), image_folder), _root = os.getenv("DETECTRON2_DATASETS", "/home/jtli/SAR/dataset") # /media/data 自己加的磁盘 register_all_coco_class(_root) register_all_ship(_root) register_all_voc(_root) register_all_air_sar1(_root) register_all_air_sar2(_root) register_all_hrsid(_root) 这段代码咋用Django封装API?
可以使用Django框架的RESTful API来封装这段代码,具体步骤如下:
1. 在Django项目中创建一个app,例如命名为“detectron2”。
2. 在该app中创建一个视图函数,用于接收API请求并执行代码。可以使用Django的request对象获取请求参数,使用response对象返回处理结果。示例代码如下:
```
from django.http import JsonResponse
import os
from itertools import product
from detectron2.data.datasets import register_coco_instances
def register_all_datasets(request):
root = os.getenv("DETECTRON2_DATASETS", "/home/jtli/SAR/dataset")
register_all_coco_class(root)
register_all_ship(root)
register_all_voc(root)
register_all_air_sar1(root)
register_all_air_sar2(root)
register_all_hrsid(root)
return JsonResponse({'status': 'success'})
```
3. 在Django项目中的urls.py文件中添加一个路由,将API请求映射到该视图函数。示例代码如下:
```
from django.urls import path
from .views import register_all_datasets
urlpatterns = [
path('register_all_datasets/', register_all_datasets, name='register_all_datasets'),
]
```
4. 将Django项目部署到服务器,启动Django服务。
5. 使用API测试工具(例如Postman)向服务器发送API请求,即可执行代码并返回处理结果。例如向http://localhost:8000/register_all_datasets/发送POST请求即可注册所有数据集。
class PrototypicalCalibrationBlock: def __init__(self, cfg): super().__init__() self.cfg = cfg self.device = torch.device(cfg.MODEL.DEVICE) self.alpha = self.cfg.TEST.PCB_ALPHA self.imagenet_model = self.build_model() self.dataloader = build_detection_test_loader(self.cfg, self.cfg.DATASETS.TRAIN[0]) self.roi_pooler = ROIPooler(output_size=(1, 1), scales=(1 / 32,), sampling_ratio=(0), pooler_type="ROIAlignV2") self.prototypes = self.build_prototypes() self.exclude_cls = self.clsid_filter() def build_model(self): logger.info("Loading ImageNet Pre-train Model from {}".format(self.cfg.TEST.PCB_MODELPATH)) if self.cfg.TEST.PCB_MODELTYPE == 'resnet': imagenet_model = resnet101() else: raise NotImplementedError state_dict = torch.load(self.cfg.TEST.PCB_MODELPATH) imagenet_model.load_state_dict(state_dict) imagenet_model = imagenet_model.to(self.device) imagenet_model.eval() return imagenet_model def build_prototypes(self): all_features, all_labels = [], [] for index in range(len(self.dataloader.dataset)): inputs = [self.dataloader.dataset[index]] assert len(inputs) == 1 # load support images and gt-boxes img = cv2.imread(inputs[0]['file_name']) # BGR img_h, img_w = img.shape[0], img.shape[1] ratio = img_h / inputs[0]['instances'].image_size[0] inputs[0]['instances'].gt_boxes.tensor = inputs[0]['instances'].gt_boxes.tensor * ratio boxes = [x["instances"].gt_boxes.to(self.device) for x in inputs] # extract roi features features = self.extract_roi_features(img, boxes) all_features.append(features.cpu().data) gt_classes = [x['instances'].gt_classes for x in inputs] all_labels.append(gt_classes[0].cpu().data)
这段代码是一个名为PrototypicalCalibrationBlock的类的定义,它包含了一些方法和属性。__init__方法接受一个cfg参数,用来初始化一些属性。其中包括设备类型、alpha值、预训练模型、数据加载器、RoI池化器和类别原型等。build_model方法用于加载ImageNet预训练模型,支持resnet101模型。build_prototypes方法用于提取RoI特征和类别标签,并将其存储为特征向量和类别原型。这个类的作用是在目标检测任务上进行模型校准。
阅读全文
相关推荐

















