From 78678df5d85b1e00039d47d6c50337bdca0b908c Mon Sep 17 00:00:00 2001 From: dpshekhawat Date: Fri, 22 Jul 2022 15:12:49 +0530 Subject: [PATCH 1/4] improved code structure --- main.py | 87 +++++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 56 insertions(+), 31 deletions(-) diff --git a/main.py b/main.py index bf35a33..348907a 100644 --- a/main.py +++ b/main.py @@ -2,68 +2,93 @@ import cv2 import os -from os import path import time from datetime import datetime # Opencv DNN net = cv2.dnn.readNet("dnn_model/yolov4-tiny.weights", "dnn_model/yolov4-tiny.cfg") model = cv2.dnn_DetectionModel(net) -model.setInputParams(size=(320, 320), scale=1/255) +model.setInputParams(size=(320, 320), scale=1 / 255) # Load Class list classes = [] + with open("dnn_model/classes.txt", "r") as f: for class_name in f.readlines(): class_name = class_name.strip() classes.append(class_name) -#print("Objects list") -#print("classes") - # Initialize camera cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) +# Storing current time in variable start_time = time.time() # Configurations -thres = 0.25 # confidence threshold -timeInterval = 5 # timeinterval for capturing +thres = os.environ.get(thres, 0.25) # confidence threshold +timeInterval = 5 # time interval for capturing capture = True # capture if True folder = "images/" # path to store images -if not os.path.exists(folder): - os.mkdir(folder) +try: + if not os.path.exists(folder): + os.mkdir(folder) +except PermissionError as pe: + print(pe) # Font/Box style used for labelling object detected font = cv2.FONT_HERSHEY_PLAIN font_scale = 1 thick = 2 -while True: - if cap.isOpened(): - # Get Frames - ret, frame = cap.read() - if ret: - # Object Detection - (class_ids, scores, bboxes) = model.detect(frame, confThreshold = thres, nmsThreshold=.4) - for class_id, score, bbox in zip(class_ids, scores, bboxes): - (x, y, w, h) = bbox - class_name = classes[class_id] - - cv2.putText(frame, class_name.capitalize(), (x,y - 10), font, font_scale, (0, 200, 50), thick) - cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 200, 50), thick) - # Uncomment below lines to see real time feed of object detection - #cv2.imshow("ObjectDetection", frame) - #cv2.waitKey(1) - if int(round(time.time()-start_time, 2)) >= timeInterval: - filename = "{}.png".format(datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) - cv2.imwrite(os.path.join(folder,filename), frame) - start_time = time.time() - if capture != True: - break +while cap.isOpened() and capture: + # Get Frames + ret, frame = cap.read() + + if ret: + # Object Detection + (class_ids, scores, bboxes) = model.detect( + frame, confThreshold=thres, nmsThreshold=0.4 + ) + for class_id, score, bbox in zip(class_ids, scores, bboxes): + (x, y, w, h) = bbox + class_name = classes[class_id] + + cv2.putText( + frame, + class_name.capitalize(), + (x, y - 10), + font, + font_scale, + (0, 200, 50), + thick, + ) + + cv2.rectangle( + frame, + (x, y), + (x + w, y + h), + (0, 200, 50), + thick, + ) + """ + Uncomment the below lines to see real-time + feed of object detection. + """ + #cv2.imshow("ObjectDetection", frame) + #cv2.waitKey(1) + + if int(round(time.time() - start_time, 2)) >= timeInterval: + filename = "{}.jpeg".format(datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) + cv2.imwrite(os.path.join(folder, filename), frame) + + # Resetting variable to current time + start_time = time.time() + + else: + break cap.release() cv2.destroyAllWindows() \ No newline at end of file From 848a93601eb8ebc0b4289c1f0774dfbd5c9cc595 Mon Sep 17 00:00:00 2001 From: dpshekhawat Date: Mon, 1 Aug 2022 23:39:03 +0530 Subject: [PATCH 2/4] set env variables --- main.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/main.py b/main.py index 348907a..923b848 100644 --- a/main.py +++ b/main.py @@ -26,11 +26,13 @@ # Storing current time in variable start_time = time.time() -# Configurations -thres = os.environ.get(thres, 0.25) # confidence threshold -timeInterval = 5 # time interval for capturing -capture = True # capture if True -folder = "images/" # path to store images +# Configurations with their default values set. +thres = os.getenv("THRES", 0.25) # confidence threshold +timeInterval = os.getenv("TIMEINT", 5) # time interval for capturing +capture = os.getenv("CAPTURE", True) # capture if True + +# Path to store images +folder = "images/" try: if not os.path.exists(folder): @@ -43,6 +45,7 @@ font_scale = 1 thick = 2 +# cap.isOpened() to check cap object has started capturing the frame. while cap.isOpened() and capture: # Get Frames ret, frame = cap.read() From 3a18039c280c38ed6a160abe24afa04f35a427da Mon Sep 17 00:00:00 2001 From: dpshekhawat Date: Thu, 4 Aug 2022 23:02:56 +0530 Subject: [PATCH 3/4] refactored code and performance improvements --- main.py | 102 +++++++++++++++++++++++++------------------------------- 1 file changed, 46 insertions(+), 56 deletions(-) diff --git a/main.py b/main.py index 923b848..1bbd829 100644 --- a/main.py +++ b/main.py @@ -23,27 +23,40 @@ cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) -# Storing current time in variable -start_time = time.time() +# Configurations +thres = os.getenv("THRES",0.25) # confidence threshold +timeInterval = os.getenv("TIMEINT",5) # time interval for capturing +capture = os.getenv("CAPTURE",True) # capture if True +folder = "images/" # path to store images -# Configurations with their default values set. -thres = os.getenv("THRES", 0.25) # confidence threshold -timeInterval = os.getenv("TIMEINT", 5) # time interval for capturing -capture = os.getenv("CAPTURE", True) # capture if True -# Path to store images -folder = "images/" +# Object Detection +def objdetect(frame, thres): + (class_ids, scores, bboxes) = model.detect( + frame, confThreshold=thres, nmsThreshold=0.4 + ) + for class_id, score, bbox in zip(class_ids, scores, bboxes): + (x, y, w, h) = bbox + class_name = classes[class_id] + + cv2.putText( + frame, + class_name.capitalize(), + (x, y - 10), + cv2.FONT_HERSHEY_PLAIN, + fontScale=1, + color=(0, 200, 50), + thickness=2, + ) -try: - if not os.path.exists(folder): - os.mkdir(folder) -except PermissionError as pe: - print(pe) + cv2.rectangle( + frame, + (x, y), + (x + w, y + h), + color=(0, 200, 50), + thickness=2, + ) -# Font/Box style used for labelling object detected -font = cv2.FONT_HERSHEY_PLAIN -font_scale = 1 -thick = 2 # cap.isOpened() to check cap object has started capturing the frame. while cap.isOpened() and capture: @@ -51,45 +64,22 @@ ret, frame = cap.read() if ret: - # Object Detection - (class_ids, scores, bboxes) = model.detect( - frame, confThreshold=thres, nmsThreshold=0.4 - ) - for class_id, score, bbox in zip(class_ids, scores, bboxes): - (x, y, w, h) = bbox - class_name = classes[class_id] - - cv2.putText( - frame, - class_name.capitalize(), - (x, y - 10), - font, - font_scale, - (0, 200, 50), - thick, - ) - - cv2.rectangle( - frame, - (x, y), - (x + w, y + h), - (0, 200, 50), - thick, - ) - """ - Uncomment the below lines to see real-time - feed of object detection. - """ - #cv2.imshow("ObjectDetection", frame) - #cv2.waitKey(1) - - if int(round(time.time() - start_time, 2)) >= timeInterval: - filename = "{}.jpeg".format(datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) - cv2.imwrite(os.path.join(folder, filename), frame) - - # Resetting variable to current time - start_time = time.time() - + # Error Handling + try: + if not os.path.exists(folder): + os.mkdir(folder) + except PermissionError as pe: + print("Cannot create folder "+str(pe)) + break + else: + objdetect(frame, thres) + + # Saving images to specified folder. + filename = "{}.jpeg".format(datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) + cv2.imwrite(os.path.join(folder, filename), frame) + + # Suspend execution for set time interval. + time.sleep(timeInterval) else: break From e58b6fca76155a4a77db73bc0880d536f8471a1e Mon Sep 17 00:00:00 2001 From: dpshekhawat Date: Fri, 5 Aug 2022 12:50:48 +0530 Subject: [PATCH 4/4] moved folder checking code outside loop --- main.py | 44 +++++++++++++++++++++----------------------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/main.py b/main.py index 1bbd829..ad088f9 100644 --- a/main.py +++ b/main.py @@ -5,6 +5,7 @@ import time from datetime import datetime + # Opencv DNN net = cv2.dnn.readNet("dnn_model/yolov4-tiny.weights", "dnn_model/yolov4-tiny.cfg") model = cv2.dnn_DetectionModel(net) @@ -31,7 +32,7 @@ # Object Detection -def objdetect(frame, thres): +def objDetect(frame, thres): (class_ids, scores, bboxes) = model.detect( frame, confThreshold=thres, nmsThreshold=0.4 ) @@ -58,30 +59,27 @@ def objdetect(frame, thres): ) -# cap.isOpened() to check cap object has started capturing the frame. -while cap.isOpened() and capture: - # Get Frames - ret, frame = cap.read() +try: + if not os.path.exists(folder): + os.mkdir(folder) +except PermissionError as pe: + print(f'Cannot create folder {pe}') +else: + while cap.isOpened() and capture: + # Get Frames + ret, frame = cap.read() - if ret: - # Error Handling - try: - if not os.path.exists(folder): - os.mkdir(folder) - except PermissionError as pe: - print("Cannot create folder "+str(pe)) - break - else: - objdetect(frame, thres) + if ret: + objDetect(frame, thres) - # Saving images to specified folder. - filename = "{}.jpeg".format(datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) - cv2.imwrite(os.path.join(folder, filename), frame) - - # Suspend execution for set time interval. - time.sleep(timeInterval) - else: - break + # Saving images to specified folder. + filename = "{}.jpeg".format(datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) + cv2.imwrite(os.path.join(folder, filename), frame) + + # Suspend execution for set time interval. + time.sleep(timeInterval) + else: + break cap.release() cv2.destroyAllWindows() \ No newline at end of file