Python picamera.PiCamera() Examples

The following are 30 code examples of picamera.PiCamera(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module picamera , or try the search function .
Example #1
Source File: pi-timolo81.py    From pi-timolo with MIT License 7 votes vote down vote up
def __init__(self, resolution=(CAMERA_WIDTH, CAMERA_HEIGHT), framerate=CAMERA_FRAMERATE, rotation=0, hflip=False, vflip=False):
        # initialize the camera and stream
        try:
           self.camera = PiCamera()
        except:
           print("ERROR - PiCamera Already in Use by Another Process")
           print("INFO  - Exit %s" % progName)
           quit()
        self.camera.resolution = resolution
        self.camera.framerate = framerate
        self.camera.hflip = hflip
        self.camera.vflip = vflip
        self.camera.rotation = rotation
        self.rawCapture = PiRGBArray(self.camera, size=resolution)
        self.stream = self.camera.capture_continuous(self.rawCapture,
            format="bgr", use_video_port=True)
        # initialize the frame and the variable used to indicate
        # if the thread should be stopped
        self.frame = None
        self.stopped = False 
Example #2
Source File: video_cam.py    From ncappzoo with MIT License 6 votes vote down vote up
def __init__(self, cam_type):
        self.cam_width = res_width
        self.cam_height = res_height
        self.camera_type = cam_type
        self.camera = None
        self.rawCapture = None

        if cam_type == "camerapi":
            log.info("Loading Camera Pi")
            self.camera = PiCamera()
            self.camera.resolution = (self.cam_width, self.cam_height)

        elif cam_type == "usb":
            camera_id = 0
            log.info("Loading USB Camera id {}".format(camera_id))
            self.camera = cv2.VideoCapture(camera_id)
            self.camera.set(cv2.CAP_PROP_FPS, 30)
            self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, self.cam_width)
            self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, self.cam_height)

        log.info("Camera size {}x{}".format(self.cam_width, self.cam_height)) 
Example #3
Source File: camera_pi.py    From object-detection with MIT License 6 votes vote down vote up
def frames():
        with PiCamera() as camera:
            camera.rotation = int(str(os.environ['CAMERA_ROTATION']))
            stream = io.BytesIO()
            for _ in camera.capture_continuous(stream, 'jpeg',
                                               use_video_port=True):
                # return current frame
                stream.seek(0)
                _stream = stream.getvalue()
                data = np.fromstring(_stream, dtype=np.uint8)
                img = cv2.imdecode(data, 1)
                yield img

                # reset stream for next frame
                stream.seek(0)
                stream.truncate() 
Example #4
Source File: pi-timolo81.py    From pi-timolo with MIT License 6 votes vote down vote up
def getStreamImage(isDay):
    # Capture an image stream to memory based on daymode
    with picamera.PiCamera() as camera:
        camera.resolution = (testWidth, testHeight)
        with picamera.array.PiRGBArray(camera) as stream:
            if isDay:
                camera.exposure_mode = 'auto'
                camera.awb_mode = 'auto'
                time.sleep(motionCamSleep)   # sleep so camera can get AWB
            else:
                # use variable framerate_range for Low Light motion image stream
                camera.framerate_range = (Fraction(1, 6), Fraction(30, 1))
                time.sleep(2) # Give camera time to measure AWB
                camera.iso = nightMaxISO
            camera.capture(stream, format='rgb', use_video_port=useVideoPort)
            camera.close()
            return stream.array

#----------------------------------------------------------------------------------------------- 
Example #5
Source File: pi-timolo81.py    From pi-timolo with MIT License 6 votes vote down vote up
def takeDayImage(filename, cam_sleep_time):
    # Take a Day image using exp=auto and awb=auto
    with picamera.PiCamera() as camera:
        camera.resolution = (imageWidth, imageHeight)
        camera.framerate = 80
        camera.vflip = imageVFlip
        camera.hflip = imageHFlip
        camera.rotation = imageRotation # Valid values 0, 90, 180, 270
        # Day Automatic Mode
        camera.exposure_mode = 'auto'
        camera.awb_mode = 'auto'
        time.sleep(cam_sleep_time)   # use motion or TL camera sleep to get AWB
        if imagePreview:
            camera.start_preview()
        if imageFormat == ".jpg" :
            camera.capture(filename, use_video_port=useVideoPort, format='jpeg',quality=imageJpegQuality)
        else:
            camera.capture(filename, use_video_port=useVideoPort)
        camera.close()
    logging.info("camSleepSec=%.2f exp=auto awb=auto Size=%ix%i "
              % ( cam_sleep_time, imageWidth, imageHeight ))
    if not showDateOnImage:   # showDateOnImage displays FilePath so avoid showing twice
        logging.info("FilePath  %s" % (filename))

#----------------------------------------------------------------------------------------------- 
Example #6
Source File: balloon_video.py    From ardupilot-balloon-finder with GNU General Public License v3.0 6 votes vote down vote up
def init_camera(self):
        # return immediately if already initialised
        if not self.camera is None:
            return
 
        # use webcam
        if self.camera_type == 0:
            self.camera = cv2.VideoCapture(0)
            #self.camera.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH,self.img_width)
            #self.camera.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT,self.img_height)

            # check we can connect to camera
            if not self.camera.isOpened():
                print "failed to open camera, exiting!"
                sys.exit(0)

        # use rpi camera
        if self.camera_type == 1:
            self.camera = PiCamera()
            self.camera.resolution = (self.img_width,self.img_height)
            # to-do: check we can connect to camera

    # close camera 
Example #7
Source File: spectrometer.py    From RPiSpectrometer with MIT License 6 votes vote down vote up
def take_picture(name, shutter):
    print("initialising camera")
    camera = picamera.PiCamera()
    try:
        print("allowing camera to warmup")
        camera.vflip = True
        camera.framerate = Fraction(1, 2)
        camera.shutter_speed = shutter
        camera.iso = 100
        camera.exposure_mode = 'off'
        camera.awb_mode = 'off'
        camera.awb_gains = (1, 1)
        time.sleep(3)
        print("capturing image")
        camera.capture(name, resize=(1296, 972))
    finally:
    	camera.close()
    return name 
Example #8
Source File: service.py    From Plastic-Detection-Model with MIT License 6 votes vote down vote up
def postImg():
	
    with picamera.PiCamera() as camera:
        print("Opening Camera.")
        time.sleep(2)
        camera.capture(imagePath)
        camera.close()
        print("Image Captured!")
    
    imageFile = open(imagePath, "rb")
    imageBytes = base64.b64encode(imageFile.read())
    print("Sending image to cloud server for analysis.")
    response = requests.post(
		"http://174.138.58.241/detect",
		data=imageBytes
	)
	
    print("Response received!")
    response_data = response.json()
    print(response_data) 
Example #9
Source File: picam.py    From MMM-Facial-Recognition-OCV3 with MIT License 6 votes vote down vote up
def run(self):
        with picamera.PiCamera() as camera:
            camera.resolution = (620, 540)
            if self.preview:
                camera.start_preview(fullscreen=False, window = (100, 20, 620, 540))
            stream = io.BytesIO()
            for stream in camera.capture_continuous(stream, format='jpeg', use_video_port=True):
                self.lock.acquire()
                try:
                    # swap the stream for the buffer
                    temp = stream
                    stream = self.buffer
                    self.buffer = temp
                    stream.truncate()
                    stream.seek(0)
                finally:
                    self.lock.release()
                if self.running is False:
                    break
            if self.preview:
                camera.stop_preview() 
Example #10
Source File: pi-timolo.py    From pi-timolo with MIT License 6 votes vote down vote up
def __init__(self, resolution=(CAMERA_WIDTH, CAMERA_HEIGHT),
                 framerate=CAMERA_FRAMERATE,
                 rotation=0,
                 hflip=False, vflip=False):
        # initialize the camera and stream
        try:
            self.camera = PiCamera()
        except:
            logging.error("PiCamera Already in Use by Another Process")
            logging.error("Exiting %s Due to Error", progName)
            exit(1)
        self.camera.resolution = resolution
        self.camera.framerate = framerate
        self.camera.hflip = hflip
        self.camera.vflip = vflip
        self.camera.rotation = rotation
        self.rawCapture = PiRGBArray(self.camera, size=resolution)
        self.stream = self.camera.capture_continuous(self.rawCapture,
                                                     format="bgr",
                                                     use_video_port=True)
        # initialize the frame and the variable used to indicate
        # if the thread should be stopped
        self.thread = None   # Initialize thread
        self.frame = None
        self.stopped = False 
Example #11
Source File: PiCamera.py    From calvin-base with Apache License 2.0 6 votes vote down vote up
def _p_read_image(self):
        import base64
        import io
        stream = io.BytesIO()
        with picamera.PiCamera() as cam:
            cam.rotation = self._rotation
            cam.resolution = self._resolution
            if self._label:
                cam.annotate_text = self._label
            cam.start_preview()
            if self._rescale:
                cam.capture(stream, format="jpeg", resize=self._rescale, use_video_port=True)
            else :
                cam.capture(stream, format="jpeg", use_video_port=True)
        stream.seek(0)
        return base64.b64encode(stream.read()) 
Example #12
Source File: PiCamera.py    From calvin-base with Apache License 2.0 6 votes vote down vote up
def init(self, mode, label=None, width=None, height=None, rotation=0, **kwargs):
        self._in_progress = None
        self._b64image = None
        mode = mode.split("x")
        self._resolution = (int(mode[0]), int(mode[1]))
        if width and height:
            self._rescale = (width, height)
        else :
            self._rescale = None
        self._label = label
        self._rotation = rotation
        self._camera = picamera.PiCamera()
        self._camera.rotation = self._rotation
        self._camera.resolution = self._resolution
        if self._label:
            self._camera.annotate_text = self._label
        self._camera.start_preview() 
Example #13
Source File: pi-timolo.py    From pi-timolo with MIT License 6 votes vote down vote up
def takeDayImage(filename, cam_sleep_time):
    # Take a Day image using exp=auto and awb=auto
    with picamera.PiCamera() as camera:
        camera.resolution = (imageWidth, imageHeight)
        camera.framerate = 80
        camera.vflip = imageVFlip
        camera.hflip = imageHFlip
        camera.rotation = imageRotation # Valid values 0, 90, 180, 270
        # Day Automatic Mode
        camera.exposure_mode = 'auto'
        camera.awb_mode = 'auto'
        time.sleep(cam_sleep_time)   # use motion or TL camera sleep to get AWB
        if imagePreview:
            camera.start_preview()
        if imageFormat == ".jpg" :
            camera.capture(filename, use_video_port=useVideoPort, format='jpeg',quality=imageJpegQuality)
        else:
            camera.capture(filename, use_video_port=useVideoPort)
        camera.close()
    logging.info("camSleepSec=%.2f exp=auto awb=auto Size=%ix%i "
              % ( cam_sleep_time, imageWidth, imageHeight ))
    if not showDateOnImage:   # showDateOnImage displays FilePath so avoid showing twice
        logging.info("FilePath  %s" % (filename))

#----------------------------------------------------------------------------------------------- 
Example #14
Source File: pimotion.py    From pimotion with MIT License 6 votes vote down vote up
def start(self):
        with picamera.PiCamera() as camera:
            camera.resolution = (1280, 960)
            camera.framerate = 10

            handler = CaptureHandler(camera, self.post_capture_callback)

            self.__print('Waiting 2 seconds for the camera to warm up')
            time.sleep(2)

            try:
                self.__print('Started recording')
                camera.start_recording(
                    '/dev/null', format='h264',
                    motion_output=MyMotionDetector(camera, handler)
                )

                while True:
                    handler.tick()
                    time.sleep(1)
            finally:
                camera.stop_recording()
                self.__print('Stopped recording') 
Example #15
Source File: mypivideostream.py    From hardware_demo with MIT License 6 votes vote down vote up
def __init__(self, resolution=(640, 480), framerate=32, save_image_interval=1):
        '''
        @param save_image_interval, interval in sec to save imave
        '''
        # initialize the camera and stream
        self.camera = PiCamera()
        self.camera.resolution = resolution
        self.camera.framerate = framerate
        self.rawCapture = PiRGBArray(self.camera, size=resolution)
        self.stream = self.camera.capture_continuous(self.rawCapture,
            format="bgr", use_video_port=True)

        # initialize the frame and the variable used to indicate
        # if the thread should be stopped
        self.frame = None
        self.rects = [] # list of matching faces
        self.stopped = False 
Example #16
Source File: capture.py    From r_e_c_u_r with GNU General Public License v3.0 6 votes vote down vote up
def create_capture_device(self):
        if self.data.settings['capture']['TYPE']['value'] != 'usb':
            if self.use_capture:
                if self.piCapture_with_no_source():
                    return False
                self.update_capture_settings()
                
                try:
                    self.device = picamera.PiCamera(resolution=self.resolution, framerate=self.framerate, sensor_mode = self.sensor_mode)
                    return True
                except picamera.exc.PiCameraError as e:
                    self.use_capture = False
                    self.data.settings['capture']['DEVICE']['value'] = 'disabled'
                    print('camera exception is {}'.format(e))
                    self.message_handler.set_message('INFO', 'no capture device attached')
                    return False 
Example #17
Source File: rpis_camera.py    From rpi-security with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, photo_size, gif_size, motion_size, camera_vflip,
            camera_hflip, camera_capture_length, motion_detection_threshold,
            camera_mode):
        self.photo_size = photo_size
        self.gif_size = gif_size
        self.camera_vflip = camera_vflip
        self.camera_hflip = camera_hflip
        self.lock = Lock()
        self.queue = Queue()
        self.motion_framerate = 5
        self.motion_size = motion_size
        self.motion_detection_threshold = motion_detection_threshold
        self.temp_directory = '/var/tmp'
        self.camera_save_path = '/var/tmp'
        self.camera_capture_length = camera_capture_length
        self.camera_mode = camera_mode
        self.motion_detection_running = False
        self.too_dark_message_printed = False

        try:
            self.camera = PiCamera()
            self.camera.vflip = self.camera_vflip
            self.camera.hflip = self.camera_hflip
        except Exception as e:
            exit_error('Camera module failed to intialise with error {0}'.format(repr(e))) 
Example #18
Source File: image_processor.py    From aws-greengrass-mini-fulfillment with Apache License 2.0 6 votes vote down vote up
def __init__(self, res_width=96, res_height=96):
        self.camera = picamera.PiCamera(resolution=(res_width, res_height))
        # TODO propagate configurable resolution through '96' logic below

        self.camera.hflip = True
        self.camera.vflip = True
        self.res_width = res_width
        self.res_height = res_height
        self.stream = picamera.array.PiYUVArray(self.camera)
        self.pixelObjList = []
        self.object_id_center = 0
        self.pixelObjList.append(PixelObject(self.next_obj_id()))
        self.max_pixel_count = 0
        self.largest_object_id = 0
        self.largest_X = 0
        self.largest_Y = 0
        self.filename = '' 
Example #19
Source File: camera.py    From pi-tracking-telescope with MIT License 6 votes vote down vote up
def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        #self.video = cv2.VideoCapture(0)
        self.camera = PiCamera()
        #self.rawCapture = PiRGBArray(self.camera)
        self.camera.resolution = (640, 480)
        self.camera.framerate = 32
        self.rawCapture = PiRGBArray(self.camera, size=(640, 480))
 
        
        # allow the camera to warmup
        time.sleep(0.1)

        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4') 
Example #20
Source File: pi-timolo.py    From pi-timolo with MIT License 6 votes vote down vote up
def getStreamImage(isDay):
    # Capture an image stream to memory based on daymode
    with picamera.PiCamera() as camera:
        camera.resolution = (testWidth, testHeight)
        with picamera.array.PiRGBArray(camera) as stream:
            if isDay:
                camera.exposure_mode = 'auto'
                camera.awb_mode = 'auto'
                time.sleep(motionCamSleep)   # sleep so camera can get AWB
            else:
                # use variable framerate_range for Low Light motion image stream
                camera.framerate_range = (Fraction(1, 6), Fraction(30, 1))
                time.sleep(2) # Give camera time to measure AWB
                camera.iso = nightMaxISO
            camera.capture(stream, format='rgb', use_video_port=useVideoPort)
            camera.close()
            return stream.array

#----------------------------------------------------------------------------------------------- 
Example #21
Source File: camera.py    From pi-tracking-telescope with MIT License 6 votes vote down vote up
def setupRpiCam(self):
        # import the necessary packages
        from picamera.array import PiRGBArray
        from picamera import PiCamera
        
        # initialize the camera and grab a reference to the raw camera capture
        camera = PiCamera()
        camera.resolution = (self.width, self.height)
        camera.framerate = self.fps
        camera.crop = (0.0, 0.0, 1.0, 1.0)
        self.camera = camera
        self.rawCapture = PiRGBArray(camera, size=(self.width, self.height))
        self.rgb = bytearray(self.width * self.height * 3)
        self.yuv = bytearray(self.width * self.height * 3 / 2)
        
        # wait for camera to warm up
        time.sleep(0.1) 
Example #22
Source File: capture.py    From rpi-vision with MIT License 6 votes vote down vote up
def __init__(self, resolution=(320, 240), framerate=24, vflip=True, hflip=True):
        self.camera = PiCamera()
        self.camera.resolution = resolution
        self.camera.framerate = framerate
        self.camera.vflip = vflip
        self.camera.hflip = hflip
        self.camera.rotation = 270

        self.data_container = PiRGBArray(self.camera, size=resolution)

        self.stream = self.camera.capture_continuous(
            self.data_container, format="bgr", use_video_port=True
        )

        self.frame = None
        self.stopped = False
        print('starting camera preview')
        self.camera.start_preview() 
Example #23
Source File: server.py    From compoundpi with GNU General Public License v2.0 6 votes vote down vote up
def serve_forever(self):
        # seed the random number generator from the system clock
        random.seed()
        logging.info('Initializing camera')
        self.server.seqno = 0
        self.server.client_address = None
        self.server.client_timestamp = None
        self.server.responders = {}
        self.server.files = []
        self.server.camera = picamera.PiCamera()
        try:
            logging.info('Starting server thread')
            thread = threading.Thread(target=self.server.serve_forever)
            thread.start()
            while thread.is_alive():
                thread.join(1)
            logging.info('Server thread ended')
        finally:
            logging.info('Closing camera')
            self.server.camera.close() 
Example #24
Source File: camera_worker.py    From mudpi-core with MIT License 6 votes vote down vote up
def init(self):
		try:
			self.camera = PiCamera(resolution=(self.resolutionX, self.resolutionY))
			# Below we calibrate the camera for consistent imaging
			self.camera.framerate = 30
			# Wait for the automatic gain control to settle
			time.sleep(2)
			# Now fix the values
			self.camera.shutter_speed = self.camera.exposure_speed
			self.camera.exposure_mode = 'off'
			g = self.camera.awb_gains
			self.camera.awb_mode = 'off'
			self.camera.awb_gains = g
		except:
			self.camera = PiCamera()

		#Pubsub Listeners
		self.pubsub = variables.r.pubsub()
		self.pubsub.subscribe(**{self.topic: self.handleEvent})

		print('Camera Worker...\t\t\t\033[1;32m Ready\033[0;0m')
		return 
Example #25
Source File: main.py    From iotedge-scott-or-not with MIT License 5 votes vote down vote up
def obj_camera():
    if os.environ.get('DEVICE') == 'RPI':
        print( "\nRunning on linux...")
        import picamera
        camera = picamera.PiCamera()
        camera.rotation = 180
        camera.resolution = (640, 480)
        camera.start_preview()
        return camera
    else:
        from utils import camera
        return camera 
Example #26
Source File: camera_pi.py    From flask-video-streaming with MIT License 5 votes vote down vote up
def frames():
        with picamera.PiCamera() as camera:
            # let camera warm up
            time.sleep(2)

            stream = io.BytesIO()
            for _ in camera.capture_continuous(stream, 'jpeg',
                                                 use_video_port=True):
                # return current frame
                stream.seek(0)
                yield stream.read()

                # reset stream for next frame
                stream.seek(0)
                stream.truncate() 
Example #27
Source File: camera.py    From oreilly-flask-apis-video with MIT License 5 votes vote down vote up
def __init__(self):
        super(PiCamera, self).__init__()
        self.camid = 'pi' 
Example #28
Source File: camera.py    From oreilly-flask-apis-video with MIT License 5 votes vote down vote up
def capture(self):
        """Capture a picture."""
        filename = self.get_new_photo_filename()
        with picamera.PiCamera() as camera:
            camera.resolution = (1024, 768)
            camera.hflip = True
            camera.vflip = True
            camera.start_preview()
            time.sleep(2)  # wait for camera to warm up
            camera.capture(self.camid + '/' + filename)
        return filename 
Example #29
Source File: camera.py    From oreilly-flask-apis-video with MIT License 5 votes vote down vote up
def capture_timelapse(self, count, interval):
        """Capture a time lapse."""
        filename = self.get_new_photo_filename('_{0:03d}_{1:03d}')
        with picamera.PiCamera() as camera:
            camera.resolution = (1024, 768)
            camera.hflip = True
            camera.vflip = True
            camera.start_preview()
            time.sleep(2)  # wait for camera to warm up
            for i in range(count):
                camera.capture(self.camid + '/' + filename.format(i, count))
                time.sleep(interval)
        return filename.format(0, count) 
Example #30
Source File: hardware_test.py    From rpi-deep-pantilt with MIT License 5 votes vote down vote up
def camera_test(rotation):
    camera = PiCamera()
    camera.rotation = rotation
    logging.info('Starting Raspberry Pi Camera')
    camera.start_preview()

    try:
        while True:
            continue
    except KeyboardInterrupt:
        logging.info('Stopping Raspberry Pi Camera')
        camera.stop_preview()