diff --git a/projects/perception/activity_recognition/demos/online_recognition/LICENSE b/projects/perception/activity_recognition/demos/online_recognition/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/projects/perception/activity_recognition/demos/online_recognition/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/projects/perception/activity_recognition/demos/online_recognition/README.md b/projects/perception/activity_recognition/demos/online_recognition/README.md new file mode 100644 index 0000000000..0ad295004b --- /dev/null +++ b/projects/perception/activity_recognition/demos/online_recognition/README.md @@ -0,0 +1,44 @@ +# OpenDR human activity recognition demo +
+ + + +
+ +Live demo of online human activity recognition using the [OpenDR toolkit](https://opendr.eu). +It captures the video stream from a webcam, performs frame-by-frame predictions, and presents the results on a web UI. + + +## Set-up +After setting up the _OpenDR toolkit_, install dependencies of this demo by navigating to this folder and run: +```bash +pip install -e . +``` + + +## Running the example +Human Activity Recognition using [X3D](https://openaccess.thecvf.com/content_CVPR_2020/papers/Feichtenhofer_X3D_Expanding_Architectures_for_Efficient_Video_Recognition_CVPR_2020_paper.pdf) +```bash +python demo.py --ip 0.0.0.0 --port 8000 --algorithm x3d --model xs +``` + +Human Activity Recognition using CoX3D +```bash +python demo.py --ip 0.0.0.0 --port 8000 --algorithm cox3d --model s +``` + +If you navigate your piano and http://0.0.0.0:8000 and pick up a ukulele, you might see something like this: + + + +For other options, see `python demo.py --help` + + +## Troubleshooting +If no video is displayed, you may try to select another video source using the `--video_source` flag: +```bash +python demo.py --ip 0.0.0.0 --port 8000 --algorithm cox3d --model s --video_source 1 +``` + +## Acknowledgement +This work has received funding from the European Union’s Horizon 2020 research and innovation programme under grant agreement No 871449 (OpenDR). This publication reflects the authors’ views only. The European Commission is not responsible for any use that may be made of the information it contains. diff --git a/projects/perception/activity_recognition/demos/online_recognition/activity_recognition/__init__.py b/projects/perception/activity_recognition/demos/online_recognition/activity_recognition/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/projects/perception/activity_recognition/demos/online_recognition/activity_recognition/kinetics400_classes.csv b/projects/perception/activity_recognition/demos/online_recognition/activity_recognition/kinetics400_classes.csv new file mode 100644 index 0000000000..b792765fbd --- /dev/null +++ b/projects/perception/activity_recognition/demos/online_recognition/activity_recognition/kinetics400_classes.csv @@ -0,0 +1,401 @@ +id,name +0,abseiling +1,air drumming +2,answering questions +3,applauding +4,applying cream +5,archery +6,arm wrestling +7,arranging flowers +8,assembling computer +9,auctioning +10,baby waking up +11,baking cookies +12,balloon blowing +13,bandaging +14,barbequing +15,bartending +16,beatboxing +17,bee keeping +18,belly dancing +19,bench pressing +20,bending back +21,bending metal +22,biking through snow +23,blasting sand +24,blowing glass +25,blowing leaves +26,blowing nose +27,blowing out candles +28,bobsledding +29,bookbinding +30,bouncing on trampoline +31,bowling +32,braiding hair +33,breading or breadcrumbing +34,breakdancing +35,brush painting +36,brushing hair +37,brushing teeth +38,building cabinet +39,building shed +40,bungee jumping +41,busking +42,canoeing or kayaking +43,capoeira +44,carrying baby +45,cartwheeling +46,carving pumpkin +47,catching fish +48,catching or throwing baseball +49,catching or throwing frisbee +50,catching or throwing softball +51,celebrating +52,changing oil +53,changing wheel +54,checking tires +55,cheerleading +56,chopping wood +57,clapping +58,clay pottery making +59,clean and jerk +60,cleaning floor +61,cleaning gutters +62,cleaning pool +63,cleaning shoes +64,cleaning toilet +65,cleaning windows +66,climbing a rope +67,climbing ladder +68,climbing tree +69,contact juggling +70,cooking chicken +71,cooking egg +72,cooking on campfire +73,cooking sausages +74,counting money +75,country line dancing +76,cracking neck +77,crawling baby +78,crossing river +79,crying +80,curling hair +81,cutting nails +82,cutting pineapple +83,cutting watermelon +84,dancing ballet +85,dancing charleston +86,dancing gangnam style +87,dancing macarena +88,deadlifting +89,decorating the christmas tree +90,digging +91,dining +92,disc golfing +93,diving cliff +94,dodgeball +95,doing aerobics +96,doing laundry +97,doing nails +98,drawing +99,dribbling basketball +100,drinking +101,drinking beer +102,drinking shots +103,driving car +104,driving tractor +105,drop kicking +106,drumming fingers +107,dunking basketball +108,dying hair +109,eating burger +110,eating cake +111,eating carrots +112,eating chips +113,eating doughnuts +114,eating hotdog +115,eating ice cream +116,eating spaghetti +117,eating watermelon +118,egg hunting +119,exercising arm +120,exercising with an exercise ball +121,extinguishing fire +122,faceplanting +123,feeding birds +124,feeding fish +125,feeding goats +126,filling eyebrows +127,finger snapping +128,fixing hair +129,flipping pancake +130,flying kite +131,folding clothes +132,folding napkins +133,folding paper +134,front raises +135,frying vegetables +136,garbage collecting +137,gargling +138,getting a haircut +139,getting a tattoo +140,giving or receiving award +141,golf chipping +142,golf driving +143,golf putting +144,grinding meat +145,grooming dog +146,grooming horse +147,gymnastics tumbling +148,hammer throw +149,headbanging +150,headbutting +151,high jump +152,high kick +153,hitting baseball +154,hockey stop +155,holding snake +156,hopscotch +157,hoverboarding +158,hugging +159,hula hooping +160,hurdling +161,hurling (sport) +162,ice climbing +163,ice fishing +164,ice skating +165,ironing +166,javelin throw +167,jetskiing +168,jogging +169,juggling balls +170,juggling fire +171,juggling soccer ball +172,jumping into pool +173,jumpstyle dancing +174,kicking field goal +175,kicking soccer ball +176,kissing +177,kitesurfing +178,knitting +179,krumping +180,laughing +181,laying bricks +182,long jump +183,lunge +184,making a cake +185,making a sandwich +186,making bed +187,making jewelry +188,making pizza +189,making snowman +190,making sushi +191,making tea +192,marching +193,massaging back +194,massaging feet +195,massaging legs +196,massaging person's head +197,milking cow +198,mopping floor +199,motorcycling +200,moving furniture +201,mowing lawn +202,news anchoring +203,opening bottle +204,opening present +205,paragliding +206,parasailing +207,parkour +208,passing American football (in game) +209,passing American football (not in game) +210,peeling apples +211,peeling potatoes +212,petting animal (not cat) +213,petting cat +214,picking fruit +215,planting trees +216,plastering +217,playing accordion +218,playing badminton +219,playing bagpipes +220,playing basketball +221,playing bass guitar +222,playing cards +223,playing cello +224,playing chess +225,playing clarinet +226,playing controller +227,playing cricket +228,playing cymbals +229,playing didgeridoo +230,playing drums +231,playing flute +232,playing guitar +233,playing harmonica +234,playing harp +235,playing ice hockey +236,playing keyboard +237,playing kickball +238,playing monopoly +239,playing organ +240,playing paintball +241,playing piano +242,playing poker +243,playing recorder +244,playing saxophone +245,playing squash or racquetball +246,playing tennis +247,playing trombone +248,playing trumpet +249,playing ukulele +250,playing violin +251,playing volleyball +252,playing xylophone +253,pole vault +254,presenting weather forecast +255,pull ups +256,pumping fist +257,pumping gas +258,punching bag +259,punching person (boxing) +260,push up +261,pushing car +262,pushing cart +263,pushing wheelchair +264,reading book +265,reading newspaper +266,recording music +267,riding a bike +268,riding camel +269,riding elephant +270,riding mechanical bull +271,riding mountain bike +272,riding mule +273,riding or walking with horse +274,riding scooter +275,riding unicycle +276,ripping paper +277,robot dancing +278,rock climbing +279,rock scissors paper +280,roller skating +281,running on treadmill +282,sailing +283,salsa dancing +284,sanding floor +285,scrambling eggs +286,scuba diving +287,setting table +288,shaking hands +289,shaking head +290,sharpening knives +291,sharpening pencil +292,shaving head +293,shaving legs +294,shearing sheep +295,shining shoes +296,shooting basketball +297,shooting goal (soccer) +298,shot put +299,shoveling snow +300,shredding paper +301,shuffling cards +302,side kick +303,sign language interpreting +304,singing +305,situp +306,skateboarding +307,ski jumping +308,skiing (not slalom or crosscountry) +309,skiing crosscountry +310,skiing slalom +311,skipping rope +312,skydiving +313,slacklining +314,slapping +315,sled dog racing +316,smoking +317,smoking hookah +318,snatch weight lifting +319,sneezing +320,sniffing +321,snorkeling +322,snowboarding +323,snowkiting +324,snowmobiling +325,somersaulting +326,spinning poi +327,spray painting +328,spraying +329,springboard diving +330,squat +331,sticking tongue out +332,stomping grapes +333,stretching arm +334,stretching leg +335,strumming guitar +336,surfing crowd +337,surfing water +338,sweeping floor +339,swimming backstroke +340,swimming breast stroke +341,swimming butterfly stroke +342,swing dancing +343,swinging legs +344,swinging on something +345,sword fighting +346,tai chi +347,taking a shower +348,tango dancing +349,tap dancing +350,tapping guitar +351,tapping pen +352,tasting beer +353,tasting food +354,testifying +355,texting +356,throwing axe +357,throwing ball +358,throwing discus +359,tickling +360,tobogganing +361,tossing coin +362,tossing salad +363,training dog +364,trapezing +365,trimming or shaving beard +366,trimming trees +367,triple jump +368,tying bow tie +369,tying knot (not on a tie) +370,tying tie +371,unboxing +372,unloading truck +373,using computer +374,using remote controller (not gaming) +375,using segway +376,vault +377,waiting in line +378,walking the dog +379,washing dishes +380,washing feet +381,washing hair +382,washing hands +383,water skiing +384,water sliding +385,watering plants +386,waxing back +387,waxing chest +388,waxing eyebrows +389,waxing legs +390,weaving basket +391,welding +392,whistling +393,windsurfing +394,wrapping present +395,wrestling +396,writing +397,yawning +398,yoga +399,zumba \ No newline at end of file diff --git a/projects/perception/activity_recognition/demos/online_recognition/activity_recognition/screenshot.png b/projects/perception/activity_recognition/demos/online_recognition/activity_recognition/screenshot.png new file mode 100644 index 0000000000..30e74dd4bd Binary files /dev/null and b/projects/perception/activity_recognition/demos/online_recognition/activity_recognition/screenshot.png differ diff --git a/projects/perception/activity_recognition/demos/online_recognition/activity_recognition/video.gif b/projects/perception/activity_recognition/demos/online_recognition/activity_recognition/video.gif new file mode 100644 index 0000000000..1a677a8bb4 Binary files /dev/null and b/projects/perception/activity_recognition/demos/online_recognition/activity_recognition/video.gif differ diff --git a/projects/perception/activity_recognition/demos/online_recognition/demo.py b/projects/perception/activity_recognition/demos/online_recognition/demo.py new file mode 100644 index 0000000000..7d3872e40d --- /dev/null +++ b/projects/perception/activity_recognition/demos/online_recognition/demo.py @@ -0,0 +1,345 @@ +# Copyright 2020-2021 OpenDR European Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import threading +import time +from typing import Dict +import numpy as np +import torch +import torchvision +import cv2 +from imutils import resize +from flask import Flask, Response, render_template +from imutils.video import VideoStream +from pathlib import Path +import pandas as pd + +# OpenDR imports +from opendr.perception.activity_recognition.x3d.x3d_learner import X3DLearner +from opendr.perception.activity_recognition.cox3d.cox3d_learner import CoX3DLearner +from opendr.engine.data import Video, Image + +TEXT_COLOR = (255, 0, 255) # B G R + + +# Initialize the output frame and a lock used to ensure thread-safe +# exchanges of the output frames (useful for multiple browsers/tabs +# are viewing tthe stream) +output_frame = None +lock = threading.Lock() + + +# initialize a flask object +app = Flask(__name__) + + +@app.route("/") +def index(): + # return the rendered template + return render_template("index.html") + + +def runnig_fps(alpha=0.1): + t0 = time.time_ns() + fps_avg = 10 + + def wrapped(): + nonlocal t0, alpha, fps_avg + t1 = time.time_ns() + delta = (t1 - t0) * 1e-9 + t0 = t1 + fps_avg = alpha * (1 / delta) + (1 - alpha) * fps_avg + return fps_avg + + return wrapped + + +def draw_fps(frame, fps): + cv2.putText( + frame, + f"{fps:.1f} FPS", + (10, frame.shape[0] - 10), + cv2.FONT_HERSHEY_SIMPLEX, + 1, + TEXT_COLOR, + 1, + ) + + +def draw_preds(frame, preds: Dict): + base_skip = 40 + delta_skip = 30 + for i, (cls, prob) in enumerate(preds.items()): + cv2.putText( + frame, + f"{prob:04.3f} {cls}", + (10, base_skip + i * delta_skip), + cv2.FONT_HERSHEY_SIMPLEX, + 1, + TEXT_COLOR, + 1, + ) + + +def draw_centered_box(frame, border): + border = 10 + minX = (frame.shape[1] - frame.shape[0]) // 2 + border + minY = border + maxX = (frame.shape[1] + frame.shape[0]) // 2 - border + maxY = frame.shape[0] - border + cv2.rectangle(frame, (minX, minY), (maxX, maxY), color=TEXT_COLOR, thickness=1) + + +def center_crop(frame): + height, width = frame.shape[0], frame.shape[1] + e = min(height, width) + x0 = (width - e) // 2 + y0 = (height - e) // 2 + cropped_frame = frame[y0:y0 + e, x0:x0 + e] + return cropped_frame + + +def image_har_preprocessing(image_size: int): + standardize = torchvision.transforms.Normalize( + mean=(0.45, 0.45, 0.45), std=(0.225, 0.225, 0.225) + ) + + def wrapped(frame): + nonlocal standardize + frame = resize(frame, height=image_size, width=image_size) + frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame = torch.tensor(frame).permute((2, 0, 1)) # H, W, C -> C, H, W + frame = frame / 255.0 # [0, 255] -> [0.0, 1.0] + frame = standardize(frame) + return Image(frame, dtype=np.float) + + return wrapped + + +def video_har_preprocessing(image_size: int, window_size: int): + frames = [] + + standardize = torchvision.transforms.Normalize( + mean=(0.45, 0.45, 0.45), std=(0.225, 0.225, 0.225) + ) + + def wrapped(frame): + nonlocal frames, standardize + frame = resize(frame, height=image_size, width=image_size) + frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frame = torch.tensor(frame).permute((2, 0, 1)) # H, W, C -> C, H, W + frame = frame / 255.0 # [0, 255] -> [0.0, 1.0] + frame = standardize(frame) + if not frames: + frames = [frame for _ in range(window_size)] + else: + frames.pop(0) + frames.append(frame) + vid = Video(torch.stack(frames, dim=1)) + return vid + + return wrapped + + +KINETICS400_CLASSES = pd.read_csv( + "activity_recognition/kinetics400_classes.csv", verbose=True, index_col=0 +).to_dict()["name"] + + +def clean_kinetics_preds(preds): + k = 3 + class_scores, class_inds = torch.topk(preds[0].confidence, k=k) + preds = { + KINETICS400_CLASSES[int(class_inds[i])]: float(class_scores[i].item()) + for i in range(k) + } + return preds + + +def x3d_activity_recognition(model_name): + global vs, output_frame, lock + + # Prep stats + fps = runnig_fps() + + # Init model + learner = X3DLearner(device="cpu", backbone=model_name, num_workers=0) + X3DLearner.download(path="model_weights", model_names={model_name}) + learner.load(Path("model_weights") / f"x3d_{model_name}.pyth") + + preprocess = video_har_preprocessing( + image_size=learner.model_hparams["image_size"], + window_size=learner.model_hparams["frames_per_clip"], + ) + + # Loop over frames from the video stream + while True: + try: + frame = vs.read() + + frame = center_crop(frame) + + # Prepocess frame + vid = preprocess(frame) + + # Gererate preds + preds = learner.infer(vid) + preds = clean_kinetics_preds(preds) + + frame = cv2.flip(frame, 1) # Flip horizontally for webcam-compatibility + draw_preds(frame, preds) + draw_fps(frame, fps()) + + with lock: + output_frame = frame.copy() + except Exception: + pass + + +def cox3d_activity_recognition(model_name): + global vs, output_frame, lock + + # Prep stats + fps = runnig_fps() + + # Init model + learner = CoX3DLearner(device="cpu", backbone=model_name, num_workers=0) + CoX3DLearner.download(path="model_weights", model_names={model_name}) + learner.load(Path("model_weights") / f"x3d_{model_name}.pyth") + + preprocess = image_har_preprocessing(image_size=learner.model_hparams["image_size"]) + + # Loop over frames from the video stream + while True: + try: + frame = vs.read() + + frame = center_crop(frame) + + # Prepocess frame + vid = preprocess(frame) + + # Gererate preds + preds = learner.infer(vid) + preds = clean_kinetics_preds(preds) + + frame = cv2.flip(frame, 1) # Flip horizontally for webcam-compatibility + draw_preds(frame, preds) + draw_fps(frame, fps()) + + with lock: + output_frame = frame.copy() + except Exception: + pass + + +def generate(): + # grab global references to the output frame and lock variables + global output_frame, lock + + # loop over frames from the output stream + while True: + # wait until the lock is acquired + with lock: + # check if the output frame is available, otherwise skip + # the iteration of the loop + if output_frame is None: + continue + + # encode the frame in JPEG format + (flag, encodedImage) = cv2.imencode(".jpg", output_frame) + + # ensure the frame was successfully encoded + if not flag: + continue + + # yield the output frame in the byte format + yield ( + b"--frame\r\n" + b"Content-Type: image/jpeg\r\n\r\n" + bytearray(encodedImage) + b"\r\n" + ) + + +@app.route("/video_feed") +def video_feed(): + # return the response generated along with the specific media + # type (mime type) + return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame") + + +# check to see if this is the main thread of execution +if __name__ == "__main__": + # construct the argument parser and parse command line arguments + ap = argparse.ArgumentParser() + ap.add_argument( + "-i", "--ip", type=str, required=True, help="IP address of the device" + ) + ap.add_argument( + "-o", + "--port", + type=int, + required=True, + help="Ephemeral port number of the server (1024 to 65535)", + ) + ap.add_argument( + "-m", + "--model_name", + type=str, + default="xs", + help="Model identifier", + ) + ap.add_argument( + "-v", + "--video_source", + type=int, + default=0, + help="ID of the video source to use", + ) + ap.add_argument( + "-a", + "--algorithm", + type=str, + default="x3d", + help="Which algortihm to run", + choices=["cox3d", "x3d"], + ) + args = vars(ap.parse_args()) + + # initialize video stream and allow the camera sensor to warmup + # vs = VideoStream(usePiCamera=1).start() + vs = VideoStream(src=args["video_source"]).start() + time.sleep(2.0) + + algorithm = { + "x3d": x3d_activity_recognition, + "cox3d": cox3d_activity_recognition, + }[args["algorithm"]] + + # start a thread that will perform motion detection + t = threading.Thread(target=algorithm, args=(args["model_name"],)) + t.daemon = True + t.start() + + # start the flask app + app.run( + host=args["ip"], + port=args["port"], + debug=True, + threaded=True, + use_reloader=False, + ) + + # release the video stream pointer + vs.stop() diff --git a/projects/perception/activity_recognition/demos/online_recognition/requirements.txt b/projects/perception/activity_recognition/demos/online_recognition/requirements.txt new file mode 100644 index 0000000000..be2de487e6 --- /dev/null +++ b/projects/perception/activity_recognition/demos/online_recognition/requirements.txt @@ -0,0 +1,8 @@ +flask +# black +# isort>=5.7 +# flake8-black +numpy +opencv-contrib-python +imutils +pandas \ No newline at end of file diff --git a/projects/perception/activity_recognition/demos/online_recognition/setup.py b/projects/perception/activity_recognition/demos/online_recognition/setup.py new file mode 100644 index 0000000000..efdf8db3dd --- /dev/null +++ b/projects/perception/activity_recognition/demos/online_recognition/setup.py @@ -0,0 +1,53 @@ +# Copyright 2020-2021 OpenDR European Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from setuptools import find_packages, setup + + +def from_file(file_name: str = "requirements.txt", comment_char: str = "#"): + """Load requirements from a file""" + with open(file_name, "r") as file: + lines = [ln.strip() for ln in file.readlines()] + reqs = [] + for ln in lines: + # filer all comments + if comment_char in ln: + ln = ln[: ln.index(comment_char)].strip() + # skip directly installed dependencies + if ln.startswith("http"): + continue + if ln: # if requirement is not empty + reqs.append(ln) + return reqs + + +def long_description(): + text = open("README.md", encoding="utf-8").read() + # SVG images are not readable on PyPI, so replace them with PNG + text = text.replace(".svg", ".png") + return text + + +setup( + name="online_activity_recognition", + version="0.1.0", + description="Example of in-browser video streaming and processing using the OpenDR toolkit.", + long_description=long_description(), + long_description_content_type="text/markdown", + author="Lukas Hedegaard", + author_email="lhm@ece.au.dk", + install_requires=from_file("requirements.txt"), + packages=find_packages(exclude=["test"]), + keywords=["deep learning", "pytorch", "AI", "OpenDR", "video", "webcam"], +) diff --git a/projects/perception/activity_recognition/demos/online_recognition/templates/index.html b/projects/perception/activity_recognition/demos/online_recognition/templates/index.html new file mode 100644 index 0000000000..63679ec4ce --- /dev/null +++ b/projects/perception/activity_recognition/demos/online_recognition/templates/index.html @@ -0,0 +1,14 @@ + + + + OpenDR activity recognition demo + + + + + OpenDR activity recognition demo + + + + \ No newline at end of file