Skip to content

Instantly share code, notes, and snippets.

@godie007
Created December 6, 2019 22:38
Show Gist options
  • Save godie007/744badb9f9b4202d85d0368d8d1aa27a to your computer and use it in GitHub Desktop.
Save godie007/744badb9f9b4202d85d0368d8d1aa27a to your computer and use it in GitHub Desktop.
import numpy as np
import cv2
import requests_async as requests
import json
import time
import sys
import asyncio
import aiohttp
url = 'http://localhost:8081/'
sdThresh = 5
font = cv2.FONT_HERSHEY_SIMPLEX
#TODO: Face Detection 1
def distMap(frame1, frame2):
"""outputs pythagorean distance between two frames"""
frame1_32 = np.float32(frame1)
frame2_32 = np.float32(frame2)
diff32 = frame1_32 - frame2_32
norm32 = np.sqrt(diff32[:,:,0]**2 + diff32[:,:,1]**2 + diff32[:,:,2]**2)/np.sqrt(255**2 + 255**2 + 255**2)
dist = np.uint8(norm32*255)
return dist
# cv2.namedWindow('frame')
cv2.namedWindow('dist')
#capture video stream from camera source. 0 refers to first camera, 1 referes to 2nd and so on.
cap = cv2.VideoCapture(0)
_, frame1 = cap.read()
_, frame2 = cap.read()
facecount = 0
flag = 0
async def send_file(frame4,frame3):
try:
async with aiohttp.ClientSession() as session:
_, img_encoded = cv2.imencode('.jpg', frame4)
data = aiohttp.FormData()
data.add_field('name', 'foo')
data.add_field('file', img_encoded.tostring(), filename='file.jpg',content_type='Auto')
async with session.post(url, data=data) as response:
data = await response.text()
response = json.loads(data)
prediction = response["result"][0]["prediction"]
for i in prediction:
frame = cv2.rectangle(frame3,(i['xmin'],i['ymin']),(i['xmax'],i['ymax']),(0,0,255),2)
print (data)
except Exception as e:
print( "Error: %s" % e )
while(True):
_, frame3 = cap.read()
_, frame4 = cap.read()
rows, cols, _ = np.shape(frame3)
cv2.imshow('dist', frame3)
dist = distMap(frame1, frame3)
frame1 = frame2
frame2 = frame3
# apply Gaussian smoothing
mod = cv2.GaussianBlur(dist, (9,9), 0)
# apply thresholding
_, thresh = cv2.threshold(mod, 100, 255, 0)
# calculate st dev test
_, stDev = cv2.meanStdDev(mod)
cv2.imshow('dist', mod)
# cv2.putText(frame2, "Standard Deviation - {}".format(round(stDev[0][0],0)), (70, 70), font, 1, (255, 0, 255), 1, cv2.LINE_AA)
if stDev > sdThresh:
# tic = time.clock()
flag = flag + 1
if flag % 30 == 0:
futures = []
futures.append(send_file(frame4, frame3))
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(futures))
cv2.imshow('bird', frame3)
#TODO: Face Detection 2
# cv2.imshow('frame', frame2)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment