image.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. # MIT License
  2. # Copyright (c) Kentaro Wada
  3. import base64
  4. import io
  5. import cv2
  6. import numpy as np
  7. import PIL.ExifTags
  8. import PIL.Image
  9. import PIL.ImageOps
  10. def img_data_to_pil(img_data):
  11. f = io.BytesIO()
  12. f.write(img_data)
  13. img_pil = PIL.Image.open(f)
  14. return img_pil
  15. def img_data_to_arr(img_data):
  16. img_pil = img_data_to_pil(img_data)
  17. img_arr = np.array(img_pil)
  18. return img_arr
  19. def img_b64_to_arr(img_b64):
  20. img_data = base64.b64decode(img_b64)
  21. img_arr = img_data_to_arr(img_data)
  22. return img_arr
  23. def img_pil_to_data(img_pil):
  24. f = io.BytesIO()
  25. img_pil.save(f, format="PNG")
  26. img_data = f.getvalue()
  27. return img_data
  28. def img_arr_to_b64(img_arr):
  29. img_data = img_arr_to_data(img_arr)
  30. img_b64 = base64.b64encode(img_data).decode("utf-8")
  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. img_arr=cv2.cvtColor(img_arr,cv2.COLOR_RGBA2GRAY)
  49. return img_arr
  50. def apply_exif_orientation(image):
  51. try:
  52. exif = image._getexif()
  53. except AttributeError:
  54. exif = None
  55. if exif is None:
  56. return image
  57. exif = {PIL.ExifTags.TAGS[k]: v for k, v in exif.items() if k in PIL.ExifTags.TAGS}
  58. orientation = exif.get("Orientation", None)
  59. if orientation == 1:
  60. # do nothing
  61. return image
  62. elif orientation == 2:
  63. # left-to-right mirror
  64. return PIL.ImageOps.mirror(image)
  65. elif orientation == 3:
  66. # rotate 180
  67. return image.transpose(PIL.Image.ROTATE_180)
  68. elif orientation == 4:
  69. # top-to-bottom mirror
  70. return PIL.ImageOps.flip(image)
  71. elif orientation == 5:
  72. # top-to-left mirror
  73. return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_270))
  74. elif orientation == 6:
  75. # rotate 270
  76. return image.transpose(PIL.Image.ROTATE_270)
  77. elif orientation == 7:
  78. # top-to-right mirror
  79. return PIL.ImageOps.mirror(image.transpose(PIL.Image.ROTATE_90))
  80. elif orientation == 8:
  81. # rotate 90
  82. return image.transpose(PIL.Image.ROTATE_90)
  83. else:
  84. return image