image_classification.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import numpy as np
  15. from ...utils.func_register import FuncRegister
  16. from ...modules.image_classification.model_list import MODELS
  17. from ..components import *
  18. from ..results import TopkResult
  19. from ..utils.process_hook import batchable_method
  20. from .base import BasePredictor
  21. class ClasPredictor(BasePredictor):
  22. entities = MODELS
  23. _FUNC_MAP = {}
  24. register = FuncRegister(_FUNC_MAP)
  25. def _check_args(self, kwargs):
  26. assert set(kwargs.keys()).issubset(set(["batch_size"]))
  27. return kwargs
  28. def _build_components(self):
  29. ops = {}
  30. ops["ReadImage"] = ReadImage(batch_size=self.kwargs.get("batch_size", 1))
  31. for cfg in self.config["PreProcess"]["transform_ops"]:
  32. tf_key = list(cfg.keys())[0]
  33. func = self._FUNC_MAP.get(tf_key)
  34. args = cfg.get(tf_key, {})
  35. op = func(self, **args) if args else func(self)
  36. ops[tf_key] = op
  37. predictor = ImagePredictor(
  38. model_dir=self.model_dir,
  39. model_prefix=self.MODEL_FILE_PREFIX,
  40. option=self.pp_option,
  41. )
  42. ops["predictor"] = predictor
  43. post_processes = self.config["PostProcess"]
  44. for key in post_processes:
  45. func = self._FUNC_MAP.get(key)
  46. args = post_processes.get(key, {})
  47. op = func(self, **args) if args else func(self)
  48. ops[key] = op
  49. return ops
  50. @register("ResizeImage")
  51. # TODO(gaotingquan): backend & interpolation
  52. def build_resize(
  53. self, resize_short=None, size=None, backend="cv2", interpolation="LINEAR"
  54. ):
  55. assert resize_short or size
  56. if resize_short:
  57. op = ResizeByShort(
  58. target_short_edge=resize_short, size_divisor=None, interp="LINEAR"
  59. )
  60. else:
  61. op = Resize(target_size=size)
  62. return op
  63. @register("CropImage")
  64. def build_crop(self, size=224):
  65. return Crop(crop_size=size)
  66. @register("NormalizeImage")
  67. def build_normalize(
  68. self,
  69. mean=[0.485, 0.456, 0.406],
  70. std=[0.229, 0.224, 0.225],
  71. scale=1 / 255,
  72. order="",
  73. channel_num=3,
  74. ):
  75. assert channel_num == 3
  76. assert order == ""
  77. return Normalize(mean=mean, std=std)
  78. @register("ToCHWImage")
  79. def build_to_chw(self):
  80. return ToCHWImage()
  81. @register("Topk")
  82. def build_topk(self, topk, label_list=None):
  83. return Topk(topk=int(topk), class_ids=label_list)
  84. @register("MultiLabelThreshOutput")
  85. def build_threshoutput(self, threshold, label_list=None):
  86. return MultiLabelThreshOutput(threshold=float(threshold), class_ids=label_list)
  87. @batchable_method
  88. def _pack_res(self, data):
  89. keys = ["img_path", "class_ids", "scores"]
  90. if "label_names" in data:
  91. keys.append("label_names")
  92. return {"result": TopkResult({key: data[key] for key in keys})}