def RunCamera(argv, killer): vid_len = 60 with picamera.PiCamera() as camera: camera.resolution = (1360, 768) camera.framerate = 24 camera.brightness = 60 camera.contrast = 20 camera.sharpness = 20 camera.iso = 0 camera.annotate_foreground = picamera.Color('black') camera.annotate_background = picamera.Color('white') camera.annotate_text = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S') camera.annotate_text_size = 22 zero = dt.datetime.now() while True: start = dt.datetime.now() file_name = start.strftime( '/home/pi/videos/frontcam/%Y%m%d-%H%M%S.h264') print 'Record: ' + file_name camera.start_recording(file_name, bitrate=4500000) now = dt.datetime.now() while (now - start).seconds <= vid_len: camera.annotate_text = dt.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') camera.wait_recording(1) now = dt.datetime.now() if killer.kill_now: camera.stop_recording() break camera.stop_recording()
def isreal(id): if id=="3203319541": return True #while True: start1=time.time(); camera.capture_sequence(['/home/pi/'+id+'.jpg'],use_video_port=True) end1=time.time(); print("time1:",end1-start1) try: start2=time.time(); re=str(totf.sock_client(r'/home/pi/'+id+'.jpg')) print(re) end2=time.time(); print("time2:",end2-start2) except: return True if re=="1": camera.annotate_background=picamera.Color('green') camera.annotate_text="SUCCEED" print("11111") return True else: camera.annotate_background=picamera.Color('red') camera.annotate_text="FAILED" print("00000") return False
def judgment(id): start0=time.time(); f = open("data.txt",'r') lines = f.readlines() for line in lines: if line.startswith(id): if isreal(id): GPIO.output(relay,GPIO.HIGH) end0=time.time(); print("time0:",end0-start0) print ("OPEN!") time.sleep(2) GPIO.output(relay,GPIO.LOW) f.close() camera.annotate_text="" return True else: camera.annotate_background=picamera.Color('red') camera.annotate_text="FAILED" time.sleep(1) camera.annotate_text="" print ("failed") f.close() return False camera.annotate_text_size=100 camera.annotate_background=picamera.Color('red') camera.annotate_text="ID UNDEFIND" time.sleep(1) camera.annotate_text="" camera.annotate_text_size=160 print ("ID undefined!") f.close() return False
def takeVideo(filename): # Take a short motion video if required logging.info("Size %ix%i for %i sec %s" % (imageWidth, imageHeight, motionVideoTimer, filename)) if motionVideoOn: with picamera.PiCamera() as camera: camera.resolution = (imageWidth, imageHeight) camera.vflip = imageVFlip camera.hflip = imageHFlip camera.rotation = imageRotation #Note use imageVFlip and imageHFlip variables if showDateOnImage: rightNow = datetime.datetime.now() dateTimeText = " Started at %04d-%02d-%02d %02d:%02d:%02d " % (rightNow.year, rightNow.month, rightNow.day, rightNow.hour, rightNow.minute, rightNow.second) camera.annotate_text_size = showTextFontSize camera.annotate_foreground = picamera.Color('black') camera.annotate_background = picamera.Color('white') camera.annotate_text = dateTimeText camera.start_recording(filename) camera.wait_recording(motionVideoTimer) camera.stop_recording() # This creates a subprocess that runs convid.sh with the filename as a parameter try: convid = "%s/convid.sh %s" % ( baseDir, filename ) proc = subprocess.Popen(convid, shell=True, stdin=None, stdout=None, stderr=None, close_fds=True) except IOError: print("subprocess %s failed" %s ( convid )) else: print("unidentified error") createSyncLockFile(filename) return
def __init__(self): camera.resolution = (768, 768) #写真サイズ camera.vflip = True #映像を上下逆に camera.hflip = True #映像を左右逆に camera.brightness = 60 #明るさを60に camera.annotate_foreground = picamera.Color("white") camera.annotate_background = picamera.Color("black")
def ChooseBackcolorClick ( self ): # pass a String for the color - not a Value! result = askcolor(parent=self,color=str(self.BackColor), title='Annotation Background color') # [0] is (R,G,B) tuple, [1] is hex value of color if result[0] == None: return # Cancel self.BackColor = picamera.Color(result[1]) self.camera.annotate_background = picamera.Color(result[1])
def AnnotationForegroundColor ( self, AddColor ): if AddColor: self.camera.annotate_foreground = \ picamera.Color(y=float(self.Ycolor.get()), u=0, v=0) self.Ycolor.state(['!disabled']) self.Ycolor.focus_set() else: self.Ycolor.state(['disabled']) self.camera.annotate_foreground = picamera.Color('white')
def start_camera(): camera = picamera.PiCamera() camera.resolution = (1920, 1080) camera.framerate = 25 camera.video_stabilization = True camera.annotate_foreground = picamera.Color('black') camera.annotate_text_size = 18 camera.annotate_background = picamera.Color('white') return camera
def add_time_toggle(self, state_active): if state_active: self.cam.annotate_background = picamera.Color('black') self.cam.annotate_foreground = picamera.Color('white') self.cam.annotate_text = 'Elapsed Time' else: self.cam.annotate_background = None self.cam.annotate_foreground = picamera.Color('white') self.cam.annotate_text = ''
def takephoto(): camera.annotate_foreground = picamera.Color('black') camera.annotate_background = picamera.Color('white') camera.annotate_text = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') filename = BASEDIR + "images/" + datetime.datetime.now().strftime( '%Y-%m-%d_%H%M%S') + ".jpg" time.sleep(0.3) camera.capture(filename) mailphoto(MAILFROMADDRESS, MAILFROMPASS, MAILTOADDRESS, filename)
def updateOverlays(self, currentTime): self.picam.annotate_background = picamera.Color("black") self.picam.annotate_foreground = picamera.Color("white") self.picam.annotate_text_size = 15 # determine what to display depending on the second (it's the # current date/time by default) annotation = currentTime.strftime("%Y-%m-%d, %H:%M:%S") # update the overlay text self.picam.annotate_text = str(annotation)
def TakePhoto(): camera = picamera.PiCamera() filename = datetime.today() #print(filename) camera.annotate_background = picamera.Color("teal") camera.annotate_foreground = picamera.Color("lightpink") camera.annotate_text = datetime.now().strftime('%Y-%m-%d %H:%M:%S') camera.annotate_text_size = 55 #camera.resolution(100,100) camera.capture('/home/pi/Pictures/Test/Photo1.jpg', resize=(200, 200)) camera.close()
def __init__(self, camera, roomba): super(StreamingHttpServer, self).__init__( ('', HTTP_PORT), StreamingHttpHandlerFactory(camera,roomba)) with io.open('index.html', 'r') as f: self.index_template = f.read() with io.open('jsmpg.js', 'r') as f: self.jsmpg_content = f.read() camera.annotate_foreground = picamera.Color('black') camera.annotate_background = picamera.Color('white') camera.annotate_text_size = 32 camera.annotate_text = "Welcome to Roomba Cam"
def run(self): self.load_configuration() self.camera.framerate_range = (0.0333, 30) self.camera.annotate_foreground = picamera.Color(r=255, g=255, b=255) raw_capture = picamera.array.PiRGBArray(self.camera, size=self.camera.resolution) while (True): start_time = time.time() self.camera.annotate_text = str(datetime.datetime.now()) print('exposure_speed = %d shutter_speed = %d' % (self.camera.exposure_speed, self.camera.shutter_speed)) self.camera.capture(raw_capture, format='rgb', use_video_port=False) image = raw_capture.array self.timelapse_callback(image) raw_capture.truncate(0) end_time = time.time() sleep_time = max(self.timelapse_period - (end_time - start_time), 0) print('sleep_time = %d' % (sleep_time)) time.sleep(sleep_time)
def Timestamp(): if (dt.datetime.now().strftime('%S') != sec.var): # accesses the second value from the last time sec() was called # updates the annotation on the video if a second has passed camera.annotate_text_size = fontSize camera.annotate_background = picamera.Color('black') camera.annotate_text = CurrentTime() sec() # calls the second function so that it can update its current second value
def thread_function(): ds = DataStore.getInstance() tos = TwitchBufferedOutputStream( twitch_stream_key=os.environ['TWITCH_SECRET'], width=1280, height=720, fps=30, verbose=True) camera = picamera.PiCamera(1280, 720, framerate=24) camera.start_preview() camera.annotate_background = picamera.Color('black') camera.annotate_text = "Current orientation: " + ds.getOrientation() sleep(2) now = datetime.now() # Begine recording the video camera.start_recording('launches/launch-' + now.strftime("%m-%d-%H-%M-%S") + '.h264') while True: # Get current frame camera.annotate_text = "Current orientation: " + ds.getOrientation( ) frame = camera.frame tos.send_video_frame(frame) time.sleep(1 / 30)
def main(args): signal.signal(signal.SIGINT, signal_handler) #allow Ctr+C to end program with saving name_seed = "TEST" if args.output is not None: name_seed = args.output[0] print("Name seed is {}".format(name_seed)) fps = int(args.fps[0]) qual = int(args.quality[0]) width = 1280 height = 720 hostname = socket.gethostname() camera = picamera.PiCamera(resolution=(width, height), framerate=fps) # camera.start_preview() camera.annotate_background = picamera.Color('black') camera.annotate_text = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S') current_date = datetime.now() current_date_str = current_date.strftime("-%d%b-%Y-%H%M%S") camera.start_preview() # for debugging outputpipe = MePipe(name_seed + '_' + hostname + '_' + current_date_str + '_stream_' + str(fps) + 'fps_' + str(qual) + 'qual') camera.start_recording(outputpipe, quality=qual, format='h264') while brexit == 0: current_date = datetime.now() current_date_str = current_date.strftime("%d-%b-%Y %H:%M:%S") camera.annotate_text = name_seed + ' ||' + current_date_str camera.wait_recording(0.2) camera.stop_recording()
def run(self): #self.camera.start_preview(fullscreen=False,window=(100,100,400,600)) while True: #cameraTime = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') self.camera.annotate_background = picamera.Color('black') self.camera.annotate_text = dt.datetime.now().strftime( '%Y-%m-%d %H:%M:%S.%f')
def cam_thread(ev, q): global date_now global recording_start # initialize camera sys.stdout.flush() print('Cam: Camera read to start recording') with picamera.PiCamera() as camera: timestamp = 0 camera.resolution = (1920, 1080) camera.framerate = 20 camera.annotate_background = picamera.Color('black') camera.start_recording('cam_stream_' + date_now + '.h264') while not ev.is_set(): if timestamp != camera.frame.timestamp: tmp = time.time() camera.annotate_text = str(tmp - recording_start) timestamp = camera.frame.timestamp q.put((tmp, timestamp)) q.put((time.time(), camera.frame.timestamp)) print('Cam: finished reading') camera.close()
def _pi_init(): global _has_picamera_module if _has_picamera_module and P.is_pi_camera_detected: try: L.l.info("Starting PI Recording") _kill_proc(P.pi_out_filename) P.pi_camera = picamera.PiCamera() P.pi_camera.resolution = P.pi_max_resolution P.pi_camera.framerate = P.pi_framerate P.pi_camera.rotation = P.pi_rotation_degree P.pi_camera.annotate_background = picamera.Color('black') _run_ffmpeg_pi() P.pi_camera.start_recording(P.ffmpeg_pi.stdin, format='h264', bitrate=P.pi_bitrate) if P.ffmpeg_pi._child_created: L.l.info("Recording PI started") P.is_recording_pi = True P.is_pi_camera_detected = True except Exception as ex: if 'Camera is not enabled' in str(ex): _has_picamera_module = False P.is_pi_camera_detected = False #P.is_recording_on = False L.l.error( "PI camera not found, disabling the camera, no recording from now" ) L.l.info("Unable to initialise picamera, ex={}".format(ex))
def takeStillCommand(threadid): if checkService(): print('Still not possible - service running') postMessage(':no_entry: Still not possible - service running', threadid) return else: postMessage(':white_check_mark: Taking still', threadid) output_basefilename = "{}".format(datetime.now().strftime('%Y%m%d-%H%M%S')) recordStill = settings.rootPath + 'videos/' + output_basefilename + '.jpg' with picamera.PiCamera() as cam: cam.rotation = settings.camRotation cam.resolution = settings.camStillResolution cam.annotate_background = picamera.Color('black') # cam.shutter_speed = 10000 cam.start_preview() time.sleep(2) cam.capture(recordStill, use_video_port=False) cam.stop_preview() postSlackStill(recordStill, output_basefilename + '.jpg', output_basefilename + '.jpg', 'Still - ' + output_basefilename + '.jpg', threadid) os.remove(recordStill) return
def take_pictures(camera, jpg_group): print("Taking pics") camera.annotate_text_size = 160 camera.annotate_foreground = picamera.Color('black') for i in range(1, TOTAL_PICS + 1): camera.hflip = True # preview a mirror image camera.start_preview() for n in range(CAPTURE_DELAY, 0, -1): surface = pygame.Surface(SCREEN.get_size(), pygame.SRCALPHA) font = pygame.freetype.SysFont('DejaVu Sans', 360) rect = font.get_rect(str(n)) pos = (surface.get_width() - rect.width) // 2, (surface.get_height() - rect.height) // 2 font.render_to(surface, pos, None, (0, 0, 0)) overlay = camera.add_overlay(pygame.image.tostring(surface, 'RGBA'), surface.get_size(), layer=3, format='rgba') time.sleep(0.5) camera.remove_overlay(overlay) time.sleep(0.5) # Make the screen white SCREEN.fill((255, 255, 255)) pygame.display.flip() camera.stop_preview() time.sleep(0.25) filename = config.file_path + jpg_group + '-0' + str(i) + '.jpg' camera.hflip = False # flip back when taking photo print('Saving: ' + filename) if config.hi_res_pics: camera.capture(filename) else: camera_w, camera_h = camera.resolution pixel_width = 500 # maximum width of animated gif on tumblr pixel_height = camera_h * pixel_width // camera_w camera.capture(filename, resize=(pixel_width, pixel_height))
def _thread(cls): with picamera.PiCamera(framerate=24) as camera: # camera setup # camera.resolution = (640, 480) # camera.resolution = (735*3, 812*3) camera.resolution = (735, 812) # camera.image_effect = 'colorbalance' # camera.image_effect = 'cartoon' # camera.awb_mode = 'auto' camera.annotate_background = picamera.Color('black') camera.annotate_text = dt.datetime.now().strftime('%Y-%m-%d') camera.hflip = False camera.vflip = False # let camera warm up camera.start_preview() # time.sleep(2) stream = io.BytesIO() for foo in camera.capture_continuous(stream, 'jpeg', use_video_port=True): # store frame stream.seek(0) cls.frame = stream.read() # reset stream for next frame stream.seek(0) stream.truncate() # if there hasn't been any clients asking for frames in # the last 10 seconds stop the thread if time.time() - cls.last_access > 10: break cls.thread = None
def __init__(self, width=1280, height=720, framerate=30): threading.Thread.__init__(self) # The shutdown_flag is a threading.Event object that # indicates whether the thread should be terminated. self.shutdown_flag = threading.Event() #Defining Camera and settings self.camera = picamera.PiCamera() self.camera.resolution = (width, height) self.framerate = framerate self.camera.framerate = framerate self.camera.clock_mode = 'raw' self.csvsheet = None self.output = None self.frame_index = 0 self.prev_frame_index = 0 self.folderName = "" #Defining a lock for picture saving self.picture_lock = threading.Lock() self.actual_GPS_time = {} #StartingCamera self.camera.start_preview() #Init background marking self.camera.annotate_background = picamera.Color('black') self.camera.annotate_text_size = 16 self.wait_time = 1 / framerate time.sleep(12.) print("Start recording frame")
def read_pic(): while True: stream = io.BytesIO() tc0 = time.time() # Read pressure information read_keller_LD(sensor, rx, ctypes.byref(p), ctypes.byref(T), ctypes.byref(stime)) tstr = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-5] tstr_file = datetime.datetime.utcnow().strftime( '%Y%m%d_%H%M%S.%f')[:-5] data_str = tstr + ' p: {:3.3f}'.format(p.value) + ' T: {:3.1f}'.format( T.value) #print(float(p),p,T) print(data_str) camera.exif_tags['EXIF.UserComment'] = data_str.encode() camera.annotate_background = picamera.Color('black') camera.annotate_text = data_str camera.capture(stream, format='jpeg', quality=quality) tc1 = time.time() size_image = stream.seek(0, 2) #print('Resolution',resolution,'quality',quality,'Image size',size_image) # "Rewind" the stream to the beginning so we can read its content stream.seek(0) data = stream.read(size_image) data_ret = {} data_ret['data'] = data data_ret['tc0'] = tc0 data_ret['tc1'] = tc1 data_ret['p'] = p data_ret['T'] = T data_ret['tstr_file'] = tstr_file data_ret['data_str'] = data_str picqueue.append(data_ret)
def start(cls): """Start a recording.""" cls.ensure_space(cls.VIDEOS_DIRECTORY) cls.recording = True now = datetime.datetime.now() # Compute how many seconds left in the minute cls.duration = 60 - now.second if cls.duration == 0: cls.duration = 60 # Add time for minutes left in the hour cls.duration += (59 - now.minute) * 60 print('Will record for', cls.duration, 'seconds.') fn = now.strftime('%Y-%m-%d_%p_%I:%M:%S.h264') fullPathFilename = cls.VIDEOS_DIRECTORY + fn print('File name: ', fn) print('Full path filename: ', fullPathFilename) cls.camera.start_preview() cls.camera.annotate_background = picamera.Color('black') cls.camera.annotate_text = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') cls.camera.start_recording(fullPathFilename) cls.annotation_timer = Timer(cls.ANNOTATION_TIMER_INTERVAL_SEC, cls.update_time_annotation) cls.annotation_timer.start() print('Starting recording') rainbowhat.display.print_str(cls.RECORDING) rainbowhat.display.show()
def startCamera(self): global camera with picamera.PiCamera(resolution='160x120', framerate=150) as camera: global output output = masterStream.StreamingOutput() #Uncomment the next line to change your Pi's Camera rotation (in degrees) #camera.rotation = 90 camera.clock_mode = 'raw' camera.start_recording(output, format='mjpeg') camera.annotate_background = picamera.Color('black') camera.annotate_text_size = 14 camera.annotate_text = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S') #Setting up the low level interrupts with optional LED vis GPIO.add_event_detect(on_pin,GPIO.RISING,callback=masterStream.interrupt_on) try: global address address = ('', 8000) server = masterStream.StreamingServer(address, masterStream.StreamingHandler) server.serve_forever() except KeyboardInterrupt: print('Keyboard interrupt ended stream at address',address) camera.close() server.server_close() GPIO.cleanup() pass finally: camera.close() server.server_close() GPIO.cleanup()
def do_GET(self): if self.path == '/stream.mjpg': self._on_join() self._set_mjpeg_headers() camera.annotate_background = picamera.Color('black') camera.annotate_text_size = 16 try: while True: with output.condition: output.condition.wait() frame = output.frame camera.annotate_text = dt.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') self.wfile.write(b'--FRAME\r\n') self.send_header('Content-Type', 'image/jpeg') self.send_header('Content-Length', len(frame)) self.end_headers() self.wfile.write(frame) self.wfile.write(b'\r\n') except Exception as e: logging.warning('Removed streaming client %s: %s', self.client_address, str(e)) finally: self._on_leave() else: self.send_error(404) self.end_headers()
def start_capture_video(self): self._cam = picamera.PiCamera() self._cam.resolution = (1920,1024) self._cam.annotate_background = picamera.Color('black') self._cam.start_recording('/home/pi/video.h264') self.capture_end_at = time.mktime(datetime.now().utctimetuple()) + BaseState.capture_duration self._capturing_video = True
def capture_photo(): GPIO.output(7, 1) try: with picamera.PiCamera(sensor_mode=3) as camera: camera.resolution = (3280, 2464) camera.hflip = True camera.vflip = True camera.annotate_background = picamera.Color('black') now = datetime.datetime.now() camera.annotate_text = now.strftime("%Y-%m-%d %H:%M:%S") camera.annotate_text_size = 100 time.sleep(2) # warmup for camera stream = io.BytesIO() camera.capture(stream, format='jpeg', use_video_port=True) stream.seek(0) except: return 'Error: camera is unavailable!', 503 GPIO.output(7, 0) filename = now.strftime("%Y_%m_%d_%H_%M_%S") r = Response(stream.read(), mimetype='image/jpeg') r.headers[ 'Content-Disposition'] = 'inline; filename=qba_' + filename + '.jpeg' r.headers['Cache-control'] = 'no-cache' return r