sezer91 commited on
Commit
0d450c2
·
1 Parent(s): 9630f96
Files changed (1) hide show
  1. app.py +30 -58
app.py CHANGED
@@ -1,65 +1,37 @@
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="Görüntü boyutu çok küçük. Minimum 64x64 piksel olmalı.")
28
-
29
- # Görüntüyü işlemciye hazırla
30
- inputs = processor(image, return_tensors="pt")
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
- # Maskeyi binary hale getir
45
- mask = (mask > 0).astype(np.uint8) * 255
46
-
47
- # Maskeyi orijinal görüntü boyutlarına yeniden boyutlandır
48
- mask_image = Image.fromarray(mask).resize((original_width, original_height), Image.NEAREST)
49
-
50
- # Maskeyi PNG olarak kaydet
51
- buffered = io.BytesIO()
52
- mask_image.save(buffered, format="PNG")
53
- mask_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
54
-
55
- return JSONResponse(content={"mask": f"data:image/png;base64,{mask_base64}"})
56
-
57
- except Exception as e:
58
- raise HTTPException(status_code=500, detail=str(e))
59
 
60
- @app.get("/")
61
- async def root():
62
- return {"message": "SAM-ViT-Base API çalışıyor. /segment endpoint'ine görüntü yükleyin."}
 
 
 
 
 
 
 
 
63
 
64
- if __name__ == "__main__":
65
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
 
1
+ import requests
 
2
  from PIL import Image
 
 
 
3
  import base64
4
+ from io import BytesIO
 
5
 
6
+ url = "https://<your-space-url>.hf.space/segment"
7
+ file_path = "input.jpg" # En az 64x64 piksel, ideal 512x512 bir görüntü kullan
8
 
9
+ try:
10
+ # Görüntü dosyasını kontrol et
11
+ img = Image.open(file_path)
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
+ with open(file_path, "rb") as file:
17
+ files = {"file": file}
18
+ response = requests.post(url, files=files)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ if response.status_code == 200:
21
+ result = response.json()
22
+ print("Başarılı! Maske alındı.")
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
+ except FileNotFoundError:
33
+ print(f"Hata: {file_path} dosyası bulunamadı.")
34
+ except ValueError as ve:
35
+ print(f"Hata: {str(ve)}")
36
+ except Exception as e:
37
+ print(f"Hata: {str(e)}")