윤영준 윤영준 05-17
fix in file sending
@178cf2f722e12182215e78c08ef6fa21343d3342
DB/db.py
--- DB/db.py
+++ DB/db.py
@@ -1,12 +1,0 @@
-import psycopg2
-import json
-import requests
-import time
-
-
-async def get_cctv_info():
-    pass
-
-def setup_db():
-    pass
-
hls_streaming/hls.py
--- hls_streaming/hls.py
+++ hls_streaming/hls.py
@@ -9,7 +9,7 @@
 
 
 class FrameCapturer:
-    def __init__(self, hls_url, cctv_id, interval=5, buffer_duration=15, buffer_size=600, time_zone="Asia/Seoul", endpoint="localhost:12345"):
+    def __init__(self, hls_url, cctv_id, interval=5, buffer_duration=15, buffer_size=600, time_zone="Asia/Seoul", endpoint="http://localhost:12345/cctv/infer"):
         '''
         :param hls_url: hls address
         :param cctv_id: cctv_id number(whatever it is, this exists to distinguish from where. Further disscusion is needed with frontend developers.)
@@ -69,6 +69,7 @@
                             self.current_frame = cv2.cvtColor(np.array(self.current_frame), cv2.COLOR_RGB2BGR)
                             frame_name = f"captured_frame_{self.captured_frame_count}.jpg"
                             img_binary = cv2.imencode('.png', self.current_frame)
+                            img_binary = img_binary[1].tobytes()
                             self.send_image_to_server(img_binary, self.endpoint)
                             # cv2.imwrite(f'hls_streaming/captured_frame_/{datetime.now()}_{frame_name}', img)
                             self.last_capture_time = current_time
@@ -87,7 +88,12 @@
             'x-cctv-longitude' : '',
         }
         try:
-            requests.post(endpoint, headers=header, files=image)
+            file = {
+                'image': (f'frame_{self.cctvid}.{image_type}',
+                              image,
+                              f'image/{image_type}')
+                    }
+            requests.post(endpoint, headers=header, files=file)
         except:
             print("Can not connect to the analyzer server. Check the endpoint address or connection.\n"
                   f"Can not connect to : {self.endpoint}")
@@ -121,3 +127,4 @@
         t2 = time.time()
         with open("result.txt", "w") as file:
             file.write(f'{t2-t1} seconds before terminating')
+        exit()
 
test.py (added)
+++ test.py
@@ -0,0 +1,54 @@
+from flask import Flask, request
+from flask_restx import Api, Resource, fields
+import os
+from datetime import datetime
+
+app = Flask(__name__)
+api = Api(app, version='1.0', title='CCTV Image Upload API',
+          description='A simple API for receiving CCTV images')
+
+# Namespace definition
+ns = api.namespace('cctv', description='CCTV operations')
+
+# Define the expected model for incoming data
+image_upload_model = api.model('ImageUpload', {
+    'image': fields.String(required=True, description='Image file', dt='File'),
+    'x-cctv-info': fields.String(required=False, description='CCTV identifier'),
+    'x-time-sent': fields.String(required=False, description='Time image was sent'),
+    'x-cctv-latitude': fields.String(required=False, description='Latitude of CCTV'),
+    'x-cctv-longitude': fields.String(required=False, description='Longitude of CCTV')
+})
+
+# Define the directory where images will be saved
+IMAGE_DIR = "received_images"
+if not os.path.exists(IMAGE_DIR):
+    os.makedirs(IMAGE_DIR)
+
[email protected]('/infer', )
+class ImageUpload(Resource):
+    @ns.expect(image_upload_model, validate=True)
+    @ns.response(200, 'Success')
+    @ns.response(400, 'Validation Error')
+    def post(self):
+        if 'image' not in request.files:
+            ns.abort(400, 'No image part in the request')
+
+        image = request.files['image']
+        cctv_info = request.headers.get('x-cctv-info', '')
+        time_sent = request.headers.get('x-time-sent', '')
+        cctv_latitude = request.headers.get('x-cctv-latitude', 'Not provided')
+        cctv_longitude = request.headers.get('x-cctv-longitude', 'Not provided')
+
+        if image.filename == '':
+            ns.abort(400, 'No selected image')
+
+        # Use current timestamp to avoid filename conflicts
+        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+        filename = f"{timestamp}_{cctv_info}.png"
+        image_path = os.path.join(IMAGE_DIR, filename)
+        image.save(image_path)
+
+        return {"message": f"Image {filename} uploaded successfully!"}
+
+if __name__ == '__main__':
+    app.run(debug=True, port=12345)
yoloseg/inference_.py
--- yoloseg/inference_.py
+++ yoloseg/inference_.py
@@ -105,7 +105,7 @@
                 y1 = 0
             x1, y1, x2, y2 = x1, y1, x1 + w, y1 + h
 
-            # To handle edge cases where you get bboxes that pass beyond the original image
+            # To handle edge cases where you get bboxes that pass beyond the original image_binary
             if y2 > image_shape[1]:
                 h = h + image_shape[1] - h - y1
             if x2 > image_shape[0]:
@@ -126,7 +126,7 @@
             # Threshold to create a binary mask
             final_mask = (resized_mask > 0.5).astype(np.uint8)
 
-            # Place the mask in the corresponding location on a full-sized mask image
+            # Place the mask in the corresponding location on a full-sized mask image_binary
             full_mask = np.zeros((image_shape[0], image_shape[1]), dtype=np.uint8)
             print(final_mask.shape)
             print(full_mask[y1:y2, x1:x2].shape)
@@ -161,25 +161,25 @@
 
 def overlay_mask(image, mask, color=(0, 255, 0), alpha=0.5):
     """
-    Overlays a mask onto an image using a specified color and transparency level.
+    Overlays a mask onto an image_binary using a specified color and transparency level.
 
     Parameters:
-        image (np.ndarray): The original image.
-        mask (np.ndarray): The mask to overlay. Must be the same size as the image.
+        image (np.ndarray): The original image_binary.
+        mask (np.ndarray): The mask to overlay. Must be the same size as the image_binary.
         color (tuple): The color for the mask overlay in BGR format (default is green).
         alpha (float): Transparency factor for the mask; 0 is fully transparent, 1 is opaque.
 
     Returns:
-        np.ndarray: The image with the overlay.
+        np.ndarray: The image_binary with the overlay.
     """
     # Ensure the mask is a binary mask
     mask = (mask > 0).astype(np.uint8)  # Convert mask to binary if not already
 
-    # Create an overlay with the same size as the image but only using the mask area
+    # Create an overlay with the same size as the image_binary but only using the mask area
     overlay = np.zeros_like(image, dtype=np.uint8)
     overlay[mask == 1] = color
 
-    # Blend the overlay with the image using the alpha factor
+    # Blend the overlay with the image_binary using the alpha factor
     return cv2.addWeighted(src1=overlay, alpha=alpha, src2=image, beta=1 - alpha, gamma=0)
 
 
@@ -199,10 +199,10 @@
         run_with_cuda=True
     )
 
-    # Load an image
+    # Load an image_binary
     img = cv2.imread(image_path)
     if img is None:
-        print("Error loading image")
+        print("Error loading image_binary")
         return
     img = cv2.resize(img, model_input_shape)
     # Run inference
@@ -221,7 +221,7 @@
         label = f"{class_name}: {confidence:.2f}"
         cv2.putText(img, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, detection['color'], 2)
 
-    # Show the image
+    # Show the image_binary
     # cv2.imshow('Detections', img)
     # cv2.waitKey(0)
     # cv2.destroyAllWindows()
@@ -256,7 +256,7 @@
     for iteration, image_path in enumerate(image_dir):
         img = cv2.imread(image_path)
         if img is None:
-            print("Error loading image")
+            print("Error loading image_binary")
             return
         img = cv2.resize(img, model_input_shape)
         # Run inference
@@ -267,17 +267,17 @@
         print(t2-t1)
 
         # Display results
-        for detection in detections:
-            x, y, w, h = detection['box']
-            class_name = detection['class_name']
-            confidence = detection['confidence']
-            cv2.rectangle(img, (x, y), (x+w, y+h), detection['color'], 2)
-            label = f"{class_name}: {confidence:.2f}"
-            cv2.putText(img, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, detection['color'], 2)
-
-        if len(mask_maps) > 0 :
-            seg_image = overlay_mask(img, mask_maps[0], color=(0, 255, 0), alpha=0.3)
-            cv2.imwrite(f"result/{iteration}.png", seg_image)
+        # for detection in detections:
+        #     x, y, w, h = detection['box']
+        #     class_name = detection['class_name']
+        #     confidence = detection['confidence']
+        #     cv2.rectangle(img, (x, y), (x+w, y+h), detection['color'], 2)
+        #     label = f"{class_name}: {confidence:.2f}"
+        #     cv2.putText(img, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, detection['color'], 2)
+        #
+        # if len(mask_maps) > 0 :
+        #     seg_image = overlay_mask(img, mask_maps[0], color=(0, 255, 0), alpha=0.3)
+        #     cv2.imwrite(f"result/{iteration}.png", seg_image)
 
 
 if __name__ == "__main__":
Add a comment
List