def getHumanDetector(winSize): svm4human = svm.SVM() svm4human.setLinearSVM() detector4human = detector.Detector(winSize) detector4human.setClassifier(svm4human) dataSet = [] labels = [] # positive samples posSamples = imageProcessor.loadImages(IN_CLASS_HUMAN_SET_TRAIN) dataSet += posSamples labels += [1 for i in range(len(posSamples))] posSamples = imageProcessor.loadImages(MIT_HUMAN_SET) dataSet += posSamples labels += [1 for i in range(len(posSamples))] # negative samples negSamples = imageProcessor.loadImages(IN_CLASS_BACKGROUND_SET) dataSet += negSamples labels += [0 for i in range(len(negSamples))] # negSamples = imageProcessor.loadImages(IN_CLASS_CAR_SET_TEST) # dataSet += negSamples # labels += [0 for i in range(len(negSamples))] detector4human.train(dataSet, labels) return detector4human
def run_detection(self): CONFIG["cascade"] = self.cascadeVar.get() CONFIG["fullScreen"] = self.fullScreenVar.get() == 1 CONFIG["camera"] = 1 #CONFIG["camera"] = int(self.cameraVar.get()) det = detector.Detector(CONFIG) det.detect_video()
def main(): print('app started') pygame.init() detector = dt.Detector(PATH_DETECTOR_MODEL_XML, PATH_DETECTOR_MODEL_BIN) classifier = cl.Classifier(PATH_CLASSIFIER_MODEL, PATH_CLASSIFIER_LABEL) main_loop(detector, classifier) print('app exit')
def get_dummy_detector(self, K, p, labels=None, t=1): # If no custom labels are specified, assign each node to its own cluster if labels is None: labels = np.arange(len(K)) # Create dummy locations so that all we need to worry about is population sizes if not isinstance(p, pd.DataFrame): p = pd.DataFrame({ 'lat': np.arange(len(p)), 'lon': np.arange(len(p)), 'pop': np.array(p) }) def strict_heuristic(data, btol): diff = data['prp_in'] - data['prp_out'] mask = (diff == 0) data['type'] = None data.loc[mask, 'type'] = 'bridge' data.loc[(diff < 0) & ~mask, 'type'] = 'source' data.loc[(diff > 0) & ~mask, 'type'] = 'sink' return data # Run and return d = detector.Detector(K, p, b_heuristic=strict_heuristic, method=labels).run(t) return d
def test__strip_comment_chars_1(self): dtr = detector.Detector(license_data) result = dtr._strip_comment_chars(["# Foo", "# Bar"], ['#']) assert_equal(result, ["Foo", "Bar"]) result = dtr._strip_comment_chars(["# Foo", " # Bar"], ['#']) assert_equal(result, ["Foo", " Bar"])
def test_compilation(self): # Missing key data = {'': {'start': '', 'match': '', 'end': ''}} assert_raises(Exception, detector.Detector, data) # Duplicate key data = { 'foo': { 'start': '', 'match': '', 'end': '', 'subs': {\ 'foo': { 'start': '', 'match': '', 'end': ''} } } } assert_raises(Exception, detector.Detector, data) # Underscore start in orig data data = {'_foo': {'start': '', 'match': '', 'end': ''}} assert_raises(Exception, detector.Detector, data) data1 = { 'MPL-1.1': { 'start': r"The contents of this (?:file|package) are subject to the", 'match': r"subject to the Mozilla Public License Version 1.1", 'end': r"Contributor|All Rights Reserved|Initial Developer", 'subs': { 'MPL-1.1|GPL-2.0|LGPL-2.1': { # Mozilla 'start': r"The contents of this (?:file|package) are subject to the", 'match': r"either the GNU General", 'end': r"terms of any one of the MPL, the GPL or the LGPL" }, } }, } dtr = detector.Detector(license_data) assert_equal(dtr._license_data['MPL-1.1']['start'], \ r"The contents of this (?:file|package) are subject to the")
def _watch_key(self, key): if key == 32: # SPACE --> 32 self.FLAG_Display = not self.FLAG_Display # Left --> 81 Up --> 82 Right --> 83 Down --> 84 elif key == 81: pass elif key == 82: self.FLAG_Light += np.array(10, dtype = 'uint8') elif key == 83: pass elif key == 84: self.FLAG_Light -= np.array(10, dtype = 'uint8') elif key in [100, 10]: # ENTER --> 10 Detect --> 100 if self.detector.trained: self.FLAG_Detect = not self.FLAG_Detect elif key == 109: # Mirror --> 109 self.FLAG_Mirror = not self.FLAG_Mirror elif key in [113, 27]: # Quit --> 113 ESC --> 27 cv2.destroyAllWindows() self.cam.release() elif key == 114: # Reload --> 114 reload(detector) self.detectot = detector.Detector() print('\nReloaded modules: \33[1mdetector\33[0m') elif key == 115: # Save --> 115 #============================================================================== # threading.Thread(target = detector.save_photo, args = ([frame],)).start() # # 因为python传参时数字、字符或元组满足传值规则,字典或列表满足传址规则 # # 为了新线程中能够多次存储照片,所以传一个列表,相当于传了一个对象 #============================================================================== threading.Thread(target = self.detector.save_photo, args = (self.cam,)).start() # why not deliver a camera object directly? elif key == 116: # Train --> 116 self._train() #============================================================================== # threading.Thread(target = self.detector.train, # kwargs = self.train_params, # ).start() #============================================================================== elif key == 118: # Vertical --> 118 self.FLAG_Vmiror = not self.FLAG_Vmiror
def test_detect_image(self): """ Test that it can use the rekognition service and detect labels """ with open("landscape_resized.jpg", "rb") as image_file: d = detector.Detector() rs = d.detect_image(image_file.read()) self.assertIn("Building", rs.keys()) self.assertIn("City", rs.keys())
def test__strip_comment_chars_3(self): dtr = detector.Detector(license_data) result = dtr._strip_comment_chars(["/* Foo", "* Bar", "* Baz */"], ['/*', '*', '*/']) assert_equal(result, ["Foo", "Bar", "Baz"]) result = dtr._strip_comment_chars(["/* Foo", "* Bar", "*/"], ['/*', '*', '*/']) assert_equal(result, ["Foo", "Bar", ""]) result = dtr._strip_comment_chars(["/* **** Foo ****", "* Bar", "*/"], ['/*', '*', '*/']) assert_equal(result, ["**** Foo ****", "Bar", ""])
def __init__(self, env, prefix, topic, directory, from_frame, to_frame): self.env = env self.directory = directory self.from_frame = from_frame self.to_frame = to_frame rospy.init_node('kinbody_detector', anonymous=True) self.detector = detector.Detector(prefix, topic) self.listener = tf.TransformListener()
def run_loop(self, times, clusters): for c in clusters: for t in times: d = detector.Detector(transitions, locations, n_clusters=c, random_state=42).run(t) if t is None: t = d.ss_step self.basic_run_checks(d, t)
def test_identification(self): dtr = detector.Detector(license_data, {'details': True}) dir = os.path.join("test", "data", "identification") # For each line for line in open(os.path.join(dir, "index.csv")): line = line.strip() if line == '' or re.match("Header", line): continue yield self.check_identification, dtr, line, dir
def test_migrate(self): d = detector.Detector(transitions, locations, n_clusters=268, random_state=42).run() # Total initial population should be approximately equal to total final population initial = np.sum(locations['pop']) final = np.sum(d.migrate(d.ss_step)) self.assertTrue(np.isclose(initial, final), '{} != {}'.format(initial, final))
def test_bridge_heuristic(self): def bad_func0(x): return x def bad_func1(data, b_tol): data['this is a bad name'] = 'bridge' return data def valid_func(data, b_tol): data['type'] = 'bridge' return data # Should use defualt heuristic instead d0 = detector.Detector(transitions, locations, b_heuristic=bad_func0, n_clusters=2, random_state=42).run() d1 = detector.Detector(transitions, locations, b_heuristic=bad_func1, n_clusters=2, random_state=42).run() # Get another instance for comparisons d2 = detector.Detector(transitions, locations, n_clusters=2, random_state=42).run() # Should be the same self.assertTrue(np.all(d0.cdata()['type'] == d2.cdata()['type'])) self.assertTrue(np.all(d1.cdata()['type'] == d2.cdata()['type'])) # Should pass if a valid function is used d3 = detector.Detector(transitions, locations, b_heuristic=valid_func, n_clusters=2, random_state=42).run() self.assertTrue(np.all(d3.ndata()['ctype'] == 'bridge'))
def test_communities(self): d1 = detector.Detector(transitions, locations, n_clusters=3, random_state=42) d1._communities() n1 = d1.ndata() # Number of unique labels must match the number of clusters self.assertEqual(len(n1['cid'].unique()), 3) # Number of sinks, sources, and bridges should sum to the number of nodes self.assertTrue(np.sum(n1.groupby('cid').size()) == len(locations)) # Should result in the same clusters when a random_state is used d2 = detector.Detector(np.zeros(transitions.shape), locations, n_clusters=3, random_state=42) d2._communities() self.assertTrue(np.all(n1['cid'] == d2.ndata()['cid']))
def detect(): detectors = [ detector.Detector('Joker', 24, 27, lights.yellow), detector.Detector('Batman', 23, 17, lights.purple) ] while True: for detec in detectors: detection = detec.measure() if detection: # Goal lights.meteor() # Send to the server client.emit('goal:scored', detec.team) print("Goal scored against %s!" % detec.team) eventbus.emit('goal:scored') goal() # Wait for the given time countdown(DEFAULT_GOAL_TIMEOUT) # Highlight the last scoring team detec.light_up() time.sleep(0.1)
def __init__(self, log, ch, bandFile=None): self.log = log self.ch = ch self.nDet = int(self.ch.clcDet) #Number of detectors to calculate #Store detectors if bandFile: band = bd.Band(log, bandFile, ch.freqs) if band.eff is not None: bands = band.sample(nsample=self.nDet) self.detectors = [ dt.Detector(log, self.ch, bands[i]) for i in range(self.nDet) ] else: self.detectors = [ dt.Detector(log, self.ch) for i in range(self.nDet) ] else: self.detectors = [ dt.Detector(log, self.ch) for i in range(self.nDet) ]
def detect_example_linux(): name = 'c01_verdonk-Wever oost-201907240707' GR = True rgb_path = r"/home/duncan/Documents/VanBoven/Orthomosaics/" + name + GR * '-GR' + r'/' + name + GR * '-GR' + r".tif" dem_path = r"/home/duncan/Documents/VanBoven/Orthomosaics/" + name + GR * '-GR' + r'/' + name + r"_DEM" + GR * '-GR' + ".tif" clp_path = r"/home/duncan/Documents/VanBoven/Orthomosaics/" + name + GR * '-GR' + r'/' + name + GR * '-GR' + r"_FIELD.shp" Settings = settings.BroccoliUnifiedSettings() D = detector.Detector(rgb_path, dem_path, clp_path, Settings) D.detect(max_count=10) D.remove_duplicate_crops() D.write_shapefiles('./Test Count')
def run(config): with picamera.PiCamera(resolution='640x480', framerate=30) as camera: q = Queue(5) output = streamer.StreamingOutput(q) camera.start_recording(output, format='mjpeg') watcher = detector.Detector(config, q) server = streamer.StreamingServer(('', 8000), streamer.StreamingHandler) watch_thread = threading.Thread(target=watcher.run, daemon=True, args=()) stream_thread = threading.Thread(target=server.serve_forever, daemon=True, args=()) try: watch_thread.start() stream_thread.start() s3 = boto3.client( 's3', region_name=config['aws_region'], aws_access_key_id=config['access_key_id'], aws_secret_access_key=config['secret_access_key']) device = socket.gethostname() while True: if not q.empty(): name = q.get() connection = http.client.HTTPSConnection( config['iot_hub_hostname']) headers = {'Content-type': 'application/json'} notification = { 'device': device, 'event': 'motion', 'stream_url': device + ':8000' } connection.request('POST', '/security/camera/' + device, json.dumps(notification), headers) response = connection.getresponse() if response.status != 200: pathname = config['log_directory'] + '/' + name camera.capture(pathname, use_video_port=True) s3.upload_file(Bucket=configuration['s3_bucket_name'], Filename=pathname, Key=name) q.task_done() time.sleep(0.2) finally: camera.stop_recording() stream_thread.join(5) watch_thread.join(5)
def test__find_next_comment(self): dtr = detector.Detector(license_data) for i in range(len(self.blocks)): delims = self.blocks[i]['delims'] results = self.blocks[i]['results'] string = self.blocks[i]['string'].splitlines() end_line = 0 for result1, result2 in results: (start_line, end_line) = \ dtr._find_next_comment(end_line, string, delims) assert_equal(start_line, result1) assert_equal(end_line, result2)
def test_constructor(self): # Error should be raised if given a bad clustering method with self.assertRaises(NotImplementedError): d = detector.Detector(transitions, locations, method='oof', n_clusters=2, random_state=42) d._communities() # Error should be raised if locations is a bad type with self.assertRaises(TypeError): dummy_locs = 1.3423 dummy_tmtx = np.array([]) d = detector.Detector(dummy_tmtx, dummy_locs, n_clusters=2, random_state=42) # Error should be raised if transitions is a bad type with self.assertRaises(TypeError): dummy_locs = pd.DataFrame({ 'lat': [0, 1], 'lon': [0, 0], 'pop': [1, 1] }) dummy_tmtx = 0.1234 d = detector.Detector(dummy_tmtx, dummy_locs, n_clusters=2, random_state=42) # No errors should be raised for a valid call d = detector.Detector(transitions, locations, method='agglomerative', n_clusters=2)
def detect_example_windows(): rgb_path = r"D:\\Old GR\\c01_verdonk-Wever west-201907240724-GR.tif" dem_path = r"D:\\Old GR\\c01_verdonk-Wever west-201907240724_DEM-GR.tif" clp_path = r"C:\\Users\\VanBoven\\Documents\\DL Plant Count\\ML-Plant-Detection\\Field Shapefiles\\c01_verdonk-Wever west-201907240724-GR_FIELD.shp" Settings = settings.BroccoliUnifiedSettings() D = detector.Detector(rgb_path, dem_path, clp_path, Settings, platform='windows') D.detect(max_count=10) D.remove_duplicate_crops() D.write_shapefiles()
def run_compute_forward(self, num_frames): det = detector.Detector(mode="preprocessed") self.warm_up(det, "preprocessed") proc_latencies = [] for _ in range(num_frames): start = time.time() frame = self.recv_frame(97) ret = det.inference(frame) resp = det.get_detection_results(*ret) self.send_resp(resp) duration = time.time() - start proc_latencies.append(duration) self.logger.info("All frames are received! Stop the server!") return proc_latencies
def run(args): if args['mode'] == 'train': ## preprocessing steps preprocess.preprocess_train('./cars/cars_train', './cars/devkit/cars_train_annos.mat') preprocess.preprocess_test('./cars/cars_test', './cars/devkit/cars_test_annos.mat') split_test_val.test_with_labels( './cars/cars_test', './cars/devkit/cars_test_annos_withlabels.mat') split_test_val.val_test_split() train.start(train_path, val_path) elif args['mode'] == 'test': car_detector = det.Detector() car_recognizer = rec.Recognizer() images_dir = os.listdir(args['data'] + "/test/") for imagepath in images_dir: no_of_cars, car_boxes = car_detector.test_model(args['data'] + "/test/" + imagepath) print('car_boxes', car_boxes[0]) if no_of_cars > 0: print(imagepath) image_ = image.load_img(args['data'] + "/test/" + imagepath) image_ = image.img_to_array(image_) height, width, ch = image_.shape if no_of_cars > 1: for cars in range(0, no_of_cars): print('cars', cars) rec_image = image_[int(car_boxes[cars][0] * height):int(car_boxes[cars][2] * height), int(car_boxes[cars][1] * width):int(car_boxes[cars][3] * width)] result = car_recognizer.load_images_predict(rec_image) print("found {} in the above image".format(result)) else: rec_image = image_[int(car_boxes[0][0] * height):int(car_boxes[0][2] * height), int(car_boxes[0][1] * width):int(car_boxes[0][3] * width)] result = car_recognizer.load_images_predict(rec_image) print("found {} in the above image".format(result))
def test__find_details(self): dtr = detector.Detector(license_data, {'details': True}) (copyrights, license) = \ dtr._find_details(self.block0, 'MPL-2.0') assert_equal(copyrights, ["Copyright (C) 2010 Fred Bloggs"]) assert_equal(license, self.mpl2) (copyrights, license) = \ dtr._find_details(self.block1, 'MPL-2.0') assert_equal(copyrights, ["Copyright (C) 2010 Fred Bloggs", "Copyright (C) 2009-2012 George Jones"]) assert_equal(license, self.mpl2) (copyrights, license) = \ dtr._find_details(self.block2, 'MPL-2.0') assert_equal(license, self.mpl2)
def __init__(self, window, window_title, conf): self.window = window self.window.title(window_title) self.feed_frame = tkinter.Frame(self.window) self.control_frame = tkinter.Frame(self.window) self.feed_frame.pack() self.control_frame.pack(side="bottom") logging.info("Started UI.") self.detector = detector.Detector(conf) self.canvas1 = tkinter.Canvas(self.feed_frame, width=900 * 2 + 40, height=550) #self.canvas1 = tkinter.Canvas(self.feed_frame) self.canvas1.pack() self.sw_cam_button = tkinter.Button(self.control_frame, pady=15, text="Switch", command=self.detector.switch_cams) self.sw_cam_button.pack(side="bottom") self.report_label = tkinter.Label( self.control_frame, padx=10, pady=10, font=("Helvetica", 14), justify=tkinter.LEFT, text="cam fps: 0\nDetected Persons: 0\nLatitude: 0\nLongitude: 0\n" ) self.report_label.pack(side="left") with open(os.path.join(CURDIR, os.path.pardir, 'version')) as ver_file: self.version_label = tkinter.Label(self.control_frame, padx=10, pady=0, font=("Helvetica", 14), justify=tkinter.LEFT, text="ver: {}".format( ver_file.read())) self.version_label.pack(side="left") self.delay = 1 self.update() self.window.mainloop()
def processImage(self, msg): robotId = msg['robotId'] videoId = msg['videoId'] image = msg['stream'] video_serial = robotId + "-" + videoId self.imageKeyFrame += 1 print("processImage {} at keyframe {}".format(video_serial, self.imageKeyFrame)) detectorWorker = detector.Detector(robotId, videoId, image, self.detectCallback, self.detectQueue, self.detectThroughput) detectorWorker.keyframe = self.imageKeyFrame detectorWorker.start()
def test_compute_sss(self): d = detector.Detector(transitions, locations, n_clusters=3, random_state=42) s = d.ss_step # Before steady state, some communities should still be outside the default threshold self.assertFalse( np.all( np.abs(d.migrate(d.ss_step - 1) - d.migrate(d.ss_step)) <= 0.05)) # At steady state, no community should be outside the default threshold self.assertTrue( np.all( np.abs(d.migrate(d.ss_step) - d.migrate(d.ss_step + 1)) <= 0.05))
def detect_example_linux(): """Example of broccoli crop detection workflow on linux""" name = 'c01_verdonk-Wever oost-201907240707' GR = True rgb_path = r"/home/duncan/Documents/VanBoven/Orthomosaics/" + name + GR * '-GR' + r'/' + name + GR * '-GR' + r".tif" dem_path = r"/home/duncan/Documents/VanBoven/Orthomosaics/" + name + GR * '-GR' + r'/' + name + r"_DEM" + GR * '-GR' + ".tif" clp_path = r"/home/duncan/Documents/VanBoven/Orthomosaics/" + name + GR * '-GR' + r'/' + name + GR * '-GR' + r"_FIELD.shp" Settings = settings.BroccoliUnifiedSettings( model_path= '/home/duncan/Documents/VanBoven/Code/Git Folder/Unified CNNs/Broccoli v4' ) D = detector.Detector(rgb_path, dem_path, clp_path, Settings) D.detect(max_count=5, get_background=True) D.remove_duplicate_crops() D.write_shapefiles('./Test Count') D.save_background_to_pickle('./Test Count')
def setup(self, send, log, cfg, botopts): BotMod.setup(self, send, log, cfg, botopts) self._get_vumeter_cfg(cfg) self.ev = DetectorEventHandler(self.send_event, self.botopts) self.d = detector.Detector(self.botopts) self.rec = recorder.Recorder(self.sample_rate, self.interval, self.channels, self.rec, self.dev, self.tool, self.zero_range, self.sox_filter) self.sim = simulator.Simulator() self.log("init audio: cmd=", self.rec.cmd) self.log("options=",self.botopts.get_values()) # setup threading self.queue = queue.Queue() self.thread = threading.Thread(target=self.thread_run, name="audiorec") self.do_run = True self.thread.start()