diff --git a/README.rst b/README.rst index 85c4f1e..46e4a91 100644 --- a/README.rst +++ b/README.rst @@ -25,10 +25,19 @@ Features additional Utils ================ +- saveFrames +- detectionBox +- show_all_frames + +Detection Utils +=============== + - face detection - hand detection - eye detection (yet to be added) +add code examples here for each feature and utilities + .. |GitHub stars| image:: https://img.shields.io/github/stars/rishi23root/opencv.wrap.svg :target: https://github.com/rishi23root/opencv.wrap/stargazers .. |PyPI| image:: https://img.shields.io/pypi/v/opencv.wrap.svg diff --git a/newBuild.py b/newBuild.py index c76658b..4f4a26e 100644 --- a/newBuild.py +++ b/newBuild.py @@ -1,10 +1,13 @@ +# flake8: noqa: E501 # create a new build for the project -import os,re +import os +import re + def updated_version(old_version): # old_version = old_version.split('.') - major_release, minor_release, revision = (int(i) for i in old_version.split('.')) + major_release, minor_release, revision = (int(i) for i in old_version.split(".")) # if revision < 30: # revision += 1 # else: @@ -16,49 +19,56 @@ def updated_version(old_version): # major_release += 1 revision += 1 - return f'{major_release}.{minor_release}.{revision}' + return f"{major_release}.{minor_release}.{revision}" # update the version in the setup.py file -with open('setup.py','r') as f: +with open("setup.py", "r") as f: data = f.read() # read the version number from the setup.py file - VERSION = re.search(r"VERSION='(.*?)'", data).group(1) - print('[info]', 'old version', VERSION) - - FOLDER_NAME = re.search(r"name='(.*?)'", data).group(1) - print('[info]', 'FOLDER_NAME ', FOLDER_NAME) + VERSION = re.search(r'VERSION = "(.*?)"', data).group(1) + print("[info]", "old version", VERSION) + + FOLDER_NAME = re.search(r'name="(.*?)"', data).group(1) + print("[info]", "FOLDER_NAME ", FOLDER_NAME) # update the version number NEW_VERSION = updated_version(VERSION) - print('[info]', 'new version', NEW_VERSION) - data = data.replace(f"VERSION='{VERSION}'",f"VERSION='{NEW_VERSION}'") + print("[info]", "new version", NEW_VERSION) + data = data.replace(f'VERSION = "{VERSION}"', f'VERSION = "{NEW_VERSION}"') + isUpdated = re.search(r'VERSION = "(.*?)"', data).group(1) + print("[info]", "updated version", isUpdated) - # update the package list all_packages_old = re.search(r"install_requires=\[([\s\S]*?)\]", data).group(1) # print(all_packages_old) - install_requires = [i.replace('\n','').replace('==','>=') for i in open('requirements.txt', 'r').readlines()] - data = data.replace(f"install_requires=[{all_packages_old}]",f"install_requires={install_requires}") + install_requires = [ + i.replace("\n", "").replace("==", ">=") + for i in open("requirements.txt", "r").readlines() + ] + data = data.replace( + f"install_requires=[{all_packages_old}]", f"install_requires={install_requires}" + ) -with open('setup.py','w') as f: +with open("setup.py", "w") as f: f.write(data) # remove the old build from the dist folder -print('[info]', 'deleting old build',f'{os.getcwd()}/dist/{FOLDER_NAME}-{VERSION}.tar.gz') -os.system(f'rm {os.getcwd()}/dist/{FOLDER_NAME}-{VERSION}.tar.gz') +print( + "[info]", "deleting old build", f"{os.getcwd()}/dist/{FOLDER_NAME}-{VERSION}.tar.gz" +) +os.system(f"rm {os.getcwd()}/dist/{FOLDER_NAME}-{VERSION}.tar.gz") # convert the README.md to README.rst -print('[info]', 'converting README.md to README.rst') -os.system('pandoc --from=markdown --to=rst --output=README.rst README.md') - +print("[info]", "converting README.md to README.rst") +os.system("pandoc --from=markdown --to=rst --output=README.rst README.md") # create a new build -print('[info]', 'creating new build') -os.system(f'python3 setup.py sdist') +print("[info]", "creating new build") +os.system(f"python3 setup.py sdist") # upload to test pypi using twine -print('[info]', 'uploading to test pypi') +print("[info]", "uploading to test pypi") # os.system(f'twine upload --repository testpypi dist/{FOLDER_NAME}-{NEW_VERSION}.tar.gz') -os.system(f'twine upload dist/{FOLDER_NAME}-{NEW_VERSION}.tar.gz') \ No newline at end of file +os.system(f"twine upload dist/{FOLDER_NAME}-{NEW_VERSION}.tar.gz") diff --git a/opencv.wrap/__init__.py b/opencv.wrap/__init__.py deleted file mode 100644 index d65a3a1..0000000 --- a/opencv.wrap/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from cv2Decorator import cv2Decorator -import utils \ No newline at end of file diff --git a/opencv.wrap/test/1/test-img2.jfif b/opencv.wrap/test/1/test-img2.jfif deleted file mode 100644 index b2442f2..0000000 Binary files a/opencv.wrap/test/1/test-img2.jfif and /dev/null differ diff --git a/opencv.wrap/test/1/test5.jfif b/opencv.wrap/test/1/test5.jfif deleted file mode 100644 index 4cb8b83..0000000 Binary files a/opencv.wrap/test/1/test5.jfif and /dev/null differ diff --git a/opencv.wrap/test/old/Face/README.md b/opencv.wrap/test/old/Face/README.md deleted file mode 100644 index 1684b5f..0000000 --- a/opencv.wrap/test/old/Face/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Face Detection -Track the face in the frame - -face detector class can be improve 😁😁 diff --git a/opencv.wrap/test/old/Face/__pycache__/FaceDetecter.cpython-310.pyc b/opencv.wrap/test/old/Face/__pycache__/FaceDetecter.cpython-310.pyc deleted file mode 100644 index 54fb667..0000000 Binary files a/opencv.wrap/test/old/Face/__pycache__/FaceDetecter.cpython-310.pyc and /dev/null differ diff --git a/opencv.wrap/test/old/Face/__pycache__/cv2Decorator.cpython-310.pyc b/opencv.wrap/test/old/Face/__pycache__/cv2Decorator.cpython-310.pyc deleted file mode 100644 index 0bd3cd6..0000000 Binary files a/opencv.wrap/test/old/Face/__pycache__/cv2Decorator.cpython-310.pyc and /dev/null differ diff --git a/opencv.wrap/test/old/Face/cv2Decorator.py b/opencv.wrap/test/old/Face/cv2Decorator.py deleted file mode 100644 index f4654ac..0000000 --- a/opencv.wrap/test/old/Face/cv2Decorator.py +++ /dev/null @@ -1,345 +0,0 @@ -# cv2Decorator.py -from os import path -import cv2 -import time -from time import sleep as nap -from functools import wraps -import traceback -from pathlib import Path - -class cv2Decorator: - def TotalTimeTaken(show = False): - """Calculate the total time taken in executing a function""" - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - try : - start = time.perf_counter() - return_data = function(*args, **kwargs) - if show: - time_taken = time.perf_counter() - start - in_mins = divmod(time_taken,60) - nap(1) - print("Time taken --> ", - ":".join( - map( - lambda x : str(int(x)), - [in_mins[1],*divmod(in_mins[0],60)[::-1]][::-1] - )) - ,"Hours") - return return_data - except Exception as e: - print(e) - return wrapper - return inner_wrapper - - previousTime = 0 # used in calculating - def CalculateFps(draw=False, - org = (5, 25), - font = cv2.FONT_HERSHEY_PLAIN, - fontScale = 2, - color = (255, 0, 0), - thickness = 2): - """Draw the fps of the frame on the image corner""" - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - # count the frames - # run the funtion - img = function(*args, **kwargs) - # calculate the fps and update it on the screen if needed - if draw : - currentTime = time.time() - # print(currentTime,Decorate.previousTime) ### testing - try: - fps = 1 / (currentTime - __class__.previousTime) - except ZeroDivisionError: - fps = 0 - finally : - __class__.previousTime = currentTime - - # get the image_size and put the text at right top - try : - shape = img.shape - cv2.putText( - img, - f'FPS:{str(int(fps)).rjust(3)}', - org =org , - fontFace =font, - fontScale = fontScale , - color =color, - thickness =thickness ) - except : - pass - finally : - return img - else : - return img - - return wrapper - return inner_wrapper - - def MirrorFrame(axis = 1): - """flip the frame from its y axis take axis as args""" - """0 means flipping around the x-axis - positive value (for example, 1) means flipping around y-axis. (mirror) - Negative value (for example, -1) means flipping around both axes.""" - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - try : - kwargs['frame'] = cv2.flip(kwargs['frame'], axis) - except KeyError: - kwargs['img'] = cv2.flip(kwargs['img'], axis) - except KeyError: - kwargs['image'] = cv2.flip(kwargs['image'], axis) - finally : - return function(*args,**kwargs) - return wrapper - return inner_wrapper - - def ConvertCOLOR(converter = cv2.COLOR_RGB2BGR): - """Convert COLOR of the frame to the converter provided""" - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - if converter : - try : - kwargs['frame'] = cv2.cvtColor(kwargs['frame'], converter) - except KeyError: - kwargs['img'] = cv2.cvtColor(kwargs['img'], converter) - except KeyError: - kwargs['image'] = cv2.cvtColor(kwargs['image'], converter) - finally : - return function(*args,**kwargs) - else : - return function(*args,**kwargs) - return wrapper - return inner_wrapper - - # simple form - def ReadCamAndShowFrames(idCam = 0, - wCam = 640, - hCam = 480 , - frameTitle:str = "Cam feed", - keysToBreak : list = [81,27]): - """Decorated funtion will can pass a args['frame'] in defining the function """ - """It makes the use webcam in cv2 easier (super simple form) - idCam cam id (default = 0), - wCam cam frame width (default = 640), if set to None it will not be update from cam - hCam cam frame height (default = 480), if set to None it will not be update from cam - frameTitle show title on the frames - keysToBreak keys to break frames (default = 81,27) - """ - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - try: - # open the webcam capture of the - try : - cap = cv2.VideoCapture(idCam) - # may cause error in reading - except : - # can cause significant frame drop - print("Using cv2.CAP_DSHOW") - cap = cv2.VideoCapture(idCam,cv2.CAP_DSHOW) - - cap.set(3, wCam) - cap.set(4, hCam) - while True: - # read image - success, frame = cap.read() - if success : - # call the function - if function : - frame = function(frame=frame) - - # show the frames - cv2.imshow(frameTitle, frame) - key = cv2.waitKey(1) - if key in keysToBreak: - cv2.destroyAllWindows() - break - else: - raise Exception("Error in reading the Frame") - - except Exception as e : - print(traceback.format_exc()) - # print(getattr(e, 'message', repr(e))) - # print(getattr(e, 'message', str(e))) - finally: - cap.release() - cv2.destroyAllWindows() - return wrapper - return inner_wrapper - - # with specific detector - def ReadCamAddDetectShowFrames( - detector = (None,), - idCam = 0, - wCam = 640, - hCam = 480 , - frameTitle:str = "Cam feed", - keysToBreak : list = [81,27]): - """Decorated funtion will can pass a args['frame','detector'] in defining the function """ - """It will call the detector class if any with its args if any and initiate the call the return the called function - detector detector to use in detection (default = (None,)), - idCam cam id (default = 0), - wCam cam frame width (default = 640), if set to None it will not be update from cam - hCam cam frame height (default = 480), if set to None it will not be update from cam - frameTitle show title on the frames - keysToBreak keys to break frames (default = 81,27) - """ - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - try: - # open the webcam capture of the - try : - cap = cv2.VideoCapture(idCam) - # may cause error in reading - except : - # can cause significant frame drop - print("Using cv2.CAP_DSHOW") - cap = cv2.VideoCapture(idCam,cv2.CAP_DSHOW) - - # use of the detector funtion, whaterver class is provied here if any - if detector[0]: - detectorFuntion = detector[0](*detector[1:]) # to detect and use different function in the hand detector class - else : - detectorFuntion = None - cap.set(3, wCam) - cap.set(4, hCam) - while True: - # read image - success, frame = cap.read() - if success : - # call the function - if function : - frame = function(frame=frame,detector=detectorFuntion) - - # show the frames - cv2.imshow(frameTitle, frame) - key = cv2.waitKey(1) - if key in keysToBreak: - cv2.destroyAllWindows() - break - else: - raise Exception("Error in reading the Frame") - - except Exception as e : - print(traceback.format_exc()) - # print(getattr(e, 'message', repr(e))) - # print(getattr(e, 'message', str(e))) - finally: - cap.release() - cv2.destroyAllWindows() - return wrapper - return inner_wrapper - - # with specific detector - def ReadCamAddDetectShowFrames_video( - videoPath: Path = "", - detector = (None,), - idCam = 0, - frameTitle:str = "video feed", - keysToBreak : list = [81,27]): - """Decorated funtion will can pass a args['frame','detector'] in defining the function """ - """It will call the detector class if any with its args if any and initiate the call the return the called function - videoPath path to the video - detector detector to use in detection (default = (None,)), - idCam cam id (default = 0), - frameTitle show title on the frames - keysToBreak keys to break frames (default = 81,27) - """ - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - try: - # open the webcam capture of the - try : - cap = cv2.VideoCapture(videoPath) - # may cause error in reading - except : - # can cause significant frame drop - print("Using cv2.CAP_DSHOW") - cap = cv2.VideoCapture(videoPath,cv2.CAP_DSHOW) - - # use of the detector funtion, whaterver class is provied here if any - if detector[0]: - detectorFuntion = detector[0](*detector[1:]) # to detect and use different function in the hand detector class - else : - detectorFuntion = None - while cap.isOpened(): - # read image - success, frame = cap.read() - if success : - # call the function - if function : - frame = function(frame=frame,detector=detectorFuntion) - - # show the frames - cv2.imshow(frameTitle, frame) - key = cv2.waitKey(1) - if key in keysToBreak: - cv2.destroyAllWindows() - break - else: - break - - except Exception as e : - print(traceback.format_exc()) - # print(getattr(e, 'message', repr(e))) - # print(getattr(e, 'message', str(e))) - finally: - cap.release() - cv2.destroyAllWindows() - return wrapper - return inner_wrapper - - # default decorator for more (template) - # def default_decorator(args1 = 1): - # def inner_wrapper(function): - # @wraps(function) - # def wrapper(*args, **kwargs): - # # run the funtion - # # return function(*args,**kwargs) - # return wrapper - # return inner_wrapper - - -# # call only one funtion to run all the basics things -if __name__ == "__main__": - # example 1 - # a = 0 - # @cv2Decorator.TotalTimeTaken(show = True) - # @cv2Decorator.ReadCamAndShowFrames() - # @cv2Decorator.CalculateFps(draw = True) - # @cv2Decorator.MirrorFrame() - # def all_actions(frame): - # # update to get all different types of action on the frames - # a += 1 - # return frame - - # all_actions() - - # example 2 # face detectection - @cv2Decorator.TotalTimeTaken(show=True) - @cv2Decorator.ReadCamAddDetectShowFrames(detector=(cv2.CascadeClassifier,cv2.data.haarcascades+"haarcascade_frontalface_default.xml")) - @cv2Decorator.CalculateFps(draw = True) - @cv2Decorator.MirrorFrame() - def all_actions(frame,detector): - gray_img = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) - - # detect face from trainerd data and detectMultiScale use to deteat every size of face - face_coordinate = detector.detectMultiScale(gray_img,1.3,5) - # extracting cordinates (x,y,width,height) - # (x,y,w,h) = face_coordinate[0] - for i in face_coordinate: - (x,y,w,h) = i - # drawing rectangle on the image - cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2) - - return frame - - all_actions() diff --git a/opencv.wrap/test/old/Hand/README.md b/opencv.wrap/test/old/Hand/README.md deleted file mode 100644 index 1402db7..0000000 --- a/opencv.wrap/test/old/Hand/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# HandTracker -Track the hand in the frame - -HandTracker class can be improve 😁😁 \ No newline at end of file diff --git a/opencv.wrap/test/old/Hand/__pycache__/HandTracker.cpython-310.pyc b/opencv.wrap/test/old/Hand/__pycache__/HandTracker.cpython-310.pyc deleted file mode 100644 index bbea723..0000000 Binary files a/opencv.wrap/test/old/Hand/__pycache__/HandTracker.cpython-310.pyc and /dev/null differ diff --git a/opencv.wrap/test/old/Hand/__pycache__/cv2Decorator.cpython-310.pyc b/opencv.wrap/test/old/Hand/__pycache__/cv2Decorator.cpython-310.pyc deleted file mode 100644 index 320d8c6..0000000 Binary files a/opencv.wrap/test/old/Hand/__pycache__/cv2Decorator.cpython-310.pyc and /dev/null differ diff --git a/opencv.wrap/test/old/Hand/cv2Decorator.py b/opencv.wrap/test/old/Hand/cv2Decorator.py deleted file mode 100644 index 44394c2..0000000 --- a/opencv.wrap/test/old/Hand/cv2Decorator.py +++ /dev/null @@ -1,283 +0,0 @@ -# cv2Decorator.py -import cv2 -import time -from time import sleep as nap -from functools import wraps -import traceback - -class cv2Decorator: - def TotalTimeTaken(show = False): - """Calculate the total time taken in executing a function""" - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - try : - start = time.perf_counter() - return_data = function(*args, **kwargs) - if show: - time_taken = time.perf_counter() - start - in_mins = divmod(time_taken,60) - nap(1) - print("Time taken --> ", - ":".join( - map( - lambda x : str(int(x)), - [in_mins[1],*divmod(in_mins[0],60)[::-1]][::-1] - )) - ,"Hours") - return return_data - except Exception as e: - print(e) - return wrapper - return inner_wrapper - - previousTime = 0 # used in calculating - def CalculateFps(draw=False, - org = (5, 25), - font = cv2.FONT_HERSHEY_PLAIN, - fontScale = 2, - color = (255, 0, 0), - thickness = 2): - """Draw the fps of the frame on the image corner""" - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - # count the frames - # run the funtion - img = function(*args, **kwargs) - # calculate the fps and update it on the screen if needed - if draw : - currentTime = time.time() - # print(currentTime,Decorate.previousTime) ### testing - try: - fps = 1 / (currentTime - __class__.previousTime) - except ZeroDivisionError: - fps = 0 - finally : - __class__.previousTime = currentTime - - # get the image_size and put the text at right top - try : - shape = img.shape - cv2.putText( - img, - f'FPS:{str(int(fps)).rjust(3)}', - org =org , - fontFace =font, - fontScale = fontScale , - color =color, - thickness =thickness ) - except : - pass - finally : - return img - else : - return img - - return wrapper - return inner_wrapper - - def MirrorFrame(axis = 1): - """flip the frame from its y axis take axis as args""" - """0 means flipping around the x-axis - positive value (for example, 1) means flipping around y-axis. (mirror) - Negative value (for example, -1) means flipping around both axes.""" - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - try : - kwargs['frame'] = cv2.flip(kwargs['frame'], axis) - except KeyError: - kwargs['img'] = cv2.flip(kwargs['img'], axis) - except KeyError: - kwargs['image'] = cv2.flip(kwargs['image'], axis) - finally : - return function(*args,**kwargs) - return wrapper - return inner_wrapper - - def ConvertCOLOR(converter = cv2.COLOR_RGB2BGR): - """Convert COLOR of the frame to the converter provided""" - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - if converter : - try : - kwargs['frame'] = cv2.cvtColor(kwargs['frame'], converter) - except KeyError: - kwargs['img'] = cv2.cvtColor(kwargs['img'], converter) - except KeyError: - kwargs['image'] = cv2.cvtColor(kwargs['image'], converter) - finally : - return function(*args,**kwargs) - else : - return function(*args,**kwargs) - return wrapper - return inner_wrapper - - # simple form - def ReadCamAndShowFrames(idCam = 0, - wCam = 640, - hCam = 480 , - frameTitle:str = "Cam feed", - keysToBreak : list = [81,27]): - """Decorated funtion will can pass a args['frame'] in defining the function """ - """It makes the use webcam in cv2 easier (super simple form) - idCam cam id (default = 0), - wCam cam frame width (default = 640), if set to None it will not be update from cam - hCam cam frame height (default = 480), if set to None it will not be update from cam - frameTitle show title on the frames - keysToBreak keys to break frames (default = 81,27) - """ - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - try: - # open the webcam capture of the - try : - cap = cv2.VideoCapture(idCam) - # may cause error in reading - except : - # can cause significant frame drop - print("Using cv2.CAP_DSHOW") - cap = cv2.VideoCapture(idCam,cv2.CAP_DSHOW) - - cap.set(3, wCam) - cap.set(4, hCam) - while True: - # read image - success, frame = cap.read() - if success : - # call the function - if function : - frame = function(frame=frame) - - # show the frames - cv2.imshow(frameTitle, frame) - key = cv2.waitKey(1) - if key in keysToBreak: - cv2.destroyAllWindows() - break - else: - raise Exception("Error in reading the Frame") - - except Exception as e : - print(traceback.format_exc()) - # print(getattr(e, 'message', repr(e))) - # print(getattr(e, 'message', str(e))) - finally: - cap.release() - cv2.destroyAllWindows() - return wrapper - return inner_wrapper - - # hand detection form - def ReadCamAddDetectShowFrames( - detector = (None,), - idCam = 0, - wCam = 640, - hCam = 480 , - frameTitle:str = "Cam feed", - keysToBreak : list = [81,27]): - """Decorated funtion will can pass a args['frame','detector'] in defining the function """ - """It will call the detector class if any with its args if any and initiate the call the return the called function - detector detector to use in detection (default = (None,)), - idCam cam id (default = 0), - wCam cam frame width (default = 640), if set to None it will not be update from cam - hCam cam frame height (default = 480), if set to None it will not be update from cam - frameTitle show title on the frames - keysToBreak keys to break frames (default = 81,27) - """ - def inner_wrapper(function): - @wraps(function) - def wrapper(*args, **kwargs): - try: - # open the webcam capture of the - try : - cap = cv2.VideoCapture(idCam) - # may cause error in reading - except : - # can cause significant frame drop - print("Using cv2.CAP_DSHOW") - cap = cv2.VideoCapture(idCam,cv2.CAP_DSHOW) - - # use of the detector funtion, whaterver class is provied here if any - if detector[0]: - detectorFuntion = detector[0](*detector[1:]) # to detect and use different function in the hand detector class - else : - detectorFuntion = None - cap.set(3, wCam) - cap.set(4, hCam) - while True: - # read image - success, frame = cap.read() - if success : - # call the function - if function : - frame = function(frame=frame,detector=detectorFuntion) - - # show the frames - cv2.imshow(frameTitle, frame) - key = cv2.waitKey(1) - if key in keysToBreak: - cv2.destroyAllWindows() - break - else: - raise Exception("Error in reading the Frame") - - except Exception as e : - print(traceback.format_exc()) - # print(getattr(e, 'message', repr(e))) - # print(getattr(e, 'message', str(e))) - finally: - cap.release() - cv2.destroyAllWindows() - return wrapper - return inner_wrapper - - # default decorator for more (template) - # def default_decorator(args1 = 1): - # def inner_wrapper(function): - # @wraps(function) - # def wrapper(*args, **kwargs): - # # run the funtion - # # return function(*args,**kwargs) - # return wrapper - # return inner_wrapper - - -# # call only one funtion to run all the basics things -if __name__ == "__main__": - # example 1 - # a = 0 - # @cv2Decorator.TotalTimeTaken(show = True) - # @cv2Decorator.ReadCamAndShowFrames() - # @cv2Decorator.CalculateFps(draw = True) - # @cv2Decorator.MirrorFrame() - # def all_actions(frame): - # # update to get all different types of action on the frames - # a += 1 - # return frame - - # all_actions() - - # example 2 # face detectection - @cv2Decorator.TotalTimeTaken(show=True) - @cv2Decorator.ReadCamAddDetectShowFrames(detector=(cv2.CascadeClassifier,cv2.data.haarcascades+"haarcascade_frontalface_default.xml")) - @cv2Decorator.CalculateFps(draw = True) - @cv2Decorator.MirrorFrame() - def all_actions(frame,detector): - gray_img = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) - - # detect face from trainerd data and detectMultiScale use to deteat every size of face - face_coordinate = detector.detectMultiScale(gray_img,1.3,5) - # extracting cordinates (x,y,width,height) - # (x,y,w,h) = face_coordinate[0] - for i in face_coordinate: - (x,y,w,h) = i - # drawing rectangle on the image - cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2) - - return frame - - all_actions() diff --git a/opencv.wrap/test/old/extract_image_from_video.py b/opencv.wrap/test/old/extract_image_from_video.py deleted file mode 100644 index b079280..0000000 --- a/opencv.wrap/test/old/extract_image_from_video.py +++ /dev/null @@ -1,25 +0,0 @@ -import cv2,os - -def extract_image(video:str,fps:int,direction): - # 1. get videos frames - if not os.path.exists(direction) : os.mkdir(direction) - vidcap = cv2.VideoCapture('a.mp4') - default_fps = round(vidcap.get(cv2.CAP_PROP_FPS)) - print("default fps of video is --> ",default_fps) - if fps < default_fps : steps = round(default_fps/fps) - else : steps = 1 - print("new fps of video is --> ",int(default_fps/steps)) - folder_path = os.path.join(direction,'image%s.jpg') - success = True - while success: - count = int(vidcap.get(1)) - success,frame = vidcap.read() - if count%steps == 0 : - try : cv2.imwrite(folder_path.replace("%s",str(count)),frame) # save file - except : pass # last frame is none - -if __name__=='__main__': - video = 'a.mp4' - fps = 5 - image_folder = os.path.join(os.getcwd(),'images') - extract_image(video,fps,image_folder) \ No newline at end of file diff --git a/opencv.wrap/test/old/face.py b/opencv.wrap/test/old/face.py deleted file mode 100644 index b205031..0000000 --- a/opencv.wrap/test/old/face.py +++ /dev/null @@ -1,33 +0,0 @@ -import cv2 -import sys -# run python face.py {image name} to get results - -def face_finder(img): - # load pre trained data - trained_data =cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") - - # using imread read image inn cv2 - img = cv2.imread(img) - - # convert into grayscale take 2 args image and color - # gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) - - # detect face from trainerd data and detectMultiScale use to deteat every size of face - # face_coordinate = trained_data.detectMultiScale(cv2.cvtColor(gray_img)) - face_coordinate = trained_data.detectMultiScale(cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)) - - # extracting cordinates (x,y,width,height) - # (x,y,w,h) = face_coordinate[0] - print('there are min people present :',len(face_coordinate)) - for i in face_coordinate: - (x,y,w,h) = i - # drawing rectangle on the image - cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) - - # show image in cv2 take 2 arrg =window name , image - cv2.imshow('image representation',img) - # wait to close the window to move further program - cv2.waitKey() - -# if __name__ == '__main__': - # face_finder(sys.argv[1]) \ No newline at end of file diff --git a/opencv.wrap/test/old/opencv_webcam.py b/opencv.wrap/test/old/opencv_webcam.py deleted file mode 100644 index 739a38d..0000000 --- a/opencv.wrap/test/old/opencv_webcam.py +++ /dev/null @@ -1,37 +0,0 @@ -import cv2 - -def main(camera_number): - # load pre trained data - trained_data =cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") - # using-webcam - webcam = cv2.VideoCapture(camera_number) - print('press esc for exit') - - while True: - # extracting-live-data-from-web-cam - boolen,img = webcam.read() - # convert into grayscale take 2 args image and color - gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) - - # detect face from trainerd data and detectMultiScale use to deteat every size of face - face_coordinate = trained_data.detectMultiScale(gray_img,1.3,5) - # extracting cordinates (x,y,width,height) - # (x,y,w,h) = face_coordinate[0] - for i in face_coordinate: - (x,y,w,h) = i - # drawing rectangle on the image - cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) - - # show image in cv2 take 2 arrg =window name , image - cv2.imshow('image representation',img) - # wait to close the window to move further program - key = cv2.waitKey(1) - if key == 81 or key == 27 : - cv2.destroyAllWindows() - break - - - - -if __name__ == '__main__': - main(0) \ No newline at end of file diff --git a/opencv.wrap/test/test.py b/opencv.wrap/test/test.py deleted file mode 100644 index 01fe455..0000000 --- a/opencv.wrap/test/test.py +++ /dev/null @@ -1,82 +0,0 @@ -import cv2 -import mediapipe as mp -mp_drawing = mp.solutions.drawing_utils -mp_drawing_styles = mp.solutions.drawing_styles -mp_hands = mp.solutions.hands - -# For static images: -IMAGE_FILES = [] -with mp_hands.Hands( - static_image_mode=True, - max_num_hands=2, - min_detection_confidence=0.5) as hands: - for idx, file in enumerate(IMAGE_FILES): - # Read an image, flip it around y-axis for correct handedness output (see - # above). - image = cv2.flip(cv2.imread(file), 1) - # Convert the BGR image to RGB before processing. - results = hands.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) - - # Print handedness and draw hand landmarks on the image. - print('Handedness:', results.multi_handedness) - if not results.multi_hand_landmarks: - continue - image_height, image_width, _ = image.shape - annotated_image = image.copy() - for hand_landmarks in results.multi_hand_landmarks: - print('hand_landmarks:', hand_landmarks) - print( - f'Index finger tip coordinates: (', - f'{hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].x * image_width}, ' - f'{hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].y * image_height})' - ) - mp_drawing.draw_landmarks( - annotated_image, - hand_landmarks, - mp_hands.HAND_CONNECTIONS, - mp_drawing_styles.get_default_hand_landmarks_style(), - mp_drawing_styles.get_default_hand_connections_style()) - cv2.imwrite( - '/tmp/annotated_image' + str(idx) + '.png', cv2.flip(annotated_image, 1)) - # Draw hand world landmarks. - if not results.multi_hand_world_landmarks: - continue - for hand_world_landmarks in results.multi_hand_world_landmarks: - mp_drawing.plot_landmarks( - hand_world_landmarks, mp_hands.HAND_CONNECTIONS, azimuth=5) - -# For webcam input: -cap = cv2.VideoCapture(0) -with mp_hands.Hands( - model_complexity=0, - min_detection_confidence=0.5, - min_tracking_confidence=0.5) as hands: - while cap.isOpened(): - success, image = cap.read() - if not success: - print("Ignoring empty camera frame.") - # If loading a video, use 'break' instead of 'continue'. - continue - - # To improve performance, optionally mark the image as not writeable to - # pass by reference. - image.flags.writeable = False - image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) - results = hands.process(image) - - # Draw the hand annotations on the image. - image.flags.writeable = True - image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) - if results.multi_hand_landmarks: - for hand_landmarks in results.multi_hand_landmarks: - mp_drawing.draw_landmarks( - image, - hand_landmarks, - mp_hands.HAND_CONNECTIONS, - mp_drawing_styles.get_default_hand_landmarks_style(), - mp_drawing_styles.get_default_hand_connections_style()) - # Flip the image horizontally for a selfie-view display. - cv2.imshow('MediaPipe Hands', cv2.flip(image, 1)) - if cv2.waitKey(5) & 0xFF == 27: - break -cap.release() \ No newline at end of file diff --git a/opencv_wrap/__init__.py b/opencv_wrap/__init__.py new file mode 100644 index 0000000..41e0ac0 --- /dev/null +++ b/opencv_wrap/__init__.py @@ -0,0 +1,2 @@ +from .cv2Decorator import cv2Decorator +from . import utils, detectors \ No newline at end of file diff --git a/opencv.wrap/cv2Decorator.py b/opencv_wrap/cv2Decorator.py similarity index 100% rename from opencv.wrap/cv2Decorator.py rename to opencv_wrap/cv2Decorator.py diff --git a/opencv.wrap/detectors/Face.py b/opencv_wrap/detectors/Face.py similarity index 83% rename from opencv.wrap/detectors/Face.py rename to opencv_wrap/detectors/Face.py index cbbdff4..876e112 100644 --- a/opencv.wrap/detectors/Face.py +++ b/opencv_wrap/detectors/Face.py @@ -1,7 +1,7 @@ # flake8: noqa: E501 import cv2 -from utils.base import Detector -from utils.util import detectionBox +from opencv_wrap.utils import Detector +from opencv_wrap.utils.helper import detectionBox import mediapipe as mp @@ -11,14 +11,11 @@ # functionalities -# 1/ get face detection -# 2/ get face landmarks ractangle -# 3/ get face landmarks points # 4/ save faces and save them them in a folder # 5/ compare faces from folder and current face -class Face(Detector): +class FaceDetector(Detector): def __init__( self, @@ -151,12 +148,28 @@ def drawLandmarks(self, processedFrame, frame): connection_drawing_spec=mp_drawing_styles.get_default_face_mesh_iris_connections_style(), ) + def saveFaces(self, frame, face_boxes, destination="./test2"): + """save the detected faces in the destination folder + + Parameters + ---------- + frame : np.array + frame to save the faces from + face_boxes : list + list of face boxes (x,y,w,h) + destination : str, optional + destination to save the faces, by default "./test2" + """ + for i, face_box in enumerate(face_boxes): + x, y, w, h = face_box + face = frame[y : y + h, x : x + w] + cv2.imwrite(f"{destination}/face_{i}.jpg", face) if __name__ == "__main__": - d1 = Face(verbose=True) - d2 = Face() + d1 = FaceDetector(verbose=True) + d2 = FaceDetector() - image = cv2.imread("./test/test.jpg") + image = cv2.imread("./testMedia/test.jpg") print(d1.detect(image)) - print("isinstance of face :", isinstance(d1, Face), end=" ") + print("isinstance of face :", isinstance(d1, FaceDetector), end=" ") print("is i1 == i2 :", d1 == d2) diff --git a/opencv.wrap/detectors/Hand.py b/opencv_wrap/detectors/Hand.py similarity index 100% rename from opencv.wrap/detectors/Hand.py rename to opencv_wrap/detectors/Hand.py diff --git a/opencv_wrap/detectors/__init__.py b/opencv_wrap/detectors/__init__.py new file mode 100644 index 0000000..fcbdc67 --- /dev/null +++ b/opencv_wrap/detectors/__init__.py @@ -0,0 +1,2 @@ +from .Face import FaceDetector as Face +from .Hand import handDetector as Hand diff --git a/opencv.wrap/test/old/Face/FaceDetecter.py b/opencv_wrap/testMedia/oldCode/Face/FaceDetecter.py similarity index 95% rename from opencv.wrap/test/old/Face/FaceDetecter.py rename to opencv_wrap/testMedia/oldCode/Face/FaceDetecter.py index c01ff07..20a62b5 100644 --- a/opencv.wrap/test/old/Face/FaceDetecter.py +++ b/opencv_wrap/testMedia/oldCode/Face/FaceDetecter.py @@ -1,7 +1,4 @@ -from typing import overload import cv2 -import mediapipe as mp - class Face: padding = 10 diff --git a/opencv.wrap/test/old/Face/main.py b/opencv_wrap/testMedia/oldCode/Face/main.py similarity index 100% rename from opencv.wrap/test/old/Face/main.py rename to opencv_wrap/testMedia/oldCode/Face/main.py diff --git a/opencv.wrap/test/old/Hand/HandTracker.py b/opencv_wrap/testMedia/oldCode/Hand/HandTracker.py similarity index 100% rename from opencv.wrap/test/old/Hand/HandTracker.py rename to opencv_wrap/testMedia/oldCode/Hand/HandTracker.py diff --git a/opencv.wrap/test/old/Hand/main.py b/opencv_wrap/testMedia/oldCode/Hand/main.py similarity index 100% rename from opencv.wrap/test/old/Hand/main.py rename to opencv_wrap/testMedia/oldCode/Hand/main.py diff --git a/opencv.wrap/test/test.jpg b/opencv_wrap/testMedia/test.jpg similarity index 100% rename from opencv.wrap/test/test.jpg rename to opencv_wrap/testMedia/test.jpg diff --git a/opencv.wrap/test/test.mp4 b/opencv_wrap/testMedia/test.mp4 similarity index 100% rename from opencv.wrap/test/test.mp4 rename to opencv_wrap/testMedia/test.mp4 diff --git a/opencv.wrap/test/1/test3.jpg b/opencv_wrap/testMedia/test3.jpg similarity index 100% rename from opencv.wrap/test/1/test3.jpg rename to opencv_wrap/testMedia/test3.jpg diff --git a/opencv.wrap/test/1/test4.jpg b/opencv_wrap/testMedia/test4.jpg similarity index 100% rename from opencv.wrap/test/1/test4.jpg rename to opencv_wrap/testMedia/test4.jpg diff --git a/opencv.wrap/test/1/test6.jpg b/opencv_wrap/testMedia/test6.jpg similarity index 100% rename from opencv.wrap/test/1/test6.jpg rename to opencv_wrap/testMedia/test6.jpg diff --git a/opencv_wrap/utils/__init__.py b/opencv_wrap/utils/__init__.py new file mode 100644 index 0000000..773cfc4 --- /dev/null +++ b/opencv_wrap/utils/__init__.py @@ -0,0 +1 @@ +from .base import * \ No newline at end of file diff --git a/opencv.wrap/utils/base.py b/opencv_wrap/utils/base.py similarity index 100% rename from opencv.wrap/utils/base.py rename to opencv_wrap/utils/base.py diff --git a/opencv.wrap/utils/util.py b/opencv_wrap/utils/helper.py similarity index 99% rename from opencv.wrap/utils/util.py rename to opencv_wrap/utils/helper.py index 75eec3b..d07e738 100644 --- a/opencv.wrap/utils/util.py +++ b/opencv_wrap/utils/helper.py @@ -5,7 +5,6 @@ import numpy as np import time - def saveFrame(frame: str, count: int, destination: Path): """save frame to destination folder with count as name of the file diff --git a/setup.py b/setup.py index e808b0f..e255c45 100644 --- a/setup.py +++ b/setup.py @@ -1,10 +1,11 @@ +# flake8: noqa: E501 from setuptools import setup, find_packages -VERSION = "0.0.3" +VERSION = "0.0.5" DESCRIPTION = "working with opencv can be quite a hussel, a lot of boiler code, nested functions for specific use cases, this package is designed to make it easier to work with opencv, while focusing on the main task in hand." setup( - name="opencv.wrap", + name="opencv-wrap", version=VERSION, description=DESCRIPTION, long_description=open("README.rst").read(), @@ -23,33 +24,7 @@ "Programming Language :: Python :: 3.10", ], packages=find_packages(), - install_requires=[ - "absl-py>=2.1.0", - "attrs>=23.2.0", - "cffi>=1.16.0", - "contourpy>=1.2.0", - "cycler>=0.12.1", - "flatbuffers>=23.5.26", - "fonttools>=4.49.0", - "jax>=0.4.24", - "kiwisolver>=1.4.5", - "matplotlib>=3.8.3", - "mediapipe>=0.10.10", - "ml-dtypes>=0.3.2", - "numpy>=1.26.4", - "opencv-contrib-python>=4.9.0.80", - "opencv-python>=4.9.0.80", - "opt-einsum>=3.3.0", - "packaging>=23.2", - "pillow>=10.2.0", - "protobuf>=3.20.3", - "pycparser>=2.21", - "pyparsing>=3.1.1", - "python-dateutil>=2.8.2", - "scipy>=1.12.0", - "six>=1.16.0", - "sounddevice>=0.4.6", - ], + install_requires=['absl-py>=2.1.0', 'attrs>=23.2.0', 'cffi>=1.16.0', 'contourpy>=1.2.0', 'cycler>=0.12.1', 'flatbuffers>=23.5.26', 'fonttools>=4.49.0', 'jax>=0.4.24', 'kiwisolver>=1.4.5', 'matplotlib>=3.8.3', 'mediapipe>=0.10.10', 'ml-dtypes>=0.3.2', 'numpy>=1.26.4', 'opencv-contrib-python>=4.9.0.80', 'opencv-python>=4.9.0.80', 'opt-einsum>=3.3.0', 'packaging>=23.2', 'pillow>=10.2.0', 'protobuf>=3.20.3', 'pycparser>=2.21', 'pyparsing>=3.1.1', 'python-dateutil>=2.8.2', 'scipy>=1.12.0', 'six>=1.16.0', 'sounddevice>=0.4.6'], zip_safe=False, entry_points={ "console_scripts": ["pyresparser=pyresparser.command_line:main"], diff --git a/test/test.py b/test/test.py new file mode 100644 index 0000000..000f880 --- /dev/null +++ b/test/test.py @@ -0,0 +1,91 @@ +# flake8: noqa: E501 +from opencv_wrap import cv2Decorator +import cv2 +from opencv_wrap.detectors import Face +from opencv_wrap.utils.helper import saveFrame, detectionBox, show_all_frames, clipImage + + +# reading a single frame from the directory + +# @cv2Decorator.TotalTimeTaken(show=True) +# @cv2Decorator.DetectInEachFrame(detector=cv2.CascadeClassifier(cv2.data.haarcascades+"haarcascade_frontalface_default.xml"),name='face') +# @cv2Decorator.CalculateFps(draw = True) +# @cv2Decorator.MirrorFrame() +# @cv2Decorator.ConvertCOLOR(converter=cv2.COLOR_BGR2GRAY) +# def all_actions(**kwargs): +# frame = kwargs['frame'] +# # detect face from trainerd data and detectMultiScale use to deteat every size of face +# face_coordinate = kwargs['face'].detectMultiScale(kwargs['color_converted'],1.3,5) +# detectionBox(detectedArr=face_coordinate, frame=frame) +# return kwargs + +# frame = cv2.imread('./testMedia/test.jpg') + +# kwargs = all_actions(frame=frame) +# cv2.imshow('frame',kwargs['frame']) +# key = cv2.waitKey(0) + + +# reading a video from the directory + + +# @cv2Decorator.DetectInEachFrame( +# detector=cv2.CascadeClassifier( +# cv2.data.haarcascades + "haarcascade_frontalface_default.xml" +# ), +# name="face", +# ) +@cv2Decorator.DetectInEachFrame( + detector=Face(verbose=True), + name="face", +) +@cv2Decorator.TotalTimeTaken(show=True) +# @cv2Decorator.AccessCamOrVideo(show=False, videoPath="./testMedia/test.mp4", fps=12) +@cv2Decorator.AccessCamOrVideo(show=False, fps=12) +@cv2Decorator.CalculateFps(draw=True) +@cv2Decorator.MirrorFrame() +@cv2Decorator.ConvertCOLOR(converter=cv2.COLOR_BGR2GRAY) +@cv2Decorator.ConvertCOLOR(converter=cv2.COLOR_RGB2BGR, frameName="bgr_frame") +def all_actions(**kwargs): + # detect face from trainerd data and detectMultiScale use to deteat every size of face + # face_coordinate = kwargs["face"].detectMultiScale(kwargs["greyScale"], 1.3, 5) + mainFrameCopy = kwargs["frame"].copy() + processed = kwargs["face"].detect(kwargs["bgr_frame"]) + face_coordinate = kwargs["face"].getDetectionBox( + processed, kwargs["frame"], draw=True + ) + kwargs["face"].drawLandmarks(processed, kwargs["frame"]) + # print(len(face_coordinate)) + + kwargs["detected"] = [clipImage(mainFrameCopy, i) for i in face_coordinate] + # saveFrame(frame=frame,count=kwargs['frame_count'],destination='./test2') + + # detectionBox(detectedArr=face_coordinate, frame=kwargs["frame"]) + # show_all_frames(kwargs,keysToShow=['frame','greyScale','mirror_frame','detected']) + # show_all_frames(kwargs,keysToShow=['frame','greyScale','mirror_frame']) + show_all_frames(kwargs, keysToShow=["frame", "detected"]) + return kwargs + + +kwargs = all_actions() + + +# reading the cam feed +# @cv2Decorator.TotalTimeTaken(show=True) +# @cv2Decorator.DetectInEachFrame(detector=cv2.CascadeClassifier(cv2.data.haarcascades+"haarcascade_frontalface_default.xml"),name='face') +# @cv2Decorator.AccessCamOrVideo(show=True) +# @cv2Decorator.CalculateFps(draw = True) +# @cv2Decorator.MirrorFrame() +# @cv2Decorator.ConvertCOLOR(converter=cv2.COLOR_BGR2GRAY) +# def all_actions(**kwargs): +# frame = kwargs['frame'] +# # detect face from trainerd data and detectMultiScale use to deteat every size of face +# face_coordinate = kwargs['face'].detectMultiScale(kwargs['color_converted'],1.3,5) +# # saveFrame(frame=frame,count=kwargs['frame_count'],destination='./test2') +# detectionBox(detectedArr=face_coordinate, frame=frame) +# return kwargs + +# kwargs = all_actions() + +# print("last ",all_actions().keys()) +# print("last ",all_actions().keys()) diff --git a/opencv.wrap/test2.py b/test/test2.py similarity index 83% rename from opencv.wrap/test2.py rename to test/test2.py index 011e9ad..f8cb3e6 100644 --- a/opencv.wrap/test2.py +++ b/test/test2.py @@ -5,7 +5,7 @@ d1 = Face(verbose=True) d2 = Face() - image = cv2.imread("./test/test.jpg") + image = cv2.imread("./testMedia/test.jpg") print(d1.detect(image)) print("isinstance of face :", isinstance(d1, Face), end=" ") print("is i1 == i2 :", d1 == d2)