Python picamera 模块,PiCamera() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用picamera.PiCamera()

项目:aws-greengrass-mini-fulfillment    作者:awslabs    | 项目源码 | 文件源码
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 = ''
项目:StratoBalloon    作者:delattreb    | 项目源码 | 文件源码
def getpicture(self, connection, cursor):
        if PiCamera is not None:
            dalcamera = dal_camera.DAL_Camera(connection, cursor)
            dalpicture = dal_picture.DAL_Picture(connection, cursor)

            index = dalcamera.get_last_picture_id()
            name = self.path + self.imgName + str(index) + '.' + self.format
            # self.camera.start_preview()
            # sleep(2)
            self.camera.capture(name, bayer = True, quality = self.quality, format = self.format)

            dalcamera.set_last_picture_id(index + 1)
            dalpicture.setpicture(name)

            logger = com_logger.Logger(self.cameranumber)
            logger.info('Picture taken:' + name)
项目:StratoBalloon    作者:delattreb    | 项目源码 | 文件源码
def getvideo(self, duration, connection, cursor):
        if PiCamera is not None:
            dal = dal_camera.DAL_Camera(connection, cursor)
            dalpicture = dal_picture.DAL_Picture(connection, cursor)

            index = dal.get_last_video_id()
            name = self.path + self.vidName + str(index) + '.h264'
            self.camera.start_recording(name)
            sleep(duration)
            self.camera.stop_recording()

            dal.set_last_video_id(index + 1)
            dalpicture.setvideo(name)

            logger = com_logger.Logger(self.cameranumber)
            logger.debug('Video taken: ' + name)
项目:hardware_demo    作者:llSourcell    | 项目源码 | 文件源码
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
项目:burro    作者:yconst    | 项目源码 | 文件源码
def __init__(self, resolution=config.camera.resolution,
                 framerate=config.camera.framerate,
                 rotation=config.camera.rotation, **kwargs):
        from picamera.array import PiRGBArray
        from picamera import PiCamera

        super(PiVideoStream, self).__init__(resolution, **kwargs)

        self.camera = PiCamera()
        self.camera.resolution = resolution
        self.camera.framerate = framerate
        self.camera.rotation = rotation
        self.camera.exposure_mode = "sports"
        self.rawCapture = PiRGBArray(self.camera, size=resolution)

        self.frame = None
        self.stopped = False

        logging.info("PiVideoStream loaded.. .warming camera")

        time.sleep(2)
        self.start()
项目:Flashlapse_NEO    作者:flashlapsedev    | 项目源码 | 文件源码
def run(self):
        global current, current_image, file_list, file
        for i in range(total):
            current = i
            sleep(0.2)
            current_image = file % i
            self.imaging_running.emit()
            with PiCamera() as camera:
                sleep(0.8)
                camera.resolution = (2464,2464)
                camera._set_rotation(180)
                camera.capture(current_image)
            self.imaging_running_done.emit()
            self.capture.emit()
            sleep(interval-1)
            file_list.append(current_image)
            if(current%(0.1*total)==0):
                self.check_point.emit()
项目:party-pi    作者:JustinShenk    | 项目源码 | 文件源码
def setup_picamera(self):
        """ Set up piCamera for rasbperry pi camera module.

        """
        from picamera import PiCamera
        from picamera.array import PiRGBArray
        piCamera = PiCamera()
        # self.piCamera.resolution = (640, 480)
        piCamera.resolution = self.resolution[0], self.resolution[1]
        self.screenwidth, self.screenheight = piCamera.resolution
        # self.piCamera.framerate = 10
        piCamera.hflip = True
        piCamera.brightness = 55
        self.rawCapture = PiRGBArray(
            piCamera, size=(self.screenwidth, self.screenheight))
        time.sleep(1)
        return piCamera
项目:donkey    作者:wroscoe    | 项目源码 | 文件源码
def __init__(self, resolution=(120, 160), framerate=20):
        from picamera.array import PiRGBArray
        from picamera import PiCamera
        resolution = (resolution[1], resolution[0])
        # initialize the camera and stream
        self.camera = PiCamera() #PiCamera gets resolution (height, width)
        self.camera.resolution = resolution
        self.camera.framerate = framerate
        self.rawCapture = PiRGBArray(self.camera, size=resolution)
        self.stream = self.camera.capture_continuous(self.rawCapture,
            format="rgb", use_video_port=True)

        # initialize the frame and the variable used to indicate
        # if the thread should be stopped
        self.frame = None
        self.on = True

        print('PiCamera loaded.. .warming camera')
        time.sleep(2)
项目:ivport-v2    作者:ivmech    | 项目源码 | 文件源码
def remove_overlay(self, overlay):
        """
        Removes a static overlay from the preview output.

        This method removes an overlay which was previously created by
        :meth:`add_overlay`. The *overlay* parameter specifies the
        :class:`PiRenderer` instance that was returned by :meth:`add_overlay`.

        .. versionadded:: 1.8
        """
        if not overlay in self._overlays:
            raise PiCameraValueError(
                "The specified overlay is not owned by this instance of "
                "PiCamera")
        overlay.close()
        self._overlays.remove(overlay)
项目:ivport-v2    作者:ivmech    | 项目源码 | 文件源码
def remove_overlay(self, overlay):
        """
        Removes a static overlay from the preview output.

        This method removes an overlay which was previously created by
        :meth:`add_overlay`. The *overlay* parameter specifies the
        :class:`~picamera.renderers.PiRenderer` instance that was returned by
        :meth:`add_overlay`.

        .. versionadded:: 1.8
        """
        if not overlay in self._overlays:
            raise PiCameraRuntimeError(
                "The specified overlay is not owned by this instance of "
                "PiCamera")
        overlay.close()
        self._overlays.remove(overlay)
项目:ivport-v2    作者:ivmech    | 项目源码 | 文件源码
def remove_overlay(self, overlay):
        """
        Removes a static overlay from the preview output.

        This method removes an overlay which was previously created by
        :meth:`add_overlay`. The *overlay* parameter specifies the
        :class:`PiRenderer` instance that was returned by :meth:`add_overlay`.

        .. versionadded:: 1.8
        """
        if not overlay in self._overlays:
            raise PiCameraValueError(
                "The specified overlay is not owned by this instance of "
                "PiCamera")
        overlay.close()
        self._overlays.remove(overlay)
项目:pytRobot    作者:ggljzr    | 项目源码 | 文件源码
def capture_img(img_path='img.jpg', res=(1024,768), vflip=True):
    """
    Captures image with PiCamera and saves it to given path.
    It cannot be used when camera is active 
    (for example when it is used by mjpg-streamer). In that case
    exception ``PiCameraMMALError`` will be raised.
    """
    camera = PiCamera()

    camera.resolution = res
    camera.vflip = vflip

    print('CAMERA: Capturing image...')
    camera.capture(img_path)
    print('CAMERA: Image saved in {}'.format(img_path))

    camera.close()
项目:AI-Robot    作者:ssebastian    | 项目源码 | 文件源码
def __enter__(self):
        self.camera = picamera.PiCamera()
        self.camera.__enter__()
        self.camera.contrast = 60
        self.camera.brightness = 50
        self.camera.resolution = (640,480)
        self.camera.frame_rate = 24
        sleep(1)
        self.camera.start_preview()

        self.camera_stream = picamera.PiCameraCircularIO(self.camera, size=640*480*3)
        self.camera.start_recording(self.camera_stream, format='rgb')
        self.camera.wait_recording(1)
        #self.camera.awb_mode = 'off'
        #self.camera.awb_gains = (1.8, 1.5)
        #self.camera.shutter_speed = 30000
        #self.camera.exposure_mode = 'off'
        #sleep(20)
        return self
项目:rasberrypi-trapcamera    作者:Scifabric    | 项目源码 | 文件源码
def _capture(config):
    """Capture a photo and save it to a file."""
    messages = []
    try:
        with picamera.PiCamera() as camera:
            camera = _setup_camera(config, camera)
            file_name = _set_photo_name(config.data)
            camera.capture(file_name)
            msg = dict(msg="Image captured: %s" % file_name, fg='green')
            messages.append(msg)
    except (PiCameraValueError, ValueError) as e:
        msg = "ERROR: PiCamera %s" % e.message
        messages.append(dict(msg=msg, fg='red'))
        file_name = None
    except:
        messages.append(dict(msg="ERROR: PiCamera not working properly",
                             fg='red'))
        messages.append(dict(msg="INFO: Using a stock image as the captured one.",
                    fg='yellow'))
        file_name = _set_photo_name(config.data)
        file_name = _get_stock_photo(file_name)
        msg = "Image captured: %s" % file_name
        messages.append(dict(msg=msg, fg='green'))
    return messages, file_name
项目:MMM-Facial-Recognition    作者:paviro    | 项目源码 | 文件源码
def run(self):
        with picamera.PiCamera() as camera:
            camera.resolution = (620, 540)
            camera.framerate = 10
            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 == False:
                    break

            camera.stop_preview()
项目:photoberry    作者:briandilley    | 项目源码 | 文件源码
def start_preview(self, **options):
        """
        Starts the preview.
        :param options: See :meth:`~picamera.camera.PiCamera.start_preview`
        """

        self.camera.rotation = 180
        self.preview_renderer = self.camera.start_preview(**options)

        wait = 0
        while True:
            if self.preview_renderer.window[2] > 0:
                break
            wait += 1
            if wait > 10:
                raise RuntimeError('Waited longer than 10 seconds for preview window')
            sleep(1)

        return self.preview_renderer
项目:photoberry    作者:briandilley    | 项目源码 | 文件源码
def add_overlay(self, source, size=None, **options):
        """
        Adds an overlay
        :param source: the source
        :param options: See :meth:`~picamera.camera.PiCamera.add_overlay`
        :param size: See :meth:`~picamera.camera.PiCamera.add_overlay`
        """

        overlay = self.camera.add_overlay(source, size=size, **options)

        wait = 0
        while True:
            if overlay.window[2] > 0:
                break
            wait += 1
            if wait > 10:
                raise RuntimeError('Waited longer than 10 seconds for overlay window')
            sleep(1)

        return overlay
项目:speed-camera    作者:pageauc    | 项目源码 | 文件源码
def __init__(self, resolution=(CAMERA_WIDTH, CAMERA_HEIGHT), framerate=CAMERA_FRAMERATE, rotation=0,
                                                   hflip=CAMERA_HFLIP, vflip=CAMERA_VFLIP):
        # 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.rotation = rotation
        self.camera.framerate = framerate
        self.camera.hflip = hflip
        self.camera.vflip = vflip
        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
项目:garage-door    作者:denniskline    | 项目源码 | 文件源码
def take_picture(self, photoDir, overlayMessage=None):
        logging.debug('taking a picture')
        if not os.path.exists(photoDir):
            os.makedirs(photoDir)
        fileName = ('{}_gd_photo.jpg'.format(datetime.datetime.now().strftime("%H%M%S")))
        file = ('{}/{}'.format(photoDir, fileName))

        overlay = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if overlayMessage is not None:
            overlay += ('  {}'.format(overlayMessage))

        camera = picamera.PiCamera()
        try:
            camera.resolution = (1024, 768)
            camera.rotation = 90
            camera.annotate_background = picamera.Color('black')
            camera.annotate_text = overlay
            camera.capture(file)
        finally:
            camera.close()

        return file
项目:MMM-Facial-Recognition-Tools    作者:paviro    | 项目源码 | 文件源码
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()
项目:Sample-Code    作者:meigrafd    | 项目源码 | 文件源码
def picam_pic( ToPath='/tmp/', Resolution=(1024,768), Format='jpeg', Quality=100, Led=False ):
    try:
        with picamera.PiCamera() as camera:
            camera.led = Led
            camera.resolution = Resolution
            camera.start_preview()
            # Camera warm-up time
            time.sleep(2)
            if Format == 'jpeg':
                for filename in camera.capture_continuous(ToPath + '{timestamp:%d.%m_%H-%M-%S}Uhr.jpg', format=Format, quality=Quality):
                    print 'Captured %s' % filename
                    break
            else:
                for filename in camera.capture_continuous(ToPath + '{timestamp:%d.%m_%H-%M-%S}Uhr.' + str(Format), format=Format):
                    print 'Captured %s' % filename
                    break
            camera.stop_preview()
    except Exception, error:
        print 'Error in picam_pic: ' + str(error)
项目:Sample-Code    作者:meigrafd    | 项目源码 | 文件源码
def main():
    print('Initializing camera')
    with picamera.PiCamera() as camera:
        camera.resolution = (WIDTH, HEIGHT)
        camera.framerate = FRAMERATE
        sleep(1) # camera warm-up time
        print('Initializing twitch stream output')
        output = BroadcastOutput(camera, BITRATE, SERVER_URL, STREAM_KEY)
        print('Starting recording')
        camera.start_recording(output, 'yuv')
        try:
            while True:
                camera.wait_recording(1)
        except KeyboardInterrupt:
            pass
        finally:
            print('Stopping recording')
            camera.stop_recording()
项目:Sommarprojekt16    作者:fregu856    | 项目源码 | 文件源码
def video_thread():
    # enable the thread to modify the global variable 'latest_video_frame': (this variable will be accessed by functions doing some sort of video analysis or video streaming)
    global latest_video_frame   

    # create an instance of the RPI camera class:
    camera = PiCamera() 

    # rotate the camera view 180 deg (I have the RPI camera mounted upside down):
    camera.hflip = True
    camera.vflip = True 

    # set resolution and frame rate:
    camera.resolution = (640, 480)
    camera.framerate = 30

    # create a generator 'video_frame_generator' which will continuously capture video frames 
    # from the camera and save them one by one in the container 'generator_output': ('video_frame_generator' is an infinte iterator which on every iteration (every time 'next()' is called on it, like eg in a for loop) gets a video frame from the camera and saves it in 'generator_output'))  
    generator_output = PiRGBArray(camera, size=(640, 480))
    video_frame_generator = camera.capture_continuous(generator_output, format="bgr", use_video_port=True)

    # allow the camera to warm up:
    time.sleep(0.1)

    for item in video_frame_generator:
        # get the numpy array representing the latest captured video frame from the camera
        # and save it globally for everyone to access:
        latest_video_frame = generator_output.array 

        # clear the output container so it can store the next frame in the next loop cycle:
        # (please note that this is absolutely necessary!)
        generator_output.truncate(0)        

        # delay for 0.033 sec (for ~ 30 Hz loop frequency):
        time.sleep(0.033) 

# stop the robot if the wifi connection is lost: (by telling the arduino to do so over serial)
项目:rascal-tensorflow    作者:stayrascal    | 项目源码 | 文件源码
def __init__(self, resolution=(160, 120), framerate=12):
        from picamera.array import PiRGBArray
        from picamera import PiCamera

        # initizlize 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.stopped = False

        print('PiVideoStream loaded.. .warming camera')

        time.sleep(2)
        self.start()
项目:spassouno-py    作者:OfficineArduinoTorino    | 项目源码 | 文件源码
def __init__(self,resolution,display):
        pygame.camera.init()
        self.resolution=resolution

        camlist = pygame.camera.list_cameras()
        if not camlist:
            import picamera
            self.is_picamera=True
            self.camera=picamera.PiCamera()
            self.camera.rotation = 270
            self.camera.exposure_compensation=10
            self.camera.exposure_mode="auto"
            self.resolution=(1920,1080)
            time.sleep(2)
            self.camera.exposure_mode="off"
        else:
            self.camera = pygame.camera.Camera(camlist[0],self.resolution)
            self.camera.start()
            self.is_picamera=False


        self.frame=pygame.surface.Surface(self.resolution, 0, display)
项目:Robo-Plot    作者:JackBuck    | 项目源码 | 文件源码
def take_photo_at(self, camera_centre):
        with picamera.PiCamera() as camera:
            camera.resolution = config.CAMERA_RESOLUTION
            camera.framerate = 24
            with picamera.array.PiRGBArray(camera) as output:
                camera.capture(output, 'bgr', use_video_port=True)
                outputarray = output.array

            # Rotate image to oriented it with paper.
            outputarray = np.rot90(outputarray, 3)

            # Save photo.
            filename = datetime.datetime.now().strftime("%M%S.%f_") + \
                       str(camera_centre[0]) \
                       + '_' \
                       + str(camera_centre[1]) + '_Photo_' + str(self._photo_index) + '.jpg'

            cv2.imwrite(os.path.join(config.debug_output_folder, filename), outputarray)
            self._photo_index += 1

            return outputarray
项目:2016-Vision    作者:Team4761    | 项目源码 | 文件源码
def capture_images():
    global count
    global frame
    global camera_resolution
    with picamera.PiCamera() as camera:
        camera_resolution = camera.resolution
        camera.shutter_speed = 100
        time.sleep(0.5) #Shutter speed is not set instantly. This wait allows time for changes to take effect.
        log.info("Initialized camera")
        max_frames = args.max_frames
        with picamera.array.PiRGBArray(camera) as stream:
            for index, foo in enumerate(camera.capture_continuous(stream, format="bgr", use_video_port=True)):
                if stopped is True:
                    return
                count = index
                log.info("Captured image. Starting to process...")
                stream.seek(0)
                stream.truncate()
                frame = stream.array
                log.debug("Converted data to array")
项目:remho    作者:teamresistance    | 项目源码 | 文件源码
def picamera():
    # Picamera will raise an OSError when importing unless the code is run
    # on an RPI due to firmware dependencies. Make the imports local so we
    # won't have to deal with this nuance when not calling this method.
    import picamera
    import picamera.array

    with picamera.PiCamera() as camera:
        camera.resolution = (640, 480)
        time.sleep(0.1)  # allow the camera time to warm up

        with picamera.array.PiRGBArray(camera, size=(640, 480)) as stream:
            if camera.closed:
                raise CameraInitializationError('Camera failed to open.')

            for frame in camera.capture_continuous(stream, format='bgr', use_video_port=True):
                image = frame.array
                yield image

                # Clear the stream in preparation for the next frame
                stream.truncate(0)


# TODO documentation
项目:hotspot-game    作者:pageauc    | 项目源码 | 文件源码
def __init__(self, resolution=(CAMERA_WIDTH, CAMERA_HEIGHT), framerate=CAMERA_FRAMERATE, rotation=0, hflip=False, vflip=False):
        # initialize the camera and stream
        self.camera = PiCamera()
        self.camera.resolution = resolution
        self.camera.rotation = rotation
        self.camera.framerate = framerate
        self.camera.hflip = hflip
        self.camera.vflip = vflip
        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
项目:sonic-track    作者:pageauc    | 项目源码 | 文件源码
def __init__(self, resolution=(CAMERA_WIDTH, CAMERA_HEIGHT), framerate=CAMERA_FRAMERATE, rotation=0, hflip=False, vflip=False):
        # initialize the camera and stream
        self.camera = PiCamera()
        self.camera.resolution = resolution
        self.camera.rotation = rotation
        self.camera.framerate = framerate
        self.camera.hflip = hflip
        self.camera.vflip = vflip
        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
项目:smart-monitor-system    作者:MostafaBalata    | 项目源码 | 文件源码
def update3(self):
        # keep looping infinitely until the thread is stopped
        stream = io.BytesIO()
        with picamera.PiCamera() as camera:

            for f in camera.capture_continuous(stream, format='jpeg'):  # self.stream:
                # grab the frame from the stream and clear the stream in
                # preparation for the next frame
                self.frame = f.array
                self.rawCapture.truncate(0)

                # if the thread indicator variable is set, stop the thread
                # and resource camera resources
                if self.stopped:
                    self.stream.close()
                    self.rawCapture.close()
                    self.camera.close()
                    return
项目:DeltaPicker    作者:T-Kuhn    | 项目源码 | 文件源码
def __init__(self):
        """Constructor"""
        self.folderCount = 0;
        self.cam = picamera.PiCamera()
        self.imageProUpperLevel = ImPro(self.cam, 256, 256)
        self.imageProUpperLevel.camera._set_led(False)

        self.imageProLowerLevel = ImPro(self.cam, 256, 256, True, 96, 96)

        # This serial port is used to send 3D coordinates to the Arduino. 
        self.port = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=3.0)

        # This offset marks the pixelposition on the image which corresponds to the physical position when the
        # DeltaPicker move down to 0.0, 0.0, -0.466. Only x and y components are used.
        self.upperLevelOffset = Vector(0, 0, 0)
        # This offset is the low level offset. It gets taken at a hight of -0.41        
        self.lowerLevelOffset = Vector(0, 0, 0)

        # Crop Offset
        self.cropOffset = Vector(80, 0, 0)


    # - - - - - - - - - - - - - - - - 
    # - - - - GO TO STARTPOS  - - - -
    # - - - - - - - - - - - - - - - -
项目:raspi-photo-booth    作者:kriskbx    | 项目源码 | 文件源码
def takePhoto():
    image = ImagePath + str(time.time()) + '.jpg'
    print image
    Camera = picamera.PiCamera()
    Camera.resolution = (3280, 2464)
    Camera.capture(image)
    Camera.close() 
    return image
项目:StratoBalloon    作者:delattreb    | 项目源码 | 文件源码
def is_plugged(function):
    def plugged(*original_args, **original_kwargs):
        return function(*original_args, **original_kwargs)

    if not PiCamera:
        logger = com_logger.Logger('CAMERA')
        logger.warning('Camera not plugged')

    return plugged
项目:StratoBalloon    作者:delattreb    | 项目源码 | 文件源码
def __init__(self, mode, cameranumber):
        if PiCamera is not None:
            self.imgName = 'PIC_'
            self.vidName = 'VID_'
            self.cameranumber = cameranumber

            conf = com_config.Config()
            config = conf.getconfig()
            logger = com_logger.Logger(self.cameranumber)

            self.camera = PiCamera()
            if mode == 'PICTURE':
                self.camera.resolution = (int(config[self.cameranumber]['pic_resolution_x']), int(config[self.cameranumber]['pic_resolution_y']))
                logger.info('Camera mode PICTURE: ' + config[self.cameranumber]['pic_resolution_x'] + ' ' + config[self.cameranumber]['pic_resolution_y'])
            if mode == 'VIDEO':
                self.camera.resolution = (int(config[self.cameranumber]['vid_resolution_x']), int(config[self.cameranumber]['vid_resolution_y']))
                logger.debug('Camera mode VIDEO: ' + config[self.cameranumber]['vid_resolution_x'] + ' ' + config[self.cameranumber]['vid_resolution_y'])
                self.camera.framerate = int(config[self.cameranumber]['framerate'])

            self.camera.rotation = int(config[self.cameranumber]['rotation'])
            # self.camera.brightness = int(config[self.cameranumber]['brightness'])
            # self.camera.contrast = int(config[self.cameranumber]['contrast'])
            if len(config[self.cameranumber]['image_effect']) > 0:
                self.camera.image_effect = config[self.cameranumber]['image_effect']
            self.camera.exposure_mode = config[self.cameranumber]['exposure_mode']
            self.camera.meter_mode = config[self.cameranumber]['meter_mode']
            self.camera.awb_mode = config[self.cameranumber]['awb']
            if len(config[self.cameranumber]['raw']) > 0:
                self.camera.raw_format = config[self.cameranumber]['raw']
            self.path = config[self.cameranumber]['picture_path']
            self.camera.iso = int(config[self.cameranumber]['ISO'])
            self.quality = int(config[self.cameranumber]['jpegquality'])
            self.format = config[self.cameranumber]['format']
项目:STS-PiLot    作者:mark-orion    | 项目源码 | 文件源码
def init_camera():
    try:
        camera = picamera.PiCamera()
        # camera setup
        camera.resolution = (cfg.width, cfg.height)
        camera.hflip = cfg.pi_hflip
        camera.vflip = cfg.pi_vflip

        # let camera warm up
        camera.start_preview()
        time.sleep(2)
        return True, camera
    except:
        return False, False
项目:PiWifiCam    作者:mark-orion    | 项目源码 | 文件源码
def init_camera():
    try:
        camera = picamera.PiCamera()
        # camera setup
        camera.resolution = (cfg.width, cfg.height)
        camera.hflip = cfg.pi_hflip
        camera.vflip = cfg.pi_vflip

        # let camera warm up
        camera.start_preview()
        time.sleep(2)
        return True, camera
    except:
        return False, False
项目:iot-demo-mxnet-greengrass    作者:aquaviter    | 项目源码 | 文件源码
def predict_from_cam(self, capfile='cap.jpg', reshape=(224, 224), N=5):
        if self.camera is None:
            self.camera = picamera.PiCamera()

        # Show quick preview of what's being captured
        self.camera.start_preview()
        time.sleep(3)
        self.camera.capture(capfile)
        self.camera.stop_preview()

        return self.predict_from_file(capfile)
项目:photobooth    作者:LoiX07    | 项目源码 | 文件源码
def __init__(self, **kwargs):
        """ Initialization of the camera """
        self.camera = PiCamera()
        version = kwargs.get('version', 0)
        # Configuration
        if version == 1:
            self.camera.resolution = (1024, 768)
        elif version == 2:
            self.camera.resolution = (3280, 2464)
        else:
            raise ValueError('Unsupported raspberry pi camera version')
        # Camera warm-up
        self.camera.start_preview()
        sleep(2)
项目:tensorflow-pi    作者:karaage0703    | 项目源码 | 文件源码
def shutter():
    photofile = open(photo_filename, 'wb')
    print(photofile)

    with picamera.PiCamera() as camera:
        camera.resolution = (640,480)
        camera.start_preview()
        sleep(1.000)
        camera.capture(photofile)
项目:tensorflow-pi    作者:karaage0703    | 项目源码 | 文件源码
def shutter():
    photofile = open(face_filename, 'wb')
    print(photofile)

    with picamera.PiCamera() as camera:
        camera.resolution = (640,480)
        camera.start_preview()
        sleep(1.000)
        camera.capture(photofile)
项目:hdr-timelapse    作者:alexellis    | 项目源码 | 文件源码
def __init__(self, config, path_maker):
        self.camera = PiCamera()
        self.camera.resolution = (int(config["width"]), int(config["height"]))
        self.camera.meter_mode = "backlit"
        self.config = config
        self.path_maker = path_maker
项目:Flashlapse_NEO    作者:flashlapsedev    | 项目源码 | 文件源码
def run(self):
        with PiCamera() as camera:
            camera.resolution = (2464,2464)
            camera._set_rotation(180)
            camera.capture("../_temp/snapshot.jpg")
项目:Flashlapse_NEO    作者:flashlapsedev    | 项目源码 | 文件源码
def run(self):
        with PiCamera() as camera:
            camera._set_rotation(180)
            camera.start_preview()
            sleep(30)
项目:CoffeeRobot    作者:ciauri    | 项目源码 | 文件源码
def detect():
    stream = io.BytesIO()

        #Get the picture (low resolution, so it should be quite fast)
        #Here you can also specify other parameters (e.g.:rotate the image)
    with picamera.PiCamera() as camera:
        camera.resolution = (700, 525)
        camera.capture(stream, format='jpeg')

    buff = np.fromstring(stream.getvalue(), dtype=np.uint8)

    #Now creates an OpenCV image
    img = cv2.imdecode(buff, 1)


    #img = cv2.imread('coffee.jpg')
    face_cascade = cv2.CascadeClassifier('/home/pi/Documents/OpenCV_Projects/XML_Files/coffeePot.xml')
    eye_cascade = cv2.CascadeClassifier('/home/pi/Documents/OpenCV_Projects/XML_Files/liquid.xml')

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.2, 500, minSize=(80,100))
    for (x,y,w,h) in faces:
        img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
        eyes = eye_cascade.detectMultiScale(roi_gray, 1.2, 10, minSize=(70,50))
        return houghlines(roi_color,h)
项目:CoffeeRobot    作者:ciauri    | 项目源码 | 文件源码
def detect():
    stream = io.BytesIO()

        #Get the picture (low resolution, so it should be quite fast)
        #Here you can also specify other parameters (e.g.:rotate the image)
    with picamera.PiCamera() as camera:
        camera.resolution = (700, 525)
        camera.capture(stream, format='jpeg')

    buff = np.fromstring(stream.getvalue(), dtype=np.uint8)

    #Now creates an OpenCV image
    img = cv2.imdecode(buff, 1)


    #img = cv2.imread('coffee.jpg')
    face_cascade = cv2.CascadeClassifier('/home/pi/Documents/OpenCV_Projects/XML_Files/coffeePot.xml')
    eye_cascade = cv2.CascadeClassifier('/home/pi/Documents/OpenCV_Projects/XML_Files/liquid.xml')

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.2, 500, minSize=(80,100))
    for (x,y,w,h) in faces:
        img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
        eyes = eye_cascade.detectMultiScale(roi_gray, 1.2, 10, minSize=(70,50))
        return houghlines(roi_color,x,y,w,h)
项目:snapshot-twitter    作者:helioloureiro    | 项目源码 | 文件源码
def GetPhoto(f = None, quality = None):
    """
    Photo aquisition
    """
    global filename, FAILCOUNTER, error_tries

    debug("GetPhoto: failcounter=%d" % FAILCOUNTER)
    if FAILCOUNTER < 0:
        print "Fail counter reached maximum attempts.  Failed."
        debug("Trying to return a failed img.")
        filename = getfailedimg()
        if not filename:
            sys.exit(1)
        debug("Using failed img: %s" % filename)
        # it needs to be 0ed or it will fail
        FAILCOUNTER = 0
        return 0
    filename = None
    debug("Camera init")
    camera = PiCamera()
    debug("Camera start")
    camera.start_preview()
    time.sleep(10)
    #if not os.path.exists(SAVEDIR):
    #    os.makedirs(SAVEDIR)
    year = time.strftime("%Y", time.localtime())
    month = time.strftime("%m", time.localtime())
    if not os.path.exists("%s/%s/%s" % (SAVEDIR, year, month)):
        os.makedirs("%s/%s/%s" % (SAVEDIR, year, month) )
    if not f:
        timestamp = time.strftime("%Y-%m-%d_%H%M%S", time.localtime())
        filename = "%s/%s/%s/%s.jpg" % (SAVEDIR, year, month, timestamp)
    else:
        filename = f
    debug("Saving file %s" % filename)
    camera.capture(filename)
    camera.stop_preview()
项目:NixieBot    作者:Zedsquared    | 项目源码 | 文件源码
def testIt():
    initGPIO()
    lightTubes()
    initTubes()
    scrollList("The quick brown fox jumped over the lazy red hypercaterpillar".split())
    print("************** running quick test ")
    with picamera.PiCamera() as cam:
        initcam(cam)
        time.sleep(1.5)
        cam.capture('tweet.jpg',resize=(800,480))
    cam.close()
    time.sleep(10)
    return()
项目:continuous-online-video-classification-blog    作者:harvitronix    | 项目源码 | 文件源码
def capture_images(save_folder):
    """Stream images off the camera and save them."""
    camera = PiCamera()
    camera.resolution = (320, 240)
    camera.framerate = 5

    # Warmup...
    time.sleep(2)

    # And capture continuously forever.
    for _ in camera.capture_continuous(
            save_folder + '{timestamp}.jpg',
            'jpeg', use_video_port=True
    ):
        pass
项目:photobooth    作者:maduck    | 项目源码 | 文件源码
def __init__(self, config):
        self.config = config
        self.camera = picamera.PiCamera()
        self.camera.annotate_text_size = 128
        self.camera.led = False
        self.camera.vflip = True
        self.camera.resolution = (
            self.config.getint("picture_width"),
            self.config.getint("picture_height")
        )