Spaces:
Paused
Paused
File size: 2,274 Bytes
a08bf4a 7c563f8 a08bf4a 7c563f8 a08bf4a 7c563f8 a08bf4a 7c563f8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
from flask import Flask, render_template, request, redirect, url_for
from transformers import DetrImageProcessor, DetrForObjectDetection
from PIL import Image, ImageDraw
import torch
import os
import uuid
app = Flask(__name__)
# Set upload folder
UPLOAD_FOLDER = 'static/uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Load DETR model and processor
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
# Save the uploaded file
filename = str(uuid.uuid4()) + os.path.splitext(file.filename)[1]
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
# Process image for object detection
image = Image.open(filepath).convert("RGB")
inputs = processor(images=image, return_tensors="pt")
outputs = model(**inputs)
# Post-process outputs
target_sizes = torch.tensor([image.size[::-1]])
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
# Draw bounding boxes
draw = ImageDraw.Draw(image)
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
box = [round(i, 2) for i in box.tolist()]
label_str = model.config.id2label[label.item()]
draw.rectangle(box, outline="red", width=3)
draw.text((box[0], box[1]), f"{label_str}: {score:.2f}", fill="red")
# Save output image
output_filename = f"output_{filename}"
output_filepath = os.path.join(app.config['UPLOAD_FOLDER'], output_filename)
image.save(output_filepath)
return render_template('results.html', original_image=url_for('static', filename=f'uploads/{filename}'),
processed_image=url_for('static', filename=f'uploads/{output_filename}'))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860) |