Comments (4)
Sorry for the delay in replying to you, you can try the following code.
import mmcv import torch from mmcv.parallel import collate, scatter from mmseg.apis import init_segmentor from mmseg.datasets.pipelines import Compose from opencd.models import * class LoadImage: """A simple pipeline to load image.""" def __call__(self, results): """Call function to load images into results. Args: results (dict): A result dict contains the file name of the image to be read. Returns: dict: ``results`` will be returned containing loaded image. """ results['filename'] = None results['ori_filename'] = None results['img'] = img results['img_shape'] = img[0].shape results['ori_shape'] = img[0].shape return results def inference_segmentor(model, imgs): """Inference image(s) with the segmentor. Args: model (nn.Module): The loaded segmentor. imgs (str/ndarray or list[str/ndarray]): Either image files or loaded images. Returns: (list[Tensor]): The segmentation result. """ cfg = model.cfg device = next(model.parameters()).device # model device # build the data pipeline test_pipeline = [LoadImage()] + cfg.data.test.pipeline[1:] test_pipeline = Compose(test_pipeline) # prepare data data = [] imgs = imgs if isinstance(imgs[0], list) else [imgs] for img in imgs: img_data = dict(img=img) img_data = test_pipeline(img_data) data.append(img_data) data = collate(data, samples_per_gpu=len(imgs)) if next(model.parameters()).is_cuda: # scatter to specified GPU data = scatter(data, [device])[0] else: data['img_metas'] = [i.data[0] for i in data['img_metas']] # forward the model with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) return result config_file = 'configs/changer/changer_ex_r18_512x512_40k_levircd.py' checkpoint_file = 'weights/ChangerEx_r18-512x512_40k_levircd_20221223_120511.pth' # build the model from a config file and a checkpoint file model = init_segmentor(config_file, checkpoint_file, device='cuda:0') # test a single image and show the results img1 = mmcv.imread('data/LEVIR-CD/test/A/test_1.png') img2 = mmcv.imread('data/LEVIR-CD/test/B/test_1.png') img = [img1, img2] result = inference_segmentor(model, img)
Thanks for your replying! I have already completed the
api
by myself, you can close this issue~.
The example code provided above uses an outdated function, so it is difficult to use it as is. Can you share the API you implemented?
from open-cd.
Sorry for the delay in replying to you, you can try the following code.
import mmcv
import torch
from mmcv.parallel import collate, scatter
from mmseg.apis import init_segmentor
from mmseg.datasets.pipelines import Compose
from opencd.models import *
class LoadImage:
"""A simple pipeline to load image."""
def __call__(self, results):
"""Call function to load images into results.
Args:
results (dict): A result dict contains the file name
of the image to be read.
Returns:
dict: ``results`` will be returned containing loaded image.
"""
results['filename'] = None
results['ori_filename'] = None
results['img'] = img
results['img_shape'] = img[0].shape
results['ori_shape'] = img[0].shape
return results
def inference_segmentor(model, imgs):
"""Inference image(s) with the segmentor.
Args:
model (nn.Module): The loaded segmentor.
imgs (str/ndarray or list[str/ndarray]): Either image files or loaded
images.
Returns:
(list[Tensor]): The segmentation result.
"""
cfg = model.cfg
device = next(model.parameters()).device # model device
# build the data pipeline
test_pipeline = [LoadImage()] + cfg.data.test.pipeline[1:]
test_pipeline = Compose(test_pipeline)
# prepare data
data = []
imgs = imgs if isinstance(imgs[0], list) else [imgs]
for img in imgs:
img_data = dict(img=img)
img_data = test_pipeline(img_data)
data.append(img_data)
data = collate(data, samples_per_gpu=len(imgs))
if next(model.parameters()).is_cuda:
# scatter to specified GPU
data = scatter(data, [device])[0]
else:
data['img_metas'] = [i.data[0] for i in data['img_metas']]
# forward the model
with torch.no_grad():
result = model(return_loss=False, rescale=True, **data)
return result
config_file = 'configs/changer/changer_ex_r18_512x512_40k_levircd.py'
checkpoint_file = 'weights/ChangerEx_r18-512x512_40k_levircd_20221223_120511.pth'
# build the model from a config file and a checkpoint file
model = init_segmentor(config_file, checkpoint_file, device='cuda:0')
# test a single image and show the results
img1 = mmcv.imread('data/LEVIR-CD/test/A/test_1.png')
img2 = mmcv.imread('data/LEVIR-CD/test/B/test_1.png')
img = [img1, img2]
result = inference_segmentor(model, img)
from open-cd.
Sorry for the delay in replying to you, you can try the following code.
import mmcv import torch from mmcv.parallel import collate, scatter from mmseg.apis import init_segmentor from mmseg.datasets.pipelines import Compose from opencd.models import * class LoadImage: """A simple pipeline to load image.""" def __call__(self, results): """Call function to load images into results. Args: results (dict): A result dict contains the file name of the image to be read. Returns: dict: ``results`` will be returned containing loaded image. """ results['filename'] = None results['ori_filename'] = None results['img'] = img results['img_shape'] = img[0].shape results['ori_shape'] = img[0].shape return results def inference_segmentor(model, imgs): """Inference image(s) with the segmentor. Args: model (nn.Module): The loaded segmentor. imgs (str/ndarray or list[str/ndarray]): Either image files or loaded images. Returns: (list[Tensor]): The segmentation result. """ cfg = model.cfg device = next(model.parameters()).device # model device # build the data pipeline test_pipeline = [LoadImage()] + cfg.data.test.pipeline[1:] test_pipeline = Compose(test_pipeline) # prepare data data = [] imgs = imgs if isinstance(imgs[0], list) else [imgs] for img in imgs: img_data = dict(img=img) img_data = test_pipeline(img_data) data.append(img_data) data = collate(data, samples_per_gpu=len(imgs)) if next(model.parameters()).is_cuda: # scatter to specified GPU data = scatter(data, [device])[0] else: data['img_metas'] = [i.data[0] for i in data['img_metas']] # forward the model with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) return result config_file = 'configs/changer/changer_ex_r18_512x512_40k_levircd.py' checkpoint_file = 'weights/ChangerEx_r18-512x512_40k_levircd_20221223_120511.pth' # build the model from a config file and a checkpoint file model = init_segmentor(config_file, checkpoint_file, device='cuda:0') # test a single image and show the results img1 = mmcv.imread('data/LEVIR-CD/test/A/test_1.png') img2 = mmcv.imread('data/LEVIR-CD/test/B/test_1.png') img = [img1, img2] result = inference_segmentor(model, img)
Thanks for your replying!
I have already completed the api
by myself, you can close this issue~.
from open-cd.
Hi~, Open-CD supports inference api now 😃 ! see here
from open-cd.
Related Issues (20)
- 作者大大您好,请问对图片的格式有要求吗,比如png,jpg,tiff,emf等是否可以 HOT 1
- 您好,有训练好的模型吗?比如基于configs/changer/changer_ex_r18_512x512_40k_levircd.py的? HOT 1
- Landsat-SCD; Folder structure HOT 2
- Using pretrained model weights in model training
- Training ChangeFormer from scratch. HOT 1
- Error occurs when I use the tools/export.py HOT 1
- 作者你好,ttp推理出现如下问题是什么原因,训练图片为1080p HOT 1
- 作者您好,请问网络在什么地方使用了AD模块?
- 模型导出 HOT 1
- 关于输出结果的问题 HOT 2
- 李老师您好!请问怎么定义多个辅助头? HOT 3
- 训练完的模型保存在哪里 HOT 1
- 有办法只输入一张图像,然后提取建筑吗,不做cd检测 HOT 2
- 学习率衰减为0
- TinyCDv2文章
- TinyCDv2文章
- SCD模型在SECOND数据集上训练,验证时,出现了NaN HOT 2
- inference HOT 4
- docker image
- train warning
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from open-cd.