image.py 2.6 KB

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