crop_image.cc 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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/utils/utils.h"
  15. namespace ultra_infer {
  16. namespace vision {
  17. namespace utils {
  18. bool CropImageByBox(Mat &src_im, Mat *dst_im, const std::vector<float> &box,
  19. std::vector<float> *center, std::vector<float> *scale,
  20. const float expandratio) {
  21. const cv::Mat *img = src_im.GetOpenCVMat();
  22. cv::Mat *crop_img = dst_im->GetOpenCVMat();
  23. int xmin = static_cast<int>(box[0]);
  24. int ymin = static_cast<int>(box[1]);
  25. int xmax = static_cast<int>(box[2]);
  26. int ymax = static_cast<int>(box[3]);
  27. float centerx = (xmin + xmax) / 2.0f;
  28. float centery = (ymin + ymax) / 2.0f;
  29. float half_h = (ymax - ymin) * (1 + expandratio) / 2.0f;
  30. float half_w = (xmax - xmin) * (1 + expandratio) / 2.0f;
  31. // adjust h or w to keep image ratio, expand the shorter edge
  32. if (half_h * 3 > half_w * 4) {
  33. half_w = half_h * 0.75;
  34. }
  35. int crop_xmin = std::max(0, static_cast<int>(centerx - half_w));
  36. int crop_ymin = std::max(0, static_cast<int>(centery - half_h));
  37. int crop_xmax = std::min(img->cols - 1, static_cast<int>(centerx + half_w));
  38. int crop_ymax = std::min(img->rows - 1, static_cast<int>(centery + half_h));
  39. crop_img->create(crop_ymax - crop_ymin, crop_xmax - crop_xmin, img->type());
  40. *crop_img =
  41. (*img)(cv::Range(crop_ymin, crop_ymax), cv::Range(crop_xmin, crop_xmax));
  42. center->clear();
  43. center->emplace_back((crop_xmin + crop_xmax) / 2.0f);
  44. center->emplace_back((crop_ymin + crop_ymax) / 2.0f);
  45. scale->clear();
  46. scale->emplace_back((crop_xmax - crop_xmin));
  47. scale->emplace_back((crop_ymax - crop_ymin));
  48. dst_im->SetWidth(crop_img->cols);
  49. dst_im->SetHeight(crop_img->rows);
  50. return true;
  51. }
  52. } // namespace utils
  53. } // namespace vision
  54. } // namespace ultra_infer