style_samplers.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Copyright (c) 2020 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. import random
  16. import cv2
  17. class DatasetSampler(object):
  18. def __init__(self, config):
  19. self.image_home = config["StyleSampler"]["image_home"]
  20. label_file = config["StyleSampler"]["label_file"]
  21. self.dataset_with_label = config["StyleSampler"]["with_label"]
  22. self.height = config["Global"]["image_height"]
  23. self.index = 0
  24. with open(label_file, "r") as f:
  25. label_raw = f.read()
  26. self.path_label_list = label_raw.split("\n")[:-1]
  27. assert len(self.path_label_list) > 0
  28. random.shuffle(self.path_label_list)
  29. def sample(self):
  30. if self.index >= len(self.path_label_list):
  31. random.shuffle(self.path_label_list)
  32. self.index = 0
  33. if self.dataset_with_label:
  34. path_label = self.path_label_list[self.index]
  35. rel_image_path, label = path_label.split('\t')
  36. else:
  37. rel_image_path = self.path_label_list[self.index]
  38. label = None
  39. img_path = "{}/{}".format(self.image_home, rel_image_path)
  40. image = cv2.imread(img_path)
  41. origin_height = image.shape[0]
  42. ratio = self.height / origin_height
  43. width = int(image.shape[1] * ratio)
  44. height = int(image.shape[0] * ratio)
  45. image = cv2.resize(image, (width, height))
  46. self.index += 1
  47. if label:
  48. return {"image": image, "label": label}
  49. else:
  50. return {"image": image}
  51. def duplicate_image(image, width):
  52. image_width = image.shape[1]
  53. dup_num = width // image_width + 1
  54. image = np.tile(image, reps=[1, dup_num, 1])
  55. cropped_image = image[:, :width, :]
  56. return cropped_image