Skip to content
Snippets Groups Projects
Commit a4c4bf24 authored by dronus's avatar dronus
Browse files

code cleanup and simplification - use hardcoded config file name conf.json, no...

code cleanup and simplification - use hardcoded config file name conf.json, no warn suppression etc.
parent 6f930c7d
Branches
No related tags found
No related merge requests found
#!/usr/bin/python3
# import the necessary packages
#from pyimagesearch.tempimage import TempImage
import math
from picamera.array import PiRGBArray
from picamera import PiCamera
import argparse
import warnings
import datetime
#import dropbox
import json
import time
import cv2
import numpy as np
import os
from threading import Timer
import jack
# First 4 bits of status byte:
NOTEON = 0x9
NOTEOFF = 0x8
CC = 0xB
# we are a Jack MIDI jack_client to send MIDI messages
jack_client = jack.Client("Woodsound Scanner")
midi_outport = jack_client.midi_midi_outports.register("output")
midi_output_queue=[] # MIDI messages ready to send
client = jack.Client("Woodsound Scanner")
outport = client.midi_outports.register("output")
out_queue=[]
@client.set_process_callback
# Jack MIDI jack_client output callback - feeds MIDI messages to Jack on it's demand
@jack_client.set_process_callback
def process(frames):
outport.clear_buffer()
while out_queue:
outport.write_midi_event(0,out_queue.pop())
client.activate()
stats=""
#timer class:
class aTimer():
def __init__(self,t,hFunction):
self.t=t
self.hFunction = hFunction
self.thread = Timer(self.t,self.handle_function)
def handle_function(self):
self.hFunction()
self.thread = Timer(self.t,self.handle_function)
self.thread.start()
def start(self):
self.thread.start()
def cancel(self):
self.thread.cancel()
def sectimerevent():
global stats
stats=getCPUtemperature()
def getCPUtemperature():
# res = os.popen('vcgencmd measure_temp').readline()
# return(res.replace("temp=","").replace("'C\n",""))
res=os.popen('/home/pi/getcpufreq.sh').readline()
return res
#a,b: center of circle, r:radius
def inside_circle(x, y, a, b, r):
return (x - a)*(x - a) + (y - b)*(y - b) < r*r
class SmoothedFpsCalculator:
"""
Provide smoothed frame per second calculation.
"""
def __init__(self, alpha=0.1):
self.t = time.time()
self.alpha = alpha
self.sfps = None
def __call__(self):
t = time.time()
d = t - self.t
self.t = t
fps = 1.0 / d
if self.sfps is None:
self.sfps = fps
else:
self.sfps = fps * self.alpha + self.sfps * (1.0 - self.alpha)
return self.sfps
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--conf", required=True,
help="path to the JSON configuration file")
args = vars(ap.parse_args())
# filter warnings, load the configuration and initialize the Dropbox
# client
warnings.filterwarnings("ignore")
conf = json.load(open(args["conf"]))
client = None
midi_outport.clear_buffer()
while midi_output_queue:
midi_outport.write_midi_event(0,midi_output_queue.pop())
jack_client.activate()
# load the configuration
conf = json.load(open('conf.json'))
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
......@@ -110,83 +34,51 @@ camera.exposure_mode='off'
camera.shutter_speed=conf["shutter_milliseconds"]*1000
rawCapture = PiRGBArray(camera, size=tuple(conf["resolution"]))
# allow the camera to warmup, then initialize the average frame, last
# uploaded timestamp, and frame motion counter
# allow the camera to warmup
print("[INFO] warming up...")
time.sleep(conf["camera_warmup_time"])
avg = None
lastUploaded = datetime.datetime.now()
motionCounter = 0
#t = aTimer(1,sectimerevent)
#t.start()
pixel_count=0
sfps = SmoothedFpsCalculator()
#num_keys=conf["pitch_range"]
histogram_steps=conf["bins"]
threshold=conf["threshold"]
last_histogram=np.zeros(histogram_steps,dtype=np.uint16)
# capture frames from the camera
clahe=cv2.createCLAHE(clipLimit=conf["contrast_limit"])
# clahe=cv2.createCLAHE(clipLimit=conf["contrast_limit"])
for f in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# grab the raw NumPy array representing the image and initialize
# the timestamp and occupied/unoccupied text
frame = f.array
timestamp = datetime.datetime.now()
text = "Unoccupied"
crop_frame=frame[100:280,0:640]
frame = f.array
# crop_frame=clahe.apply(crop_frame)
# crop_frame=cv2.equalizeHist(crop_frame)
# retval,crop_frame=cv2.threshold(crop_frame,25,255,cv2.THRESH_BINARY)
line_frame=crop_frame[140:141,5:635]
#line_frame=cv2.resize(line_frame, (num_keys+2,1), interpolation = cv2.INTER_AREA)
#line_frame_2=line_frame[0:1,1:num_keys+1]
#retval,line_frame=cv2.threshold(line_frame_2,conf["threshold"],255,cv2.THRESH_BINARY)
# crop down to some rectangular bar used for processing
cropped_frame=frame[100:280,0:640]
# crop single line for color histogram output
line_frame=cropped_frame[140:141,5:635]
# compute b/w histogram
line_frame = cv2.cvtColor(line_frame, cv2.COLOR_BGR2GRAY)
histogram=np.zeros(histogram_steps,dtype=np.uint16)
for pixel in np.nditer(line_frame):
histogram[(int)(pixel*histogram_steps/256)]+=1
index=1
for pixel in np.nditer(histogram[0:-conf['removed_top_bins']]):
last_pixel=last_histogram[index]
if pixel>=threshold and last_pixel<threshold:
pixel_count+=1
if pixel<threshold and last_pixel>=threshold:
pixel_count-=1
velocity=pixel-threshold
if velocity>127:
velocity=127
if velocity<=0:
velocity=0
packet=((CC<<4), index, velocity)
out_queue.append(packet)
packet=((0xB<<4), index, velocity) # MIDI CC ("Continuous Controller") message
midi_output_queue.append(packet)
index+=1
print("Pixels on: "+str(pixel_count)+":"+str(histogram))
last_histogram=np.copy(histogram)
# cv2.putText(frame, '%0.2f fpsu, %s' %(sfps(),stats), (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, 255)
cv2.imshow("Security Feed", crop_frame)
cv2.imshow("Security Feed", cropped_frame)
#cv2.imshow("Security Feed 2", histogram)
key = cv2.waitKey(1) & 0xFF
# if the `q` key is pressed, break from the lop
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment