NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

import cv2
import numpy as np
import os
import time
import datetime
import threading
import pytz

yolo_cfg = "yolov3.cfg"
yolo_weights = "yolov3.weights"
coco_names = "coco.names"

assert os.path.isfile(yolo_cfg), "yolov3.cfg not found"
assert os.path.isfile(yolo_weights), "yolov3.weights not found"
assert os.path.isfile(coco_names), "coco.names not found"

net = cv2.dnn.readNet(yolo_weights, yolo_cfg)
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]

with open(coco_names, "r") as f:
classes = [line.strip() for line in f.readlines()]

class VideoCaptureAsync:
def __init__(self, src=0):
self.src = src
self.cap = cv2.VideoCapture(self.src)
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 2)
self.grabbed, self.frame = self.cap.read()
self.started = False
self.read_lock = threading.Lock()

def start(self):
if self.started:
print('[!] Asynchronous video capture is already started.')
return None
self.started = True
self.thread = threading.Thread(target=self.update, args=())
self.thread.start()
return self

def update(self):
while self.started:
grabbed, frame = self.cap.read()
with self.read_lock:
self.grabbed = grabbed
self.frame = frame

def read(self):
with self.read_lock:
if self.grabbed:
frame = self.frame.copy()
else:
frame = None
return self.grabbed, frame

def stop(self):
self.started = False
self.thread.join()

def __exit__(self, exec_type, exc_value, traceback):
self.cap.release()

cap = VideoCaptureAsync("rtsp://admin:[email protected]:554/stream1").start()

frame_count = 0
skip_frames = 2

open("logfile.txt", "w").close()
file = open("logfile.txt", "a")

target_width = 640
target_height = 480
frame_size = (target_width, target_height)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')

playback_speed_factor = 0.5
original_frame_rate = 20
adjusted_frame_rate = int(original_frame_rate * playback_speed_factor)

video_writer = None
recording = False
recording_start_time = None

ulaanbaatar_tz = pytz.timezone('Asia/Ulaanbaatar')

while True:
now_ulaanbaatar = datetime.datetime.now(ulaanbaatar_tz)
current_hour = now_ulaanbaatar.hour

if 22 <= current_hour or current_hour < 10:
ret, frame = cap.read()
if not ret or frame is None:
print("Error: Could not read frame. Retrying...")
cap.stop()
time.sleep(1)
cap = VideoCaptureAsync("rtsp://admin:[email protected]:554/stream1").start()
continue

frame_count += 1
if frame_count % skip_frames != 0:
continue

if frame is not None:
frame = cv2.resize(frame, (target_width, target_height))

height, width, channels = frame.shape

blob = cv2.dnn.blobFromImage(frame, 0.00392, (320, 320), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)

class_ids = []
confidences = []
boxes = []

for output in outs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5 and classes[class_id] == "person":
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)

indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)

people_count = 0
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
people_count += 1

if people_count > 1:
if not recording:
recording = True
recording_start_time = time.time()
current_time = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
video_filename = f"video/{current_time}.mp4"
video_writer = cv2.VideoWriter(video_filename, fourcc, adjusted_frame_rate, frame_size)
if not video_writer.isOpened():
print(f"Error: Could not open video file for writing: {video_filename}")
file.write(f"{current_time}: Tailgating detected with {people_count} peoplen")
cv2.putText(frame, "Tailgating Detected!", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)
else:
cv2.putText(frame, "Recording...", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)

if recording and video_writer is not None:
video_writer.write(frame)
if time.time() - recording_start_time >= 10:
recording = False
video_writer.release()
video_writer = None

cv2.imshow('Video Feed', frame)

if cv2.waitKey(1) & 0xFF == ord('q'):
break

if recording and video_writer:
video_writer.release()
file.close()
cap.stop()
cv2.destroyAllWindows()
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.