df
Browse files
app.py
CHANGED
@@ -1,37 +1,69 @@
|
|
1 |
-
import
|
|
|
2 |
from PIL import Image
|
|
|
|
|
|
|
3 |
import base64
|
4 |
-
|
|
|
5 |
|
6 |
-
|
7 |
-
file_path = "input.jpg" # En az 64x64 piksel, ideal 512x512 bir görüntü kullan
|
8 |
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
if img.size[0] < 64 or img.size[1] < 64:
|
13 |
-
raise ValueError(f"Görüntü boyutu çok küçük: {img.size[0]}x{img.size[1]}. Minimum 64x64 piksel olmalı.")
|
14 |
-
print(f"Görüntü boyutu: {img.size[0]}x{img.size[1]}")
|
15 |
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
# Base64'ü PNG olarak kaydet
|
24 |
-
base64_string = result["mask"].split(",")[1] # "data:image/png;base64," kısmını atla
|
25 |
-
img_data = base64.b64decode(base64_string)
|
26 |
-
img = Image.open(BytesIO(img_data))
|
27 |
-
img.save("output_mask.png")
|
28 |
-
print("Maske 'output_mask.png' olarak kaydedildi.")
|
29 |
-
else:
|
30 |
-
print(f"Hata: {response.status_code}, {response.text}")
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
except ValueError as ve:
|
35 |
-
print(f"Hata: {str(ve)}")
|
36 |
-
except Exception as e:
|
37 |
-
print(f"Hata: {str(e)}")
|
|
|
1 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
2 |
+
from fastapi.responses import JSONResponse
|
3 |
from PIL import Image
|
4 |
+
import numpy as np
|
5 |
+
from transformers import SamModel, SamProcessor
|
6 |
+
import io
|
7 |
import base64
|
8 |
+
import torch
|
9 |
+
import uvicorn
|
10 |
|
11 |
+
app = FastAPI(title="SAM-ViT-Base API")
|
|
|
12 |
|
13 |
+
# SAM modelini ve işlemciyi yükle
|
14 |
+
model = SamModel.from_pretrained("facebook/sam-vit-base")
|
15 |
+
processor = SamProcessor.from_pretrained("facebook/sam-vit-base")
|
|
|
|
|
|
|
16 |
|
17 |
+
@app.post("/segment/")
|
18 |
+
async def segment_image(file: UploadFile = File(...)):
|
19 |
+
try:
|
20 |
+
# Görüntüyü oku
|
21 |
+
image_data = await file.read()
|
22 |
+
image = Image.open(io.BytesIO(image_data)).convert("RGB")
|
23 |
+
|
24 |
+
# Görüntü boyutlarını al
|
25 |
+
original_width, original_height = image.size
|
26 |
+
if original_width < 64 or original_height < 64:
|
27 |
+
raise HTTPException(status_code=400, detail=f"Görüntü boyutu çok küçük: {original_width}x{original_height}. Minimum 64x64 piksel olmalı.")
|
28 |
+
|
29 |
+
# Görüntüyü işlemciye hazırla (ölçeklendirme için max_length belirt)
|
30 |
+
inputs = processor(image, return_tensors="pt", do_rescale=True, do_resize=True, max_length=768)
|
31 |
+
|
32 |
+
# Model ile segmentasyon yap
|
33 |
+
with torch.no_grad():
|
34 |
+
outputs = model(**inputs)
|
35 |
+
|
36 |
+
# Maskeyi al
|
37 |
+
masks = outputs.pred_masks.detach().cpu().numpy() # Shape: (batch_size, num_masks, height, width)
|
38 |
+
if masks.shape[1] == 0:
|
39 |
+
raise HTTPException(status_code=500, detail="Hiç maske üretilmedi.")
|
40 |
+
|
41 |
+
# İlk maskeyi al
|
42 |
+
mask = masks[0][0] # Shape: (height, width)
|
43 |
+
|
44 |
+
# Maske şeklini kontrol et
|
45 |
+
if len(mask.shape) != 2:
|
46 |
+
raise HTTPException(status_code=500, detail=f"Hatalı maske şekli: {mask.shape}. 2D matris bekleniyor.")
|
47 |
+
|
48 |
+
# Maskeyi binary hale getir
|
49 |
+
mask = (mask > 0).astype(np.uint8) * 255
|
50 |
+
|
51 |
+
# Maskeyi orijinal görüntü boyutlarına yeniden boyutlandır
|
52 |
+
mask_image = Image.fromarray(mask).resize((original_width, original_height), Image.NEAREST)
|
53 |
+
|
54 |
+
# Maskeyi PNG olarak kaydet
|
55 |
+
buffered = io.BytesIO()
|
56 |
+
mask_image.save(buffered, format="PNG")
|
57 |
+
mask_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
58 |
+
|
59 |
+
return JSONResponse(content={"mask": f"data:image/png;base64,{mask_base64}"})
|
60 |
+
|
61 |
+
except Exception as e:
|
62 |
+
raise HTTPException(status_code=500, detail=str(e))
|
63 |
|
64 |
+
@app.get("/")
|
65 |
+
async def root():
|
66 |
+
return {"message": "SAM-ViT-Base API çalışıyor. /segment endpoint'ine görüntü yükleyin."}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
+
if __name__ == "__main__":
|
69 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|
|
|