doublelotus commited on
Commit
60e5cfd
·
1 Parent(s): 7ebb0f0

main update

Browse files
Files changed (1) hide show
  1. main.py +103 -0
main.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, send_file, Response, jsonify
2
+ from flask_cors import CORS
3
+ import numpy as np
4
+ import io
5
+ import torch
6
+ import cv2
7
+ from segment_anything import sam_model_registry, SamAutomaticMaskGenerator
8
+ from PIL import Image
9
+ import zipfile
10
+
11
+ app = Flask(__name__)
12
+ CORS(app)
13
+
14
+ cudaOrNah = "cuda" if torch.cuda.is_available() else "cpu"
15
+ print(cudaOrNah)
16
+
17
+ # Global model setup
18
+ checkpoint = "sam_vit_h_4b8939.pth"
19
+ model_type = "vit_h"
20
+ sam = sam_model_registry[model_type](checkpoint=checkpoint)
21
+ sam.to(device=cudaOrNah)
22
+ mask_generator = SamAutomaticMaskGenerator(
23
+ model=sam,
24
+ min_mask_region_area=0.0015 # Adjust this value as needed
25
+ )
26
+ print('Setup SAM model')
27
+
28
+ @app.route('/')
29
+ def hello():
30
+ return {"hei": "Malevolent Shrine :D"}
31
+
32
+ @app.route('/health', methods=['GET'])
33
+ def health_check():
34
+ # Simple health check endpoint
35
+ return jsonify({"status": "ok"}), 200
36
+
37
+ @app.route('/get-masks', methods=['POST'])
38
+ def get_masks():
39
+ try:
40
+ print('received image from frontend')
41
+ # Get the image file from the request
42
+ if 'image' not in request.files:
43
+ return jsonify({"error": "No image file provided"}), 400
44
+
45
+ image_file = request.files['image']
46
+ if image_file.filename == '':
47
+ return jsonify({"error": "No image file provided"}), 400
48
+
49
+ raw_image = Image.open(image_file).convert("RGB")
50
+ # Convert the PIL Image to a NumPy array
51
+ image_array = np.array(raw_image)
52
+ # Since OpenCV expects BGR, convert RGB to BGR
53
+ image = image_array[:, :, ::-1]
54
+
55
+ if image is None:
56
+ raise ValueError("Image not found or unable to read.")
57
+
58
+ masks = mask_generator.generate(image)
59
+ masks = sorted(masks, key=(lambda x: x['area']), reverse=True)
60
+
61
+ def is_background(segmentation):
62
+ val = (segmentation[10, 10] or segmentation[-10, 10] or
63
+ segmentation[10, -10] or segmentation[-10, -10])
64
+ return val
65
+
66
+ masks = [mask for mask in masks if not is_background(mask['segmentation'])]
67
+
68
+ for i in range(0, len(masks) - 1)[::-1]:
69
+ large_mask = masks[i]['segmentation']
70
+ for j in range(i+1, len(masks)):
71
+ not_small_mask = np.logical_not(masks[j]['segmentation'])
72
+ masks[i]['segmentation'] = np.logical_and(large_mask, not_small_mask)
73
+ masks[i]['area'] = masks[i]['segmentation'].sum()
74
+ large_mask = masks[i]['segmentation']
75
+
76
+ def sum_under_threshold(segmentation, threshold):
77
+ return segmentation.sum() / segmentation.size < 0.0015
78
+
79
+ masks = [mask for mask in masks if not sum_under_threshold(mask['segmentation'], 100)]
80
+ masks = sorted(masks, key=(lambda x: x['area']), reverse=True)
81
+
82
+ # Create a zip file in memory
83
+ zip_buffer = io.BytesIO()
84
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
85
+ for idx, mask in enumerate(masks):
86
+ alpha = mask['segmentation'].astype('uint8') * 255
87
+ mask_image = Image.fromarray(alpha)
88
+ mask_io = io.BytesIO()
89
+ mask_image.save(mask_io, format="PNG")
90
+ mask_io.seek(0)
91
+ zip_file.writestr(f'mask_{idx+1}.png', mask_io.read())
92
+
93
+ zip_buffer.seek(0)
94
+
95
+ return send_file(zip_buffer, mimetype='application/zip', as_attachment=True, download_name='masks.zip')
96
+ except Exception as e:
97
+ # Log the error message if needed
98
+ print(f"Error processing the image: {e}")
99
+ # Return a JSON response with the error message and a 400 Bad Request status
100
+ return jsonify({"error": "Error processing the image", "details": str(e)}), 400
101
+
102
+ if __name__ == '__main__':
103
+ app.run(debug=True)