image_operate.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from rembg import remove
  2. import cv2
  3. import numpy as np
  4. import os
  5. import time
  6. from datetime import datetime, timedelta
  7. def delete_old_files(folder_path, days_old):
  8. # 獲取當前時間
  9. now = time.time()
  10. # 計算指定的時間差
  11. cutoff = now - (days_old * 86400) # 86400 是一天的秒數
  12. # 遍歷資料夾中的所有檔案
  13. for filename in os.listdir(folder_path):
  14. file_path = os.path.join(folder_path, filename)
  15. # 確認這是個檔案
  16. if os.path.isfile(file_path):
  17. # 獲取檔案的最後修改時間
  18. file_mtime = os.path.getmtime(file_path)
  19. # 如果最後修改時間早於指定的時間差,則刪除該檔案
  20. if file_mtime < cutoff:
  21. os.remove(file_path)
  22. print(f"Deleted {file_path}")
  23. async def remove_background(input_path:str,output_path:str):
  24. input = cv2.imread(input_path)
  25. output = remove(input,bgcolor=(255,255,255,0))
  26. cv2.imwrite(output_path, output)
  27. delete_old_files(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/image",2)
  28. async def detect_face(image_file_path):
  29. try :
  30. img = cv2.imread(image_file_path)
  31. file_list = image_file_path.split("/")
  32. filename = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/image/check/{file_list[-1]}"
  33. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 將圖片轉成灰階
  34. face_cascade = cv2.CascadeClassifier(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/haarcascade_frontalface_default.xml") # 載入人臉模型
  35. faces = face_cascade.detectMultiScale(gray) # 偵測人臉
  36. print(len(faces))
  37. if len(faces ) == 0 :
  38. return {"state":"fail","msg":"no face"}
  39. for (x, y, w, h) in faces:
  40. cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 8) # 利用 for 迴圈,抓取每個人臉屬性,繪製方框
  41. break
  42. cv2.imwrite(filename, img)
  43. delete_old_files(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/image/remove",2)
  44. return {"state":"success","filename":f"static/image/remove/{file_list[-1]}"}
  45. except Exception as e :
  46. return {"state":"fail","msg":str(e)}