Myogyi commited on
Commit
5b22ac1
1 Parent(s): 285b582

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -56
app.py CHANGED
@@ -1,79 +1,61 @@
 
1
  import os
2
  import subprocess
3
- from fastapi import FastAPI, UploadFile, File, HTTPException
4
- from fastapi.responses import FileResponse, PlainTextResponse
5
- import shutil
6
 
7
- app = FastAPI()
8
-
9
- # Define paths and parameters
10
- weights_path = 'yolo/yolov7-main/runs/train/best.pt'
11
- img_size = 640
12
- conf = 0.20
13
- source_folder = 'dataset/images/train/'
14
- output_folder = 'out/fixed_folder/'
15
-
16
- # Ensure folders exist
17
- os.makedirs(source_folder, exist_ok=True)
18
- os.makedirs(output_folder, exist_ok=True)
19
 
20
- # Root endpoint to prevent 404 on /
21
- @app.get("/")
22
- async def root():
23
- return PlainTextResponse("Welcome to the YOLOv7 Object Detection API. Use the /detect endpoint to upload an image.")
24
 
25
- # Optional: Add a route for favicon.ico to avoid 404
26
- @app.get("/favicon.ico", include_in_schema=False)
27
- async def favicon():
28
- return PlainTextResponse("", status_code=204)
29
 
30
- # Define the detect function
31
- def detect_and_crop(image_path: str):
32
  # Run the detection command
33
  command = [
34
  'python', 'yolo/yolov7-main/detect.py',
35
  '--weights', weights_path,
36
  '--conf-thres', str(conf),
37
  '--img-size', str(img_size),
38
- '--source', image_path,
39
  '--project', 'out/', # Output directory
40
  '--name', 'fixed_folder', # Folder name for results
41
  '--exist-ok' # Don't increment folder name
42
  ]
43
 
44
- # Execute the command and check for errors
45
- result = subprocess.run(command, capture_output=True, text=True)
46
- if result.returncode != 0:
47
- raise HTTPException(status_code=500, detail=f"Detection failed: {result.stderr}")
 
48
 
49
- # Locate the output image in the expected output directory
50
- output_files = os.listdir(output_folder)
51
- output_image_path = None
52
- for file_name in output_files:
53
- if file_name.endswith(".jpg") or file_name.endswith(".jpeg") or file_name.endswith(".png"):
54
- output_image_path = os.path.join(output_folder, file_name)
55
- break
56
 
57
- if not output_image_path or not os.path.exists(output_image_path):
58
- raise HTTPException(status_code=404, detail="Output image not found.")
59
 
60
- return output_image_path
 
61
 
62
- # FastAPI endpoint to accept an image, perform detection, and return the processed image
63
- @app.post("/detect")
64
- async def detect_endpoint(file: UploadFile = File(...)):
65
- # Save the uploaded file to the source folder
66
- input_image_path = os.path.join(source_folder, 'input_image.jpg')
67
- with open(input_image_path, "wb") as buffer:
68
- shutil.copyfileobj(file.file, buffer)
69
 
70
- # Perform detection and get the path to the output image
71
- try:
72
- output_image_path = detect_and_crop(input_image_path)
73
- except HTTPException as e:
74
- raise e
75
- except Exception as e:
76
- raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")
 
77
 
78
- # Return the output image as a response
79
- return FileResponse(output_image_path, media_type="image/jpeg")
 
1
+ import gradio as gr
2
  import os
3
  import subprocess
4
+ import cv2
5
+ import numpy as np
 
6
 
7
+ # Define the detect function
8
+ def detect_and_crop(input_image):
9
+ # Define paths and parameters
10
+ weights_path = 'yolo/yolov7-main/runs/train/best.pt'
11
+ img_size = 640
12
+ conf = 0.20
13
+ source = 'dataset/images/train/' # Folder for input images
 
 
 
 
 
14
 
15
+ # Ensure the input image folder exists
16
+ os.makedirs(source, exist_ok=True)
 
 
17
 
18
+ # Save the input image to the source directory
19
+ input_image.save(os.path.join(source, 'input_image.jpg'))
 
 
20
 
 
 
21
  # Run the detection command
22
  command = [
23
  'python', 'yolo/yolov7-main/detect.py',
24
  '--weights', weights_path,
25
  '--conf-thres', str(conf),
26
  '--img-size', str(img_size),
27
+ '--source', os.path.join(source, 'input_image.jpg'),
28
  '--project', 'out/', # Output directory
29
  '--name', 'fixed_folder', # Folder name for results
30
  '--exist-ok' # Don't increment folder name
31
  ]
32
 
33
+ # Execute the command
34
+ subprocess.run(command)
35
+
36
+ # Load the result image
37
+ output_image_path = 'out/fixed_folder/input_image_upscaled.jpg'
38
 
39
+ # Check if the image exists
40
+ if not os.path.exists(output_image_path):
41
+ return "No output image found."
 
 
 
 
42
 
43
+ # Read the output image
44
+ output_image = cv2.imread(output_image_path)
45
 
46
+ # Convert BGR (OpenCV format) to RGB (Gradio format)
47
+ output_image = cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB)
48
 
49
+ return output_image
 
 
 
 
 
 
50
 
51
+ # Set up the Gradio interface
52
+ iface = gr.Interface(
53
+ fn=detect_and_crop,
54
+ inputs=gr.Image(type="pil"), # Input type
55
+ outputs=gr.Image(type="numpy"), # Output type
56
+ title="YOLOv7 Object Detection",
57
+ description="Upload an image for object detection and cropping."
58
+ )
59
 
60
+ # Launch the app
61
+ iface.launch()