Git Product home page Git Product logo

Comments (4)

cch-meiple avatar cch-meiple commented on July 27, 2024 2

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.

likyoo avatar likyoo commented on July 27, 2024

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.

boxbox-0427 avatar boxbox-0427 commented on July 27, 2024

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.

likyoo avatar likyoo commented on July 27, 2024

Hi~, Open-CD supports inference api now 😃 ! see here

from open-cd.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.