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 = ''
python类PiCamera()的实例源码
image_processor.py 文件源码
项目:aws-greengrass-mini-fulfillment
作者: awslabs
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
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)
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)
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
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()
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()
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
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)
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)
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)
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)
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()
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
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
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()
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
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
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
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
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()
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)
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()
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)
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()
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)
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
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")
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
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
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