class CLIENT(object): def __init__(self,ip='192.168.1.153'): self.ip=ip #self.vs= VideoStream(src=0) self.vs=VideoStream(usePiCamera=True) self.sender = imagezmq.ImageSender(connect_to="tcp://{}:5555".format( self.ip)) self.rpiName= socket.gethostname() self.frame=None def run(self): self.frame = self.vs.read() self.sender.send_image(self.rpiName, self.frame) def stop(self): self.vs.stop() def start(self): self.vs.start() time.sleep(2.0) self.vs.start()
class FrameLoop(object): def __init__(self, fps, lock, width=320, height=200): self.frame = None self.grey_frame = None self.fps = fps self.vs = VideoStream(src=0, framerate=self.fps, resolution=(height, width)) self.lock = lock def loop(self): while True: with self.lock: # Read the frame self.frame = self.vs.read() # self.frame = resize(self.frame, width=1080) # < Not used anymore #Convert it to greyscale self.grey_frame = cvtColor(self.frame, COLOR_BGR2GRAY) self.grey_frame = GaussianBlur(self.grey_frame, (7, 7), 0) # Sleep the thread until the time for the next frame comes sleep(1 / self.fps) def start(self): # Create a new thread self.t = Thread(target=self.loop) self.t.daemon = True # Start the video stream on camera 0 self.vs.start() # Start the thread self.t.start()
class Camera: def __init__(self): self.PiCamera = True self.frameSize = (640,480) # Initialize mutithreading the video stream. try: self.vs = VideoStream(src=0, usePiCamera=self.PiCamera, resolution=self.frameSize, framerate=32) # start camera self.vs.start() # Allow the camera to warm up. time.sleep(2.0) except ExceptionError as e: print(e) def getFrame(self): # get frame frame = self.vs.read() # if using webcame continue frame size if not self.PiCamera: frame = imutils.resize(frame, width=self.frameSize) return frame def stopStream(self): self.vs.stop()
def record_webcam(duration, frame_rate): """ Uses the local webcam to record for the duration and frame rate specified. Returns a list of tuples containing a time stamp and an image. Args: duration: The amount of time to record for in seconds as an int. frame_rate: The number of images to record each second as an int. Returns: A list of tuples containing a time stamp an image, (time stamp,(image)). """ vs = VideoStream() vs.start() n = 0 images = [] while n < duration * frame_rate: image = vs.read() if vs.read() is not None: images.append((datetime.datetime.now(), image)) n += 1 sleep(1 / frame_rate) vs.stop() return images
class RPiCamera: """ This is a class to get video stream from RPi. """ __slots__ = 'width', 'height', 'name', 'camera' def __init__(self, width, height): # image info self.width = width self.height = height # RPi's name self.name = socket.gethostname() # RPi's video stream class self.camera = VideoStream(usePiCamera=True, resolution=(width, height)) def start(self): """ Start streaming. :return: nothing """ self.camera.start() def get_image(self): """ Get individual image (frame) from streaming source. :return: An individual image """ return self.camera.read()
def camera_open(): camera1 = VideoStream(0) camera1.stream.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('Y', 'U', 'Y', 'V')) camera1.stream.stream.set(cv2.CAP_PROP_FRAME_WIDTH, c_w) camera1.stream.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, c_h) camera1.start() return camera1
def __capture_login_encodings(self, timeout=60, show_messages=True, capture_delay=1): """ A fuction created to register a captured login encodings Args: timeout: time, if reached any faces found so far are returned show_messages: bool to show messages or not capture_delay: time to wait between detection attempts Returns: list of encodings for single face detection if face found False if process not completed within 'timeout' seconds """ if timeout <= 0: timeout = 999999 try: vs = VideoStream(src=0) vs.start() except: raise Exception('Failed to start webcam stream') deadline = time.time() + timeout while time.time() < deadline: try: frame = vs.read() except: vs.stop() raise Exception('Failed to get image') image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = imutils.resize(image, 750) boxes = face_recognition.face_locations(image, model='hog') if len(boxes) == 0: if show_messages: print('No faces found') time.sleep(capture_delay) continue if len(boxes) > 1: if show_messages: print('Multiple faces found. One at a time please.') time.sleep(capture_delay) continue vs.stop() return face_recognition.face_encodings(image, boxes) vs.stop() return False
class CCamera: def __init__(self, stream="", resolution=(720, 480), framerate=30): # e.g. "http://192.168.0.29:1338/video", if stream: print("CCamera: start stream capture from ", stream) self.capture = VideoStream(stream) self.capture.start() else: print("CCamera: capture from attached RPi Camera") self.capture = _PiCamera(resolution) def read(self): return self.capture.read() def detect_pointer(self): start = timer() frame = self.read() # cv2.imwrite('_read.png', frame) blurred = cv2.GaussianBlur(frame, (11, 11), 0) hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV) # cv2.imwrite('_blur.png', hsv) # construct a mask for the color "red" mask = cv2.inRange(hsv, (160, 50, 50), (180, 255, 255)) # cv2.imwrite('_threshold.png', mask) # find contours in the mask and initialize the current # (x, y) center of the pointer cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) center = None # only proceed if at least one contour was found if len(cnts) > 0: # find the largest contour in the mask, then use # it to compute the minimum enclosing circle and # centroid c = max(cnts, key=cv2.contourArea) ((x, y), radius) = cv2.minEnclosingCircle(c) print("[{}] detected pointer at {} with radius {}".format( timer() - start, (x, y), radius)) M = cv2.moments(c) if M["m00"] > 0: center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) print("[{}] detected pointer at c1={} c2={} with radius {}". format(timer() - start, center, (x, y), radius)) return center else: print("center={} radius={}".format((x, y), radius)) print("[{}] no pointer detected".format(timer() - start)) def cleanup(self): print("CCamera: stop stream capture") self.capture.stop()
def generate_training_images(src=0, output=default_image_path, num_pics=10, name=None): detector = Detector(colors=[(0, 255, 0)]) if output == default_image_path: if name is None: name = str(uuid.uuid4()) output = os.path.sep.join([output, name]) if not os.path.exists(output): os.makedirs(output) imgs = [] vs = VideoStream(src=src) vs.start() sleep(2) snapped = False i = 0 while len(imgs) < num_pics or i < 3: frame = vs.read() copy = frame.copy() boxes_and_confs = detector.draw_boxes(copy) pic_num = len(imgs) + 1 cv2.putText(copy, '{} / {}'.format(pic_num, num_pics), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2) if float(i / 10) == 1.0: i = 1 if len(boxes_and_confs) == 1: imgs.append(frame) snapped = True elif i == 0: i += 1 elif i < 3 and snapped is True: white = (copy.shape[0], copy.shape[1], 1) copy = np.full(white, 254, dtype=np.uint8) elif i == 3 and snapped is True: snapped = False i += 1 cv2.imshow('Training Images', copy) cv2.waitKey(1) & 0xFF vs.stop() cv2.destroyAllWindows() for (i, img) in enumerate(imgs): cv2.imwrite(os.path.sep.join([output, str(i)]) + '.jpg', img)
def __init__(self): vs = VideoStream(src=0, usePiCamera=False) # if isinstance(vs.stream, WebcamVideoStream): # # Setting camera size is ignored or stops camera if camera doesn't support size. # vs.stream.stream.set(cv2.CAP_PROP_FRAME_WIDTH, 640) # vs.stream.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) vs.start() if isinstance(vs.stream, WebcamVideoStream): width = vs.stream.stream.get(cv2.CAP_PROP_FRAME_WIDTH) height = vs.stream.stream.get(cv2.CAP_PROP_FRAME_HEIGHT) print("Video frame size: %d x %d" % (width, height)) self.vs = vs
class Camera(object): def __init__(self, src=0, usb_camera=False, usb_port=-1, resolution=(100, 100), framerate=32): self._usb_camera = usb_camera self._usb_port = usb_port logger.info("Camera args: usb_camera %s usb_port: %s", usb_camera, usb_port) if self.use_video_stream(): logger.info("Using video stream") from imutils.video import VideoStream # Initialize the video stream self.__vs = VideoStream(src=src, usePiCamera=not usb_camera, resolution=resolution, framerate=framerate) self.__vs.start() # Allow the cammera sensor to warmup time.sleep(2.0) else: # On OSX, built-in camera use 0, usb cameras use 1 or greater if usb_port == -1: camera_num = 0 if is_raspi() or not self._usb_camera else 1 else: camera_num = usb_port logger.info("Not using video stream - camera_num %s", camera_num) self.__vc = VideoCapture(camera_num) self.__vc.set(cv2.CAP_PROP_FRAME_WIDTH, resolution[0]) self.__vc.set(cv2.CAP_PROP_FRAME_HEIGHT, resolution[1]) def use_video_stream(self): return not self._usb_camera and self._usb_port == -1 and is_raspi() def is_open(self): return True if self.use_video_stream() else self.__vc.isOpened() def read(self): return self.__vs.read() if self.use_video_stream() else self.__vc.read( )[1] def close(self): if self.use_video_stream(): self.__vs.stop() else: self.__vc.release() destroyAllWindows()
def test(): cam = VS(usePiCamera=0) cam.stream.stream.set(cv2.CAP_PROP_FPS, 32) cam.start() time.sleep(1) while 1: frame = cam.read() # print(frame) cv2.imshow('Frame', frame) if cv2.waitKey(1) & 0xff == ord('q'): break camera.stop() cv2.destroyAllWindows()
class RealCam(object): def __init__(self, src, fps=30, res=(320, 240)): self.res = res self.cap = VideoStream(src=src, resolution=res, framerate=fps) self.cap.stream.stream.set(cv.CAP_PROP_FRAME_WIDTH, 320) self.cap.stream.stream.set(cv.CAP_PROP_FRAME_HEIGHT, 240) self.cap.stream.stream.set(cv.CAP_PROP_FPS, fps) self.cap.start() def capture(self): return self.cap.read() def close(self): self.cap.stop()
def run_camera(self, validated_image_list: List[ValidatedImage], graph): VideoFaceMatcher.send_to_node("log", "Starting video stream...") camera_device = VideoStream(VideoFaceMatcher.CAMERA_INDEX) camera_device.stream.stream.set(cv2.CAP_PROP_FRAME_WIDTH, VideoFaceMatcher.REQUEST_CAMERA_WIDTH) camera_device.stream.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, VideoFaceMatcher.REQUEST_CAMERA_HEIGHT) camera_device.start() try: # Allow the camera sensor to warm up time.sleep(1.0) actual_camera_width = camera_device.stream.stream.get( cv2.CAP_PROP_FRAME_WIDTH) actual_camera_height = camera_device.stream.stream.get( cv2.CAP_PROP_FRAME_HEIGHT) VideoFaceMatcher.send_to_node( "log", "actual camera resolution: {} x {}".format( actual_camera_width, actual_camera_height)) fps = FPS().start() while not self.stopped: # Read image from camera, # ret_val, vid_image = camera_device.read() vid_image = camera_device.read() # if not ret_val: # VideoFaceMatcher.send_to_node("log", "No image from camera, exiting") # self.stop() # break fps.update() # run a single inference on the image and overwrite the # boxes and labels test_output, face_rects = VideoFaceMatcher.run_inference( vid_image, graph) matched_faces = VideoFaceMatcher.faces_match( validated_image_list, test_output) self.render_match_results(matched_faces, face_rects, vid_image) time.sleep(0.2) fps.stop() VideoFaceMatcher.send_to_node( "log", "Elapsed time: {:.2f}".format(fps.elapsed())) VideoFaceMatcher.send_to_node( "log", "Approx. FPS: {:.2f}".format(fps.fps())) finally: camera_device.stop()
class Camera: _stream: VideoStream def __init__(self): self._stream = VideoStream(usePiCamera=True, resolution=(640, 480)) self._stream.start() def get_latest_frame(self): return self._stream.read() def stop(self): self._stream.stop() def __del__(self): self.stop()
def scan(self): """ scan qr code to get information Return: barcodeData: a bytes object """ # initialize the video stream and allow the camera sensor to warm up print("[INFO] starting video stream...") video_stream_obj = VideoStream(src=0) video_stream = video_stream_obj.start() time.sleep(2.0) # found = set() # loop over the frames from the video stream while True: # grab the frame from the threaded video stream and resize it to # have a maximum width of 400 pixels frame = video_stream.read() frame = imutils.resize(frame, width=400) # find the barcodes in the frame and decode each of the barcodes barcodes = pyzbar.decode(frame) # loop over the detected barcodes for barcode in barcodes: # the barcode data is a bytes object so we convert it to a # string barcode_data = barcode.data.decode("utf-8") # barcodeType = barcode.type video_stream_obj.stop() return barcode_data
def publish_camera(PATH): """ Publish camera video stream to specified Kafka topic. Kafka Server is expected to be running on the localhost. Not partitioned. """ # Start up producer producer = KafkaProducer(bootstrap_servers='localhost:9092') cap = VideoStream(PATH) stream = cap.start() i = 0 t1 = time.time() try: while True: frame = stream.read() frame = cv2.resize( frame, (736, 480), # fx=0.6, fy=0.6, interpolation=cv2.INTER_AREA) ret, buffer = cv2.imencode('.jpg', frame) i += 1 if i % 1000 == 0: print("SEND", i, time.time() - t1) t1 = time.time() if i % 10 in [0, 1]: continue producer.send(topic, buffer.tobytes()) # Choppier stream, reduced load on processor # time.sleep(0.2) except: print("\nExiting.")
def main(): cam = VS(usePiCamera=0) cam.stream.stream.set(cv2.CAP_PROP_FPS, 90) # print(cam.stream.camera._get_shutter_speed()) # cam.stream.camera._set_shutter_speed(2000) # Take an image once every 2ms cam.start() stream = CS(host=host, port=12345) while 1: frame = cam.read() frame = cv2.cvtColor( frame, cv2.COLOR_BGR2GRAY ) # TODO: Find a way to get Grayscale images directly from PiCam stream.sendFrame(frame) if cv2.waitKey(1) & 0xff == ord('q'): break camera.stop() cv2.destroyAllWindows()
class Camera: def __init__(self, src=None, name='Front Door', width=600): self.src = src self.name = name self.width = width options = None self.pi = False if src is not None: options = {'src': src} elif platform.system() == 'Darwin': options = {'src': 0} else: options = {'usePiCamera': True} self.pi = True self.vs = VideoStream(**options) def start_stream(self): info('__START_VIDEO_STREAM__') self.vs.start() time.sleep(3) def loop(self, handle_frame): while True: frame = self.vs.read() if self.width and not self.pi: frame = imutils.resize(frame, width=self.width) frame, break_loop = handle_frame(frame) cv2.imshow(self.name, frame) key = cv2.waitKey(1) & 0xff if key == ord('q') or break_loop: break def stop_stream(self): info('__STOP_VIDEO_STREAM__') self.vs.stop() cv2.destroyAllWindows() def start(self, handle_frame=(lambda x: (x, False))): self.start_stream() self.loop(handle_frame) self.stop_stream()
def get_camera(): """ Returns a VideoStream object. It will try to start a VideoStream using the picamera, and if it that is unsuccessful, it will start a video stream using the default camera. :return: VideoStream object. """ try: # this will only run if it's on the pi vs = VideoStream(usePiCamera=True) time.sleep(0.5) vs.start() except: # if it's not running on the pi vs = VideoStream(src=0).start() time.sleep(2.0) return vs
class Camera: def __init__(self, port): self.port = port self.src = VideoStream(src=port + cv2.CAP_DSHOW) self.__start() time.sleep(2) def __start(self): self.src.start() def get_image_bgr(self): return self.src.read() def get_image_size(self): return list(self.get_image_bgr().shape)[:2] def stop(self): self.src.stop()
def numberOfFaces(): # Turn on LED setLed.ledON() #vs = VideoStream(usePiCamera=True).start() vs = VideoStream(usePiCamera=True) vs.start() # construct the argument parser and parse the arguments # load the known faces and embeddings along with OpenCV's Haar # cascade for face detection detector = cv2.CascadeClassifier( "/home/pi/MirageSmartMirror/src/haar_face_cascade.xml") # initialize the video stream and allow the camera sensor to warm up print("[INFO] starting video stream...") #vs = VideoStream(src=0).start() #vs = VideoStream(usePiCamera=True).start() time.sleep(2.0) # start the FPS counter # loop over frames from the video file stream # grab the frame from the threaded video stream and resize it # to 500px (to speedup processing) frame = vs.read() frame = cv2.rotate( frame, rotateCode=cv2.ROTATE_180) # Tried to rotate image - Amjad # print(frame) #cv2.imshow('video', frame) frame = imutils.resize(frame, width=500) # convert the input frame from (1) BGR to grayscale (for face # detection) and (2) from BGR to RGB (for face recognition) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # detect faces in the grayscale frame rects = detector.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) vs.stop() # Turn off LED setLed.ledOFF() return len(rects), rgb
class MyAlgoritm(threading.Thread): def __init__(self, src=0, resolution=(640, 480)): try: if src == 'picamera': # Picamera print('picamera') #self.cap = VideoStream(usePiCamera=True, resolution=resolution, framerate=32) self.cap = PiVideoStream(resolution=resolution, framerate=32) self.picameraCtrls(self.cap) else: # Webcam comum self.cap = VideoStream(src=src, resolution=resolution) except: print('camera offline') exit(0) self.stopLoop = False self.mutex = threading.Lock() threading.Thread.__init__(self) def read(self): return self.img_result def stop(self): self.stopLoop = True def imageShow(self, _img): with self.mutex: self.img_result = _img.copy() def run(self): self.cap.start() time.sleep(2) while not self.stopLoop: frame = self.cap.read() results = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) self.imageShow(results) if cv2.waitKey(1) == 27: self.stop() time.sleep(0.01) self.cap.stop()
def startBotVisionClient(self, server_ip): import socket # import needs to be here b/c same name as "from socket ..." on line 0 print("Entered the startBotVisionClient thread") global vs # initialize the ImageSender object with the socket address of server sender = imagezmq.ImageSender( connect_to="tcp://{}:5555".format(server_ip)) # get the host name, initialize the video stream, and allow the # camera sensor to warmup rpiName = socket.gethostname() vs = VideoStream(usePiCamera=True, resolution=(240, 144), framerate=25) vs.start() # vs = VideoStream(src=0).start() time.sleep(2.0) while True: # read the frame from the camera and send it to the server frame = vs.read() sender.send_image(rpiName, frame)
class Videofeed: def __init__(self, name="test"): self.name = name self.frame = None def start(self): for index in glob.glob("/dev/video?"): self.vs = VideoStream(index) self.vs.start() time.sleep(1.0) def stop(self): self.vs.stop() cv2.destroyAllWindows() def get_frame(self): self.frame = imutils.resize(self.vs.read(), width=480) b = io.BytesIO() Image.fromarray(cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)).save(b, 'jpeg') return b.getvalue() def set_frame(self, stream): self.frame = self.convert_to_frame(stream) self.show_frame(self.frame) def convert_to_frame(self, stream): self.frame = Image.open(io.BytesIO(stream)) self.frame = cv2.cvtColor(numpy.array(self.frame, dtype=numpy.uint8), cv2.COLOR_RGB2BGR) self.frame = cv2.flip(self.frame, 2) return self.frame def show_frame(self, frame): cv2.imshow(self.name, frame) key = cv2.waitKey(10) if key == 27: cv2.destroyAllWindows() return True
def read_feed(): cap = VideoStream(usePiCamera=True, resolution=(VIDEO_WIDTH, VIDEO_HEIGHT)) cap.start() time.sleep(2.0) frame = cap.read() # global VIDEO_HEIGHT, VIDEO_WIDTH # VIDEO_HEIGHT, VIDEO_WIDTH = frame.shape[:2] try: while True: frame = cap.read() jpeg_frame = cv2.imencode('.jpg', frame, [int(cv2.IMWRITE_JPEG_QUALITY), 80])[1] if VIDEO_IS_RECORDING: VIDEO_WRITER_QUEUE.put(jpeg_frame) #time.sleep(0.1) yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + jpeg_frame.tostring() + b'\r\n') finally: cap.stop()
class EspCam(object): def __init__(self, server, cam_ip, cam_name): self.name = cam_name self.stream = VideoStream("http://%s/" %(cam_ip)) self.stream.start() self.frame = self.stream.read() self.stopped = False self.sender = imagezmq.ImageSender(connect_to="tcp://%s:5555" %server) self.start() def start(self): while not self.stopped: self.frame = self.stream.read() if self.frame is None: self.stop() else: self.sender.send_image(self.name, self.frame) self.stream.stop() return def stop(self): self.stopped = True
class Cam(VideoStream): """Initializes the pi camera for capturing frames""" def __init__(self): self.boot = VideoStream(usePiCamera=True, resolution=(480, 352)) # 480, 352 self.stream = self.boot.start() self.frame = None def capture(self): self.frame = self.stream.read() def stop(self): self.stream.stop()
def faceCalibration(name): #Turn on LED setLed.ledON() vs = VideoStream(usePiCamera=True) # camera.start_preview() #path = "./Users/%s/" % name # camera = PiCamera() #simpleRec.vs.start() vs.start() time.sleep(2) path = "/home/pi/MirageSmartMirror/src/Users/%s/" % name try: os.mkdir(path) except OSError: print("Creation of the directory %s failed" % path) else: print("Successfully created the directory %s " % path) for i in range(5): if not (calibrationCancel): time.sleep(2) # camera.capture('/home/pi/MirageSmartMirror/src/Faces/%s/image%s.jpg' % (name , i)) frame = vs.read() frame = cv2.rotate( frame, rotateCode=cv2.ROTATE_180) # Tried to rotate image - Amjad pathImage = '/home/pi/MirageSmartMirror/src/Users/%s/image%s.jpg' % ( name, i) cv2.imwrite(pathImage, frame) # camera.stop_preview() else: break vs.stop() #subprocess.call("python3 /home/pi/MirageSmartMirror/src/faceEncoding.py &", shell=True) return
import math import random parser = argparse.ArgumentParser() parser.add_argument("-predictor", required=True, help="path to predictor") args = parser.parse_args() print("starting program.") print("'s' starts drawing eyes.") print("'r' to toggle recording image, and 'q' to quit") cam = VideoStream() cam.stream.stream.set(3, 1280) cam.stream.stream.set(4, 720) vs = cam.start() time.sleep(.5) # this detects our face detector = dlib.get_frontal_face_detector() # and this predicts our face's orientation predictor = dlib.shape_predictor(args.predictor) recording = False counter = 0 # get our first frame outside of loop, so we can see how our # webcam resized itself, and it's resolution w/ np.shape frame = vs.read() #frame = resize(frame, width=800)