image_classification.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 BasicPredictor
  21. class ClasPredictor(BasicPredictor):
  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(
  31. format="RGB", batch_size=self.kwargs.get("batch_size", 1)
  32. )
  33. for cfg in self.config["PreProcess"]["transform_ops"]:
  34. tf_key = list(cfg.keys())[0]
  35. func = self._FUNC_MAP.get(tf_key)
  36. args = cfg.get(tf_key, {})
  37. op = func(self, **args) if args else func(self)
  38. ops[tf_key] = op
  39. predictor = ImagePredictor(
  40. model_dir=self.model_dir,
  41. model_prefix=self.MODEL_FILE_PREFIX,
  42. option=self.pp_option,
  43. )
  44. ops["predictor"] = predictor
  45. post_processes = self.config["PostProcess"]
  46. for key in post_processes:
  47. func = self._FUNC_MAP.get(key)
  48. args = post_processes.get(key, {})
  49. op = func(self, **args) if args else func(self)
  50. ops[key] = op
  51. return ops
  52. @register("ResizeImage")
  53. # TODO(gaotingquan): backend & interpolation
  54. def build_resize(
  55. self, resize_short=None, size=None, backend="cv2", interpolation="LINEAR"
  56. ):
  57. assert resize_short or size
  58. if resize_short:
  59. op = ResizeByShort(
  60. target_short_edge=resize_short, size_divisor=None, interp="LINEAR"
  61. )
  62. else:
  63. op = Resize(target_size=size)
  64. return op
  65. @register("CropImage")
  66. def build_crop(self, size=224):
  67. return Crop(crop_size=size)
  68. @register("NormalizeImage")
  69. def build_normalize(
  70. self,
  71. mean=[0.485, 0.456, 0.406],
  72. std=[0.229, 0.224, 0.225],
  73. scale=1 / 255,
  74. order="",
  75. channel_num=3,
  76. ):
  77. assert channel_num == 3
  78. assert order == ""
  79. return Normalize(mean=mean, std=std)
  80. @register("ToCHWImage")
  81. def build_to_chw(self):
  82. return ToCHWImage()
  83. @register("Topk")
  84. def build_topk(self, topk, label_list=None):
  85. return Topk(topk=int(topk), class_ids=label_list)
  86. @register("MultiLabelThreshOutput")
  87. def build_threshoutput(self, threshold, label_list=None):
  88. return MultiLabelThreshOutput(threshold=float(threshold), class_ids=label_list)
  89. def _pack_res(self, single):
  90. keys = ["img_path", "class_ids", "scores"]
  91. if "label_names" in single:
  92. keys.append("label_names")
  93. return TopkResult({key: single[key] for key in keys})