Ashrafb commited on
Commit
695a923
·
verified ·
1 Parent(s): 71051e9

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +12 -32
main.py CHANGED
@@ -1,4 +1,4 @@
1
- from fastapi import FastAPI, File, UploadFile
2
  from fastapi.responses import StreamingResponse, FileResponse
3
  from fastapi.staticfiles import StaticFiles
4
  import torch
@@ -23,28 +23,8 @@ def load_model():
23
  # Configure logging
24
  logging.basicConfig(level=logging.INFO)
25
 
26
- def detect_and_crop_face(image):
27
- # Load the pre-trained face detector
28
- face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
29
-
30
- # Convert to grayscale
31
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
32
-
33
- # Detect faces
34
- faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
35
-
36
- # If faces are detected, crop the first face
37
- if len(faces) > 0:
38
- x, y, w, h = faces[0]
39
- cropped_face = image[y:y+h, x:x+w]
40
- return cropped_face
41
-
42
- # Log if no face is detected
43
- logging.warning("No face detected.")
44
- return None
45
-
46
  @app.post("/upload/")
47
- async def process_image(file: UploadFile = File(...)):
48
  global model
49
  if model is None:
50
  load_model()
@@ -54,7 +34,7 @@ async def process_image(file: UploadFile = File(...)):
54
 
55
  # Convert the uploaded image to numpy array
56
  nparr = np.frombuffer(contents, np.uint8)
57
- frame_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
58
 
59
  if frame_bgr is None:
60
  logging.error("Failed to decode the image.")
@@ -62,19 +42,14 @@ async def process_image(file: UploadFile = File(...)):
62
 
63
  logging.info(f"Uploaded image shape: {frame_bgr.shape}")
64
 
65
- # Detect and crop face
66
- cropped_face = detect_and_crop_face(frame_bgr)
67
- if cropped_face is None:
68
- return {"error": "No face detected or alignment failed."}
69
-
70
- # Save the cropped face temporarily
71
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
72
- cv2.imwrite(temp_file.name, cropped_face)
73
  temp_file_path = temp_file.name
74
 
75
  try:
76
- # Process the cropped face
77
- aligned_face, instyle, message = model.detect_and_align_image(temp_file_path, 0, 0, 0, 0)
78
  if aligned_face is None or instyle is None:
79
  logging.error("Failed to process the image: No face detected or alignment failed.")
80
  return {"error": message}
@@ -84,12 +59,17 @@ async def process_image(file: UploadFile = File(...)):
84
  logging.error("Failed to toonify the image.")
85
  return {"error": message}
86
 
 
87
  processed_image_rgb = cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB)
 
 
88
  _, encoded_image = cv2.imencode('.jpg', processed_image_rgb)
89
 
 
90
  return StreamingResponse(BytesIO(encoded_image.tobytes()), media_type="image/jpeg")
91
 
92
  finally:
 
93
  os.remove(temp_file_path)
94
 
95
  # Mount static files directory
 
1
+ from fastapi import FastAPI, File, UploadFile, Form
2
  from fastapi.responses import StreamingResponse, FileResponse
3
  from fastapi.staticfiles import StaticFiles
4
  import torch
 
23
  # Configure logging
24
  logging.basicConfig(level=logging.INFO)
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  @app.post("/upload/")
27
+ async def process_image(file: UploadFile = File(...), top: int = Form(...), bottom: int = Form(...), left: int = Form(...), right: int = Form(...)):
28
  global model
29
  if model is None:
30
  load_model()
 
34
 
35
  # Convert the uploaded image to numpy array
36
  nparr = np.frombuffer(contents, np.uint8)
37
+ frame_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR) # Read as BGR format by default
38
 
39
  if frame_bgr is None:
40
  logging.error("Failed to decode the image.")
 
42
 
43
  logging.info(f"Uploaded image shape: {frame_bgr.shape}")
44
 
45
+ # Save the uploaded image temporarily to pass the file path to the model
 
 
 
 
 
46
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
47
+ cv2.imwrite(temp_file.name, frame_bgr)
48
  temp_file_path = temp_file.name
49
 
50
  try:
51
+ # Process the uploaded image using the file path
52
+ aligned_face, instyle, message = model.detect_and_align_image(temp_file_path, top, bottom, left, right)
53
  if aligned_face is None or instyle is None:
54
  logging.error("Failed to process the image: No face detected or alignment failed.")
55
  return {"error": message}
 
59
  logging.error("Failed to toonify the image.")
60
  return {"error": message}
61
 
62
+ # Convert the processed image to RGB before returning
63
  processed_image_rgb = cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB)
64
+
65
+ # Convert processed image to bytes
66
  _, encoded_image = cv2.imencode('.jpg', processed_image_rgb)
67
 
68
+ # Return the processed image as a streaming response
69
  return StreamingResponse(BytesIO(encoded_image.tobytes()), media_type="image/jpeg")
70
 
71
  finally:
72
+ # Clean up the temporary file
73
  os.remove(temp_file_path)
74
 
75
  # Mount static files directory