I'm trying to build an app that can detect cavities in oral images using the YOLOV5 algorithm. I have an error when the user clicks upload it doesn't show the image in the browser, however, I can see the image saved in my app.
I tried tO print the image url and i get "Image URL: /static//static/1685369990.0033317.jpg", Which is a wrong path the image should be in static/img.jpg
This is my app.py code:
import io
import os
import time
import torch
from PIL import Image, ImageDraw, ImageFont
from flask import Flask, jsonify, url_for, render_template, request, redirect
app = Flask(__name__, static_url_path='/static')
RESULT_FOLDER = os.path.join('static')
app.config['RESULT_FOLDER'] = RESULT_FOLDER
model = torch.hub.load('ultralytics/yolov5', 'custom', path='./best.pt')
model.eval()
def draw_boxes(image, boxes, labels):
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", size=12)
for box, label in zip(boxes, labels):
x1, y1, x2, y2, _, cls = box.tolist()
draw.rectangle([x1, y1, x2, y2], outline='red', width=2)
text = f'{label}: {int(cls)}'
text_width, text_height = font.getsize(text)
draw.rectangle([x1, y1 - text_height, x1 + text_width, y1], fill='red')
draw.text((x1, y1 - text_height), text, fill='white', font=font)
return image
def get_prediction(img_bytes):
img = Image.open(io.BytesIO(img_bytes))
imgs = [img] # batched list of images
# Inference
results = model(imgs, size=640) # includes NMS
boxes = results.xyxy[0] # Get bounding boxes
labels = results.names[0] # Get class labels
# Draw bounding boxes and labels on the original image
img_with_boxes = draw_boxes(img, boxes, labels)
return img_with_boxes, boxes
@app.route('/', methods=['GET', 'POST'])
def predict():
if request.method == 'POST':
if 'file' not in request.files:
return redirect(request.url)
file = request.files.get('file')
if not file:
return
img_bytes = file.read()
try:
img_with_boxes, boxes = get_prediction(img_bytes)
img_name = str(time.time()) + '.jpg'
img_path = os.path.join(app.config['RESULT_FOLDER'], img_name)
img_with_boxes.save(img_path)
#image_url = '/' + img_path
image_url = url_for('static', filename=img_name)
print("Image URL:", image_url)
return render_template('test.html', result_image= image_url)
except Exception as e:
print(str(e)) # Print the exception for debugging
return render_template('error.html', error=str(e))
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)