animegan.cc 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  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. #include "ultra_infer/vision/generation/contrib/animegan.h"
  15. #include "ultra_infer/function/functions.h"
  16. namespace ultra_infer {
  17. namespace vision {
  18. namespace generation {
  19. AnimeGAN::AnimeGAN(const std::string &model_file,
  20. const std::string &params_file,
  21. const RuntimeOption &custom_option,
  22. const ModelFormat &model_format) {
  23. valid_cpu_backends = {Backend::PDINFER};
  24. valid_gpu_backends = {Backend::PDINFER};
  25. runtime_option = custom_option;
  26. runtime_option.model_format = model_format;
  27. runtime_option.model_file = model_file;
  28. runtime_option.params_file = params_file;
  29. initialized = Initialize();
  30. }
  31. bool AnimeGAN::Initialize() {
  32. if (!InitRuntime()) {
  33. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  34. return false;
  35. }
  36. return true;
  37. }
  38. bool AnimeGAN::Predict(cv::Mat &img, cv::Mat *result) {
  39. std::vector<cv::Mat> results;
  40. if (!BatchPredict({img}, &results)) {
  41. return false;
  42. }
  43. *result = std::move(results[0]);
  44. return true;
  45. }
  46. bool AnimeGAN::BatchPredict(const std::vector<cv::Mat> &images,
  47. std::vector<cv::Mat> *results) {
  48. std::vector<FDMat> fd_images = WrapMat(images);
  49. std::vector<FDTensor> processed_data(1);
  50. if (!preprocessor_.Run(fd_images, &(processed_data))) {
  51. FDERROR << "Failed to preprocess input data while using model:"
  52. << ModelName() << "." << std::endl;
  53. return false;
  54. }
  55. std::vector<FDTensor> infer_result(1);
  56. processed_data[0].name = InputInfoOfRuntime(0).name;
  57. if (!Infer(processed_data, &infer_result)) {
  58. FDERROR << "Failed to inference by runtime." << std::endl;
  59. return false;
  60. }
  61. if (!postprocessor_.Run(infer_result, results)) {
  62. FDERROR << "Failed to postprocess while using model:" << ModelName() << "."
  63. << std::endl;
  64. return false;
  65. }
  66. return true;
  67. }
  68. } // namespace generation
  69. } // namespace vision
  70. } // namespace ultra_infer