def __init__(self, detectors=None): if detectors is None: detectors = [ Detector(Object("red")), Detector(Object("blue")), Detector(Object("yellow")), Detector(Object("green")) ] self.detectors = detectors self.target = None self.frame = None self.mask = None
def main(): r = redis.Redis(host=config.redis.hostname, port=config.redis.port, db=config.redis.db) detector = Detector("/models/hent-AI model 268/weights.h5") detector.load_weights() # Test the connection to Redis. r.get("connection-test") while True: print("ready to receive censored image") key, uuid = r.blpop(["mask-requests:bar", "mask-requests:mosaic"], 0) print("received censored image") censored_img_data = r.get("censored-images:%s" % uuid.decode()) is_mosaic = key.decode() == "mask-requests:mosaic" try: prepared_img = detector.detect_and_mask(ImageProcessor.bytes_to_image(censored_img_data), is_mosaic, 3) print("processed image, saving to redis") r.set("masked-images:%s" % uuid.decode(), ImageProcessor.image_to_bytes(prepared_img)) r.rpush("decensor-requests:%s" % ("mosaic" if is_mosaic else "bar"), "%s" % uuid.decode()) except NoCensoredRegionsFoundError as e: print(e.description) r.set("errors:%s" % uuid.decode(), e.json)
def __get_video__(self): file_dir = filedialog.askopenfilename() filetype = os.path.splitext(file_dir)[1] if len(file_dir) > 0: if filetype in ['.mov']: model = load_model("ModelandPickle/AlexnetRP.model") # Open the computer web cam. cap = cv2.VideoCapture(file_dir) while True: # Capture the frame from the web camera. ret, frame = cap.read() facedector = Detector() face = facedector.detect_face(frame) for (x, y, w, h) in face: color = (0, 0, 255) stroke = 2 cv2.rectangle(frame, (x, y), (x + w, y + h), color, stroke) # Capture the face from the frame and then test it Capture_face = frame[y: y + h, x + 10: x + w - 10] Capture_face = cv2.resize(Capture_face, (Image_size, Image_size)) Capture_face = Capture_face.astype("float") Capture_face = img_to_array(Capture_face) face = np.expand_dims(Capture_face, axis=0) preds = model.predict(face)[0] j = np.argmax(preds) result = int(j) label = image_label[result] if (label == 'real'): label = "{}".format(label) cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) elif (label == 'fake'): label = "{}".format(label) cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) frame = cv2.putText(frame, 'Press Q to exit', (0, 10), cv2.FONT_HERSHEY_COMPLEX, 1.2, (255, 255, 255), 1) # Display the real time frame. cv2.imshow('Face Detection', frame) # If user type Q from the keyboard the loop could be break. if cv2.waitKey(20) & 0xFF == ord('q'): break # Release the resource and destroy all windows. cap.release() cv2.destroyAllWindows() else: messagebox.showerror('error', message='The file type is wrong, please upload .mov file')
def test_package_calibration(): detector = Detector() handrail_filter = calibrate_from_package_return_handrail_filter() test_img = cv2.imread("Calibration_Images/cal_80cm_45degrees.jpg") detection = detector.get_rects_from_bgr(test_img)[0] print(handrail_filter.get_distance_from_detection(detection))
def __init__(self, image_shape=(720, 1280), step_sizes=[-40, -20, 0, 20, 40], max_guided_eps=1000): self.current_episode = 0 self.max_guided_eps = max_guided_eps self.im_width = image_shape[1] self.im_height = image_shape[0] self.step_sizes = step_sizes self.fig = None self.max_dist = np.linalg.norm([self.im_width, self.im_height]) self.SCALE_IOU = 8.0 self.SCALE_DIST = 1.0 self.min_reward = 0.08 self.current_frame = None self.current_output = None self._detector = Detector() self._connector = MultiRotorConnector() self._car_connector = CarConnector() self.old_x = None self.old_y = None self.TEST = False
def __init__( self, device ): # тут бы по хорошему проинициализировать все что у нас написано self.CarCon = CarControl.CarControl( device) # кар контролу передаем девайс которым пользуемся self.Detector = Detector() self.Road = 0 self.map = Map.MyMap( open('graph.txt')) # нам нужна карта для построения маршрута self.Path = [] self.prev = 0 self.startDot = 1 self.finishDot = 18 self.bluesigns = 0 self.walls = [10000, 10000, 10000] self.lines = [10000, 10000] self.frame = np.array([]) self.RedIsON = 0 self.brick = 0 #self.camera = PiCamera() self.camera = cv2.VideoCapture(0) #self.camera.resolution = (CarSettings.PiCameraResW, CarSettings.PiCameraResH) #self.camera.framerate = CarSettings.PiCameraFrameRate #self.camera.vflip = True #self.camera.hflip = True #self.rawCapture = PiRGBArray(self.camera, size=(CarSettings.PiCameraResW, CarSettings.PiCameraResH)) self.crossroad = False self.fullcross = False self.CarCon.turn(CarSettings.DefaultAngle) self.CarCon.move(0, CarSettings.Stop)
def __init__(self, cluster_id, node, detection_list, port, polling_interval): threading.Thread.__init__(self) self.node = node self.cluster_id = cluster_id self.detection_list = detection_list self.clean_detection_list = self.clean_detection() self.ipmi_status = node.ipmi_status self.polling_interval = polling_interval self.loop_exit = False self.config = ConfigParser.RawConfigParser() self.config.read('hass.conf') self.detector = Detector(node, port) self.custom_function_map = self.set_function_map() self.function_map = [ self.detector.checkPowerStatus, self.detector.checkOSStatus, self.detector.checkNetworkStatus, self.detector.checkServiceStatus ] self.active_layer = self.set_active_layer() self.disable_layer = self.set_disable_layer() self.authUrl = "http://" + self.config.get("rpc", "rpc_username") + ":" + self.config.get("rpc", "rpc_password") + \ "@127.0.0.1:" + self.config.get( "rpc", "rpc_bind_port") self.server = xmlrpclib.ServerProxy(self.authUrl)
def import_arcadia_archived_data(data_directory='/Users/leah/Desktop/Sensor Data/Arcadia/Historical 5-min Sensor Data (from TransSuite)/TCS Detector Archive/Arcadia Detector Archive - 2014-02-09'): detector_dictionary = {} for filename in os.listdir(data_directory): if '.csv' not in filename: continue with open(os.path.join(data_directory, filename), 'rb') as csvfile: linedict = csv.DictReader(csvfile) volume = [] occupancy = [] timestamps = [] id = 0 for row in linedict: id = int(row['Detector ID']) timestamps.append(datetime.strptime(row[' "Archive Date"'], '%a %b %d %H:%M:%S %Z %Y')) if 'ON_LINE' in row[' Status']: volume.append(float(row[' Volume'])) occupancy.append(float(row[' Occupancy'])) else: # sensor is offline volume.append(None) occupancy.append(None) control_id = int(str(id)[0:-2]) detector_dictionary.setdefault(control_id, []).append(Detector(time_array=timestamps, volume=volume, occupancy=occupancy, sensor_id=id, control_id=control_id)) detector_list = [] for control_id, sensor_list in detector_dictionary.iteritems(): detector_list.append(DetectorSet(sensor_list, detector_id=control_id, control_id=control_id)) return detector_dictionary, detector_list
def find_target(self, frame, following, color=None, type_obj="object"): self.update(frame) if color is None: # se non gli passo nessun colore da cercare, li cerco tutti for detector in self.detectors: mask, rect = detector.find_obj(self.frame) if rect is not None: detector.find_type(self.frame, following) if detector.bounding_box and detector.obj.type == type_obj: # se ho rilevato qualcosa self.target = detector break else: # altrimenti cerco solo quel colore detector = Detector(Object(color)) try: mask, rect = detector.find_obj(self.frame) except TypeError: mask = None rect = None detector.obj.type = "area" if rect is not None and type_obj == "object": detector.find_type(self.frame, following) if detector.bounding_box and detector.obj.type == type_obj: # se ho rilevato qualcosa self.target = detector self.mask = mask if self.target: print "my target is " + self.target.obj.name + " " + self.target.obj.type
def __init__(self): rospy.init_node('detector', anonymous=True) config_path = rospy.get_param("~config_path") gate_pose_model_path = rospy.get_param("~gp_model_path") detector_weights_path = rospy.get_param("~d_weights_path") gate_pose_weights_path = rospy.get_param("~gp_weights_path") target_size = rospy.get_param("~target_size", '300,225').split(',') target_size = tuple([int(t) for t in target_size]) with open(gate_pose_model_path, 'r') as jsonfile: # with tf.device("/cpu:0"): self.pose_estimator = model_from_json(json.load(jsonfile)) print("[*] Loading weights from '{}'".format(gate_pose_weights_path)) self.pose_estimator.load_weights(gate_pose_weights_path, by_name=True) global pose_graph pose_graph = tf.get_default_graph() config = tf.ConfigProto() config.gpu_options.allow_growth = True tf.keras.backend.set_session(tf.Session(config=config)) self.network = Detector.Detector(config_path, detector_weights_path, target_size) rospy.Subscriber("camera", CompressedImage, self.image_callback, queue_size=1, buff_size=52428800) self.predictorPublisher = rospy.Publisher("predictor/raw", GatePrediction, queue_size=20) self.filteredPredictorPublisher = rospy.Publisher("predictor/filtered", GatePrediction, queue_size=20)
def recoverServiceFail(self, cluster_id, fail_node_name): cluster = ClusterManager.getCluster(cluster_id) if not cluster: logging.error("RecoverManager : cluster not found") return fail_node = cluster.getNodeByName(fail_node_name) port = int(self.config.get("detection", "polling_port")) version = int(self.config.get("version", "version")) detector = Detector(fail_node, port) fail_services = detector.getFailServices() status = True if "agents" in fail_services: status = self.restartDetectionService(fail_node, version) else: status = self.restartServices(fail_node, fail_services, version) if not status: # restart service fail print "start recovery" print "fail node is %s" % fail_node.name print "start recovery vm" self.recoverVM(cluster, fail_node) print "end recovery vm" return self.recoverNodeByReboot(fail_node) else: return status # restart service success
def main(): if not os.path.isfile(fname): print("Please train the data first") exit(0) videoGetter = Capturer(vSource).start() faceDetector = Detector(dname, cname, fname, videoGetter.frame, relayPin).start() #videoShower = Show(videoGetter.frame).start() # Setup GPIO for door lock GPIO.setmode(GPIO.BCM) GPIO.setup(relayPin, GPIO.OUT) GPIO.output(relayPin, 0) while True: # Stop the thread when its other worker stopped if videoGetter.stopped or faceDetector.stopped: #videoShower.stopped: if not videoGetter.stopped: videoGetter.stop() if not faceDetector.stopped: faceDetector.stop() #if not videoShower.stopped: videoShower.stop() break frame = videoGetter.frame # Capture a video frame faceDetector.frame = frame # Submit the video frame to detector for process #videoShower.frame = frame GPIO.cleanup() print("END")
def main(): input_file_name, model_name, show_video = check_args() print(f"Input Video: {input_file_name}") print(f"Model Name: {model_name}") detector = Detector() detector.initialize(model_name, input_file_name) can_read_frames = True current_frame = 0 start_time = time.time() while can_read_frames: current_frame += 1 can_read_frames, frame = detector.analyze_frame(current_frame) print(f"\rAnalyzing Frame {current_frame}", end='') if current_frame % 3 == 0: print(" \\", end='') elif current_frame % 3 == 1: print(" |", end='') elif current_frame % 3 == 2: print(" /", end='') if show_video and frame is not None: cv2.imshow("Frame", frame) cv2.waitKey(1) analyze_time = int(time.time() - start_time) print() print(f"Total Frames: {current_frame}") print(f"Analyze Time: {analyze_time}s") print(f"Average Frames Per Second: {current_frame // analyze_time}")
def main(): print("""Intrusion Detection Camera System enabled. (Optional) Open configurations.yml to update your preferences""") yml = yaml.safe_load(open("configurations.yml", "r")) detector = Detector(None, yml['main']['input_video'])
def start(self): self.client_socket, addr = self.server_socket.accept() print("[INFO] connection received from: %s\n" % (addr[0])), data = self.receive_data() frame = self.vf.convert_to_frame(data) self.detector = Detector(frame, EYE_AR_THRESH=0.24, ROLL_THRESH=15, TIME_THRESH=3) while self.client_socket: try: data = self.receive_data() frame = self.vf.convert_to_frame(data) if sys.getsizeof(data) < 40: print("[INFO] Client stopped sending messages") break self.ALARM_ON = self.detector.detect_drowsiness(frame) self.send_alarm_status() if self.vf.show_frame(frame): break except Exception as e: print("[EXCEPTION] ", e) break self.stop()
def __init__(self): self.known_height = 3.50266 # cm self.known_width = 25.5 # cm self.focal_length_width = -1 self.focal_length_height = -1 self.image_width = 0 self.image_height = 0 self.detector = Detector()
def process_video(infile,outfile, camera): print("Reading {}".format(os.path.basename(infile))) ld = Detector(use_smoothing = True, camera = camera) clip = VideoFileClip(infile) adj_clip = clip.fl_image(ld.process_image) adj_clip.write_videofile(outfile, audio=False)
def __init__(self): Thread.__init__(self) self.Detector = Detector() self.bluesigns = 0 self.RedIsON = False self.mark = False self.frame = np.array([]) self.brick = 0
def __init__(self, detector_window, classifier_window): self.detector_window = detector_window self.classifier_window = classifier_window self.detector = Detector() self.detector.load() self.classifier = Classifier() self.classifier.load() self.gesture_sequence = Gesture()
def main(): ap = argparse.ArgumentParser() ap.add_argument("-v", "--videopath", help="Path to video") ap.add_argument("-d", "--detector", help="Detection Algo") args = vars(ap.parse_args()) if (args["videopath"] == "0"): source = 0 elif (args["videopath"] == "1"): source = 1 else: source = args["videopath"] if (args["detector"] == "HG" or args["detector"] == "HC"): detector_algo = args["detector"] else: print " Detector algo not correct" quit() ############ Detection Part starts here ############## dtector = Detector(src=source, detector=detector_algo).start() while True: frame = dtector.read() frame = imutils.resize(frame, width=400) cv2.imshow("Detection", frame) key = cv2.waitKey(20) & 0xFF if key == 27: break dtector.stop() rect, img = dtector.get_roi() cv2.destroyAllWindows() # print rect ############ Detection Part ends here ############## ############ Tracking Part starts here ############## global stop_arduino_thread q = Queue() tracker = Tracker(rect, img, src=source).start() print tracker data = tracker.get_points() q.put(data) thread_arduino = Thread(target=send_arduino, args=(q, )) thread_arduino.start() while True: frame = tracker.read() frame = imutils.resize(frame, width=400) cv2.imshow("Frame", frame) data = tracker.get_points() q.put(data) key = cv2.waitKey(50) & 0xFF if key == 27: break stop_arduino_thread = True tracker.stop() cv2.destroyAllWindows()
def main(): parser = argparse.ArgumentParser() parser.add_argument("-c", "--camera", help="using camera feed", action='store_true') parser.add_argument("-p", "--path", help="path to images") parser.add_argument("-o", "--option", help="options : both, eyes, smile",required=True) parser.add_argument("-d", "--display", help="do you want to display",action='store_true') args = parser.parse_args() if args.camera: images = VideoList('Camera') elif args.path: images = FrameList(args.path) else: raise Exception('must pass either feed or images') source = images.get_source() folder = source.split('/')[-1] save = '../data/Results' if not os.path.exists(save): os.makedirs(save) detector = Detector(option=args.option, debugging=False, save=False) row = 0 workbook = xlsxwriter.Workbook(save + '/' + folder + '.xlsx') worksheet = workbook.add_worksheet() worksheet.write(row, 0, "Image Name") worksheet.write(row, 1, "Results") t = 0 f = 0 #ITERATE OVER ALL IMAGES while not images.is_finished(): name, frame = images.get_frame() value = detector.perfectPhoto(frame) if args.display: frame = cv2.resize(frame,(400,400), interpolation=cv2.INTER_AREA) cv2.imshow("Feed", frame) k = cv2.waitKey(1000) if k & 0xFF == ord('q'): images.stop() row+=1 worksheet.write(row, 0, name) worksheet.write(row,1, value*1) if value: t+=1 else: f+=1 last_row = row + 1 worksheet.write(last_row+1,0, "Predicted Yes") worksheet.write(last_row+1,1, "=COUNTIF(B2:B{},1)".format(last_row) ) worksheet.write(last_row+2 ,0, "Predicted No") worksheet.write(last_row+2,1, "=COUNTIF(B2:B{},0)".format(last_row) ) workbook.close() print("Predicted Yes: {}, Predicted No: {}".format(t,f))
def trainv(tv): print("started....") clf = Detector(T=tv) with open('Training.pkl', 'rb') as f: train = pickle.load(f) clf.training(train, 700, 700) eval(clf, train) clf.save(str(tv)) print("Done Amaze bro")
def create_model(): model = MyCNN() model.add(Convolution(num_filter= 4, input_size=(150,150,3), filter_size=(3,3))) model.add(Detector()) model.add(Pooling(filter_size=(2,2), stride_size=1, mode="max")) model.add(Flatten()) model.add(Dense(256,"relu")) model.add(Dense(1,"sigmoid")) return model
def __init__(self): super().__init__() self.Detector = Detector() self.current_frame_count = 0 self.is_running = False self.is_paused = False self.is_video_finished = True self.video_path = "" self.model_name = ""
def test_cam_angle_calculator(): detector = Detector() handrail_filter = calibrate_from_package_return_handrail_filter() cam = CameraController() for i in 1, 2: test_img = cam.get_image() out = handrail_filter.get_handrail_vectors(test_img) print(out)
def createDetector(self, detector_type, position, angle): """Create a detector array, i.e. an array of Detector objects.""" # Create detector object detector_obj = Detector(detector_type=detector_type, position=position, angle=angle, sync_obj=self.sync_obj) return detector_obj
def test_cam_dist_calculator(): detector = Detector() handrail_filter = calibrate_from_package_return_handrail_filter() cam = CameraController() test_img = cam.get_image() cv2.imshow("before", test_img) cv2.waitKey(0) detections = detector.get_rects_from_bgr(test_img) out = handrail_filter.get_valid_detections_and_distances_list(detections)
def __init__(self, parent=None): super(cdc, self).__init__(parent) # video stream is initially paused self.isPaused = False # mission is not running initially self.isRunning = False # establish a connection the quadcopter print 'Opening telemetry radio connection...' self.quad = None for i in range(0, 5): tty = '/dev/ttyUSB' + str(i) try: self.quad = mavutil.mavlink_connection(device=tty, baud=57600) except: print 'No telemetry radio on ' + tty if self.quad: print 'Telemetry radio found on ' + tty break if self.quad is None: print 'Could not open telemetry radio connection' return # min and max sequence number # determines when to start and stop capturing images self.quad.MIN_WP_SEQ = 1 self.quad.MAX_WP_SEQ = 90 # CC3100 connection information self.host = '192.168.1.1' self.port = 7277 # set up the GoProController object used for pulling static images # Ethernet Adapter is wlan0; USB Wi-Fi Adapter is wlan1 self.gpc = GoProController(device_name='wlan0') self.gpc.connect('SARSGoPro', 'sarsgopro') # set up the Detector object for testing images pulled from the GoPro self.det = Detector() # set up the UI generated by Qt/PyQt self.setupUi(self) # create and set up the VLC instance and associated media player self.instance = libvlc.Instance() self.mediaplayer = self.instance.media_player_new() self.setupVLC() # set up the telemetry window so it can periodically update with diagnostic info self.setupTelemetry() # set up the command console so it can process user input self.setupCmdCon()
def main(): indexs = [] for i in range(27): indexs.append(i + 1) config = Config() jam_detector = JamDetector(config) jam_detector.set_index_function(Utility.TCI_2) detector = None if args.with_detector: detector = Detector() Task(jam_detector, indexs, detector, args.is_visualization)
def calibrate_from_package_return_handrail_filter(): detector = Detector() handrail_filter = HandrailFilter() cal1 = cv2.imread("Calibration_Images/cal_1m_0degrees.jpg") height, width, channels = cal1.shape cal_pckg = CalibrationPackage(width, height) det1 = detector.get_rects_from_bgr(cal1)[0] cal2 = cv2.imread("Calibration_Images/cal_80cm_0degrees.jpg") det2 = detector.get_rects_from_bgr(cal1)[0] cal_pckg.add_detection(det1, 100).add_detection(det2, 80) handrail_filter.calibrate_from_package(cal_pckg) return handrail_filter