123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- from rembg import remove
- import cv2
- import numpy as np
- import os
- import time
- from datetime import datetime, timedelta
- def delete_old_files(folder_path, days_old):
- # 獲取當前時間
- now = time.time()
- # 計算指定的時間差
- cutoff = now - (days_old * 86400) # 86400 是一天的秒數
- # 遍歷資料夾中的所有檔案
- for filename in os.listdir(folder_path):
- file_path = os.path.join(folder_path, filename)
- # 確認這是個檔案
- if os.path.isfile(file_path):
- # 獲取檔案的最後修改時間
- file_mtime = os.path.getmtime(file_path)
- # 如果最後修改時間早於指定的時間差,則刪除該檔案
- if file_mtime < cutoff:
- os.remove(file_path)
- print(f"Deleted {file_path}")
- async def remove_background(input_path:str,output_path:str):
- input = cv2.imread(input_path)
- output = remove(input,bgcolor=(255,255,255,0))
- cv2.imwrite(output_path, output)
-
- delete_old_files(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/image",2)
- async def detect_face(image_file_path):
- try :
- img = cv2.imread(image_file_path)
- file_list = image_file_path.split("/")
- filename = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/image/check/{file_list[-1]}"
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 將圖片轉成灰階
- face_cascade = cv2.CascadeClassifier(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/haarcascade_frontalface_default.xml") # 載入人臉模型
- faces = face_cascade.detectMultiScale(gray) # 偵測人臉
- print(len(faces))
- if len(faces ) == 0 :
- return {"state":"fail","msg":"no face"}
- for (x, y, w, h) in faces:
- cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 8) # 利用 for 迴圈,抓取每個人臉屬性,繪製方框
- break
- cv2.imwrite(filename, img)
- delete_old_files(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/image/remove",2)
-
- return {"state":"success","filename":f"static/image/remove/{file_list[-1]}"}
- except Exception as e :
- return {"state":"fail","msg":str(e)}
-
|