Skip to content

Commit

Permalink
New app project
Browse files Browse the repository at this point in the history
  • Loading branch information
aagustinconti committed Jan 13, 2023
1 parent b534374 commit 73be9b1
Show file tree
Hide file tree
Showing 6 changed files with 252 additions and 8 deletions.
57 changes: 57 additions & 0 deletions docker_control.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import docker
import os
import logging

# Debug
logging.basicConfig(
format='%(asctime)s | %(levelname)s: %(message)s', level=logging.INFO)

# Get the current working directory
logging.info("Looking for the current directory...")
cwd = os.getcwd()
logging.info(f"The current directory is --> {cwd}")

logging.info("Looking for the current display...")
display = os.getenv("DISPLAY")
logging.info(f"The current display is --> {display}")


# Docker SDK --> https://docker-py.readthedocs.io/en/stable/containers.html

logging.info("Instantiating Docker client...")
client = docker.from_env()

logging.info("Checking if the Image already exists...")

if not os.system('[ "$(docker image inspect yolov7_detect_track_count:latest 2> /dev/null)" == [] ]'):

logging.info("The image doesn't exist. Building the Docker Image...")

os.system("cd ./dependencies")
os.system("docker build -t yolov7_detect_track_count .")
os.system("cd ..")

else:
logging.info("The image has already exists.")


logging.info(
"Setting up X Server to accept connections. Turning Access control off...")
os.system("xhost +")


logging.info("Running a container...")
container = client.containers.run(
image='yolov7_detect_track_count:latest',
auto_remove=True,
device_requests=[docker.types.DeviceRequest(
device_ids=["0"], capabilities=[['gpu']])],
devices=["/dev/video0:/dev/video0"],
volumes={
'/tmp/.X11-unix': {'bind': '/tmp/.X11-unix', 'mode': 'rw'},
cwd: {'bind': '/workspace', 'mode': 'rw'}
},
environment=[f"DISPLAY={display}"],
tty=True,
command='python test_oop.py'
)
38 changes: 38 additions & 0 deletions flask-app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Import necessary libraries
from flask import Flask, render_template, Response
import cv2
# Initialize the Flask app
app = Flask(__name__)

#https://towardsdatascience.com/video-streaming-in-web-browsers-with-opencv-flask-93a38846fe00
camera = cv2.VideoCapture("http://192.168.102.3:4747/video")
'''
for ip camera use - rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp'
for local webcam use cv2.VideoCapture(0)
'''


def gen_frames():
while True:
success, frame = camera.read() # read the camera frame
if not success:
break
else:
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') # concat


@app.route('/')
def index():
return render_template('index.html')


@app.route('/video_feed')
def video_feed():
return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')


if __name__ == "__main__":
app.run(debug=True)
10 changes: 10 additions & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<body>
<div class="container">
<div class="row">
<div class="col-lg-8 offset-lg-2">
<h3 class="mt-5">Live Streaming</h3>
<img src="{{ url_for('video_feed') }}" width="100%">
</div>
</div>
</div>
</body>
10 changes: 5 additions & 5 deletions test_oop.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
WebCamera: 0 ---> DEFAULT
Youtube Video or stream: "https://www.youtube.com/watch?v=qP1y7Tdab7Y"
Stream URL: "http://IP/hls/stream_src.m3u8"
RSTP Stream:
RSTP Stream: "http://192.168.102.3:4747/video"
Local video: "img_bank/cows_for_sale.mp4"
Local image: "img_bank/img.jpg" | "img_bank/img.png"
"""
test.video_path = 0
test.video_path = 0 #"http://192.168.102.3:4747/video"


"""
Expand All @@ -28,7 +28,7 @@
"""
test.max_width = 720
test.max_fps = 25 # Max 1000
test.inv_h_frame = True
test.inv_h_frame = False


"""
Expand All @@ -51,7 +51,7 @@
- Load the ROI color.
"""
#test.roi = [0,0,0,0]
test.auto_load_roi = True
test.auto_load_roi = False
test.roi_color = (255, 255, 255)


Expand All @@ -68,7 +68,7 @@
"""
test.model_path = 'pretrained_weights/yolov7.pt'
test.graphic_card = 0
test.class_ids = [0]
test.class_ids = []
test.img_sz = 640
test.color = (0, 255, 0)
test.conf_thres = 0.5
Expand Down
137 changes: 137 additions & 0 deletions test_oop_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
from yolov7_sort_count_oop import YoloSortCount

#################### TEST ####################

# INSTANCIATE

test = YoloSortCount()


"""
###### AVAILABLE SOURCES ######
WebCamera: 0 ---> DEFAULT
Youtube Video or stream: "https://www.youtube.com/watch?v=qP1y7Tdab7Y"
Stream URL: "http://IP/hls/stream_src.m3u8"
RSTP Stream: "http://192.168.102.3:4747/video"
Local video: "img_bank/cows_for_sale.mp4"
Local image: "img_bank/img.jpg" | "img_bank/img.png"
"""
test.video_path = "http://192.168.102.3:4747/video"


"""
###### FRAME PROPERTIES ######
- Set the max size of the frame (width)
- Set the max fps of the video
- Invert the image (In case of your WebCamera is mirrored, IE)
"""
test.max_width = 720
test.max_fps = 25 # Max 1000
test.inv_h_frame = False


"""
###### SHOWING RESULTS ######
- Show the results in your display (Interactive ROI, imshow of the out frame)
- In case of you are not showing the results, set the timer to stop the execution.
- Stop the frame with hold_image method in case you are using image as a source.
"""
test.show_img = True
test.ends_in_sec = 10
test.hold_img = False


"""
###### ROI ######
- Load the ROI manually.
-
- Load the ROI color.
"""
#test.roi = [0,0,0,0]
test.auto_load_roi = True
test.roi_color = (255, 255, 255)


"""
###### DETECTION MODEL ######
- Specify the path of the model.
- Select the ID of your Graphic Card (nvidia-smi)
- Select the classes to detect
- Set the image size (Check if the YOLO model allows that --> IE: yolov7.pt 640, yolov7-w6.pt 1280 or 640)
- Set the bounding box color
- Set the minimum confidence to detect.
- Set the minimum overlap of a predicted versus actual bounding box for an object.
"""
test.model_path = 'pretrained_weights/yolov7.pt'
test.graphic_card = 0
test.class_ids = []
test.img_sz = 640
test.color = (0, 255, 0)
test.conf_thres = 0.5
test.iou_thres = 0.65

"""
###### TRACKING MODEL ######
- Specify the path of the model.
- Set the max distance between two points to consider a tracking object.
- Set the max overlap of a predicted versus actual bounding box for an object.
- Set the image size (Check if the YOLO model allows that --> IE: yolov7.pt 640, yolov7-w6.pt 1280 or 640)
- Set max_age to consider a lost of a tracking object that get out of the seen area.
- Set the minimum frames to start to track objects.
- Set the value that indicates how many previous frames of feature vectors should be retained for distance calculation for each track.
- Set the color of the centroid and label of a tracking object.
"""
test.deep_sort_model = "osnet_x1_0"
test.ds_max_dist = 0.1
test.ds_max_iou_distance = 0.7
test.ds_max_age = 30
test.ds_n_init = 3
test.ds_nn_budget = 100
test.ds_color = (0, 0, 255)

"""
###### PLOT RESULTS ######
- Specify the min x (left to right) to plot the draws
- Specify the min y (top to bottom) to plot the draws
- Specify padding between rectangles and text
- Specify the text color.
- Specify the rectangles color.
"""
test.plot_xmin = 10
test.plot_ymin = 10
test.plot_padding = 2
test.plot_text_color = (255, 255, 255)
test.plot_bgr_color = (0, 0, 0)


"""
###### DEBUG TEXT ######
- Show the configs
- Show the detection output variables
- Show the tracking output variables
- Show counting output variables
"""
test.show_configs = False
test.show_detection = False
test.show_tracking = False
test.show_count = False

"""
###### SAVING RESULTS ######
- Select if you want to save the results
- Select a location to save the results
"""
test.save_vid = False
test.save_loc = "results/result"


# Run
test.run()
8 changes: 5 additions & 3 deletions yolov7_sort_count_oop.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,12 +158,14 @@ def load_video_capture(self, video_path):

orig_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
orig_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))


orig_ratio = orig_h / orig_w

if orig_w > self.max_width:
if orig_w > self.max_width and orig_w != 0 :
logging.info(
'Capture has more width than max. width allowed. Rezising...')

orig_ratio = orig_h / orig_w

cap = self.change_res(cap, self.max_width, orig_ratio)

orig_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
Expand Down

0 comments on commit 73be9b1

Please sign in to comment.