image.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. # MIT License
  2. # Copyright (c) Kentaro Wada
  3. import base64
  4. import io
  5. import numpy as np
  6. import PIL.ExifTags
  7. import PIL.Image
  8. import PIL.ImageOps
  9. def img_data_to_pil(img_data):
  10. f = io.BytesIO()
  11. f.write(img_data)
  12. img_pil = PIL.Image.open(f)
  13. return img_pil
  14. def img_data_to_arr(img_data):
  15. img_pil = img_data_to_pil(img_data)
  16. img_arr = np.array(img_pil)
  17. return img_arr
  18. def img_b64_to_arr(img_b64):
  19. img_data = base64.b64decode(img_b64)
  20. img_arr = img_data_to_arr(img_data)
  21. return img_arr
  22. def img_pil_to_data(img_pil):
  23. f = io.BytesIO()
  24. img_pil.save(f, format="PNG")
  25. img_data = f.getvalue()
  26. return img_data
  27. def img_arr_to_b64(img_arr):
  28. img_data = img_arr_to_data(img_arr)
  29. img_b64 = base64.b64encode(img_data).decode("utf-8")
  30. return img_b64
  31. def img_arr_to_data(img_arr):
  32. img_pil = PIL.Image.fromarray(img_arr)
  33. img_data = img_pil_to_data(img_pil)
  34. return img_data
  35. def img_data_to_png_data(img_data):
  36. with io.BytesIO() as f:
  37. f.write(img_data)
  38. img = PIL.Image.open(f)
  39. with io.BytesIO() as f:
  40. img.save(f, "PNG")
  41. f.seek(0)
  42. return f.read()
  43. def img_qt_to_arr(img_qt):
  44. w, h, d = img_qt.size().width(), img_qt.size().height(), img_qt.depth()
  45. bytes_ = img_qt.bits().asstring(w * h * d // 8)
  46. img_arr = np.frombuffer(bytes_, dtype=np.uint8).reshape((h, w, d // 8))
  47. return img_arr
  48. def apply_exif_orientation(image):
  49. try:
  50. exif = image._getexif()
  51. except AttributeError:
  52. exif = None
  53. if exif is None:
  54. return image
  55. exif = {PIL.ExifTags.TAGS[k]: v for k, v in exif.items() if k in PIL.ExifTags.TAGS}
  56. orientation = exif.get("Orientation", None)
  57. if orientation == 1:
  58. # do nothing
  59. return image
  60. elif orientation == 2:
  61. # left-to-right mirror
  62. return PIL.ImageOps.mirror(image)
  63. elif orientation == 3:
  64. # rotate 180
  65. return image.transpose(PIL.Image.ROTATE_180)
  66. elif orientation == 4:
  67. # top-to-bottom mirror
  68. return PIL.ImageOps.flip(image)
  69. elif orientation == 5:
  70. # top-to-left mirror
  71. return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_270))
  72. elif orientation == 6:
  73. # rotate 270
  74. return image.transpose(PIL.Image.ROTATE_270)
  75. elif orientation == 7:
  76. # top-to-right mirror
  77. return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_90))
  78. elif orientation == 8:
  79. # rotate 90
  80. return image.transpose(PIL.Image.ROTATE_90)
  81. else:
  82. return image