image_reader.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # -------------------------------------------------------------------------
  2. # Written by Jilan Xu
  3. # -------------------------------------------------------------------------
  4. import io
  5. from PIL import Image
  6. import logging
  7. import kestrel as ks
  8. from PIL import ImageFile
  9. ImageFile.LOAD_TRUNCATED_IMAGES = True
  10. logger = logging.getLogger('global')
  11. def pil_loader(img_bytes, filepath):
  12. buff = io.BytesIO(img_bytes)
  13. try:
  14. with Image.open(buff) as img:
  15. img = img.convert('RGB')
  16. except IOError:
  17. logger.info('Failed in loading {}'.format(filepath))
  18. return img
  19. def kestrel_loader(img_bytes, filepath):
  20. input_frame = ks.Frame()
  21. try:
  22. image_data = img_bytes.tobytes()
  23. input_frame.create_from_mem(image_data, len(image_data))
  24. if input_frame.frame_type != ks.KESTREL_VIDEO_RGB:
  25. input_frame = input_frame.cvt_color(ks.KESTREL_VIDEO_RGB)
  26. if ks.Device().mem_type() == ks.KESTREL_MEM_DEVICE:
  27. input_frame = input_frame.upload()
  28. except IOError:
  29. logger.info('Failed in loading {}'.format(filepath))
  30. return [input_frame]
  31. def build_image_reader(reader_type):
  32. if reader_type == 'pil':
  33. return pil_loader
  34. elif reader_type == 'kestrel':
  35. return kestrel_loader
  36. else:
  37. raise NotImplementedError