mmseg_handler.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import base64
  3. import os
  4. import cv2
  5. import mmcv
  6. import torch
  7. from mmengine.model.utils import revert_sync_batchnorm
  8. from ts.torch_handler.base_handler import BaseHandler
  9. from mmseg.apis import inference_model, init_model
  10. class MMsegHandler(BaseHandler):
  11. def initialize(self, context):
  12. properties = context.system_properties
  13. self.map_location = 'cuda' if torch.cuda.is_available() else 'cpu'
  14. self.device = torch.device(self.map_location + ':' +
  15. str(properties.get('gpu_id')) if torch.cuda.
  16. is_available() else self.map_location)
  17. self.manifest = context.manifest
  18. model_dir = properties.get('model_dir')
  19. serialized_file = self.manifest['model']['serializedFile']
  20. checkpoint = os.path.join(model_dir, serialized_file)
  21. self.config_file = os.path.join(model_dir, 'config.py')
  22. self.model = init_model(self.config_file, checkpoint, self.device)
  23. self.model = revert_sync_batchnorm(self.model)
  24. self.initialized = True
  25. def preprocess(self, data):
  26. images = []
  27. for row in data:
  28. image = row.get('data') or row.get('body')
  29. if isinstance(image, str):
  30. image = base64.b64decode(image)
  31. image = mmcv.imfrombytes(image)
  32. images.append(image)
  33. return images
  34. def inference(self, data, *args, **kwargs):
  35. results = [inference_model(self.model, img) for img in data]
  36. return results
  37. def postprocess(self, data):
  38. output = []
  39. for image_result in data:
  40. _, buffer = cv2.imencode('.png', image_result[0].astype('uint8'))
  41. content = buffer.tobytes()
  42. output.append(content)
  43. return output