image.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. img_b64 = base64.b64encode(img_data).decode("utf-8")
  28. return img_b64
  29. def img_arr_to_data(img_arr):
  30. img_pil = PIL.Image.fromarray(img_arr)
  31. img_data = img_pil_to_data(img_pil)
  32. return img_data
  33. def img_data_to_png_data(img_data):
  34. with io.BytesIO() as f:
  35. f.write(img_data)
  36. img = PIL.Image.open(f)
  37. with io.BytesIO() as f:
  38. img.save(f, "PNG")
  39. f.seek(0)
  40. return f.read()
  41. def img_qt_to_arr(img_qt):
  42. w, h, d = img_qt.size().width(), img_qt.size().height(), img_qt.depth()
  43. bytes_ = img_qt.bits().asstring(w * h * d // 8)
  44. img_arr = np.frombuffer(bytes_, dtype=np.uint8).reshape((h, w, d // 8))
  45. return img_arr
  46. def apply_exif_orientation(image):
  47. try:
  48. exif = image._getexif()
  49. except AttributeError:
  50. exif = None
  51. if exif is None:
  52. return image
  53. exif = {PIL.ExifTags.TAGS[k]: v for k, v in exif.items() if k in PIL.ExifTags.TAGS}
  54. orientation = exif.get("Orientation", None)
  55. if orientation == 1:
  56. # do nothing
  57. return image
  58. elif orientation == 2:
  59. # left-to-right mirror
  60. return PIL.ImageOps.mirror(image)
  61. elif orientation == 3:
  62. # rotate 180
  63. return image.transpose(PIL.Image.ROTATE_180)
  64. elif orientation == 4:
  65. # top-to-bottom mirror
  66. return PIL.ImageOps.flip(image)
  67. elif orientation == 5:
  68. # top-to-left mirror
  69. return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_270))
  70. elif orientation == 6:
  71. # rotate 270
  72. return image.transpose(PIL.Image.ROTATE_270)
  73. elif orientation == 7:
  74. # top-to-right mirror
  75. return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_90))
  76. elif orientation == 8:
  77. # rotate 90
  78. return image.transpose(PIL.Image.ROTATE_90)
  79. else:
  80. return image