def get_current_image_fast( camera ): if picamera_available == True: camera.capture('/tmp/photobooth_curcam.jpg', format='jpeg', resize=(WIDTH,HEIGHT)) return pygame.image.load('/tmp/photobooth_curcam.jpg') else: return camera.get_image() return
def main(): # 1. Take picture camera = picamera.PiCamera() camera.start_preview() sleep(5) camera.capture('/home/pi/Desktop/image.jpg') camera.stop_preview() # 2. Display saved picture using pygame. pygame.init() fpsClock = pygame.time.Clock() surface = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) black = (0, 0, 0) image = pygame.image.load('/home/pi/Desktop/image.jpg') while True: surface.fill(black) surface.blit(image, (0, 0)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() fpsClock.tick(30)
def get_current_image_as_jpg( camera, filename ): if picamera_available == True: camera.start_preview() camera.capture(filename, format='jpeg', resize=(WIDTH,HEIGHT)) camera.stop_preview() else: img = camera.get_image() pygame.image.save(img,filename) return
def get_current_image_as_jpg( camera, filename ): if picamera_available == True: #camera.start_preview() camera.capture(filename, format='jpeg', resize=(WIDTH,HEIGHT)) #camera.stop_preview() else: img = camera.get_image() pygame.image.save(img,filename) return
def camerapi(self,event): camera = picamera.PiCamera() camera.resolution = (2592, 1944) camera.drc_strength = 'high' time.sleep(2) filename = str(self.variable1) + ' Bottomview.jpg' filename2 =str(self.variable1) npath ="/home/pi/FootCam/" + str(filename2) if not os.path.isdir(npath): os.makedirs(npath) camera.capture(npath + "/" + filename) camera.close()
def phototaking(self, event): camera = picamera.PiCamera() camera.resolution = (2592, 1944) camera.drc_strength = 'high' filename = 'Timelapse.jpg' npath = "/home/pi/" + str(filename) if not os.path.isdir(npath): os.makedirs(npath) time_of_lapse = 100 while time_of_lapse > 0: camera.capture(npath + "/" + str(time_of_lapse) + filename) time_of_lapse = time_of_lapse - 1 camera.close()
def take_pic(camera): #prendre une photo en preview Ymd = datetime.datetime.now().strftime( "%Y-%m-%d") #récupération de la date Ymdhms = datetime.datetime.now().strftime( "%Y-%m-%d %H-%M-%S") #récupération de l'heure #vérification et/ou création du dossier "Photos" os.makedirs("Photos", exist_ok=True) os.chdir("Photos") os.makedirs(Ymd, exist_ok=True) os.chdir(Ymd) camera.capture(Ymdhms + '.jpg') #prise de la photo os.chmod( '.', 0o777 ) #changement des droits : tout le monde peut écrire dans le dossier et y supprimer des éléments #retour au dossier de travail os.chdir("..") os.chdir("..")
def TakePicture(self): #Code to detect the os and take a picture and store in tmp #First we detect what os if platform.system() == "Windows": cam = VideoCapture(0) # 0 -> index of camera s, img = cam.read() if s: # frame captured without any errors imwrite("tmp/photo.bmp", img) #save image else: #camera.brightness=100 #camera.contrast=50 #camera.sharpness=100 #camera.ISO=0 #camera.exposure_compensation=0 camera.resolution = (640, 480) camera.exposure_mode = 'auto' camera.meter_mode = 'average' camera.capture('tmp/photo.bmp')
def captureCSIImageAndSendOut(): isOn = isLocalTakePhotoOn() if isOn: try: camera = picamera.PiCamera() #cameraConfigDict["latestLocalUploadTime"] camera.resolution = (1920, 1080) #camera.start_preview() # Camera warm-up time time.sleep(2) #Image name fileName = str(current_milli_time()) + ".jpg" camera.capture(fileName) camera.close() #camera.stop_preview() print "SHOOOOOTTTTTing CSI image" sendImageToLocalAndRemoteServer(cpu_serial, fileName) except Exception, e: print str(e)
def captureCSIImage(): isOn = isLocalTakePhotoOn() if isOn: try: #camera.start_preview() # Camera warm-up time #time.sleep(1) #Get storage path onboard_storage_path = get_storage_path(cpu_serial) #Image name fileName = onboard_storage_path + str( current_milli_time()) + ".jpg" camera.capture(fileName) #camera.close() #camera.stop_preview() print "SHOOOOOTTTTTing CSI image" #sendImageToLocalAndRemoteServer(cpu_serial, fileName) except Exception, e: print str(e)
def quit_app(camera): #quitte proprement la caméra camera.annotate_text = "" #réinitialise le texte affiché Ymd = datetime.datetime.now().strftime( "%Y-%m-%d") #récupération de la date #vérification et/ou création du dossier "Photos" os.makedirs("Photos", exist_ok=True) os.chdir("Photos") os.makedirs(Ymd, exist_ok=True) os.chdir(Ymd) camera.capture('last_image_saved.jpg', resize=(299, 168)) #prise d'un cliché pour l'interface graphique os.chmod( '.', 0o777 ) #changement des droits : tout le monde peut écrire dans le dossier et y supprimer des éléments #retour au dossier de travail os.chdir("..") os.chdir("..") #quitte et ferme la caméra camera.close() pygame.display.quit()
if os.name == 'nt': # print("Windows doesn't support camera functionality") return self.cam.start() img = self.cam.get_image() now = datetime.now() if not os.path.exists(path): os.mkdir(path) pygame.image.save(img, path + now.strftime("%y-%b-%d_%H:%M:%S") + ".jpg") self.cam.stop() print(str(datetime.now()) + ': pic taken') #print("File: +" str(os.path.isfile(path))) def capture_next_winner(self): try: self.capture("./images/") except Exception as e: print(e) def exit(self): return #try: #except Exception as e: # print(e) if __name__ == '__main__': camera = Camera() camera.capture('../img/')
def startCamera(expTime): #démarre la caméra et sa preview #initialise pygame et ecran pygame.init() screen = pygame.display.set_mode((640, 480), 0) #initialisation de la caméra camera = picamera.PiCamera() #création de l'objet caméra camera.resolution = (1280, 720) #paramétrage de la résolution camera.crop = (0.0, 0.0, 1.0, 1.0) camera.framerate = float(24) #paramétrage des FPS camera.shutter_speed = expTime #paramétrage du temps d'exposition x = (screen.get_width() - camera.resolution[0]) / 2 y = (screen.get_height() - camera.resolution[1]) / 2 # Init buffer rgb = bytearray(camera.resolution[0] * camera.resolution[1] * 3) #camera.start_preview(fullscreen=False, window = (0, 0, width, height))#démarre la preview global pad, target, already #création de variables semi-locales target = Image.open('/home/pi/Desktop/Capsula/Icon/target.png' ) #ouverture de l'image "target" already = False #état : cible non affichée pad = Image.new('RGBA', ( ((target.size[0] + 31) // 32) * 32, ((target.size[1] + 15) // 16) * 16, )) pad.paste(target, (0, 0)) #ajout des raccourcis sous forme de texte sur la vidéo #camera.annotate_text_size = 25 #camera.annotate_foreground = picamera.Color('white') #camera.annotate_text = "P : capture image\nV : Start recording video (v again to stop)\nC: Enable/Disable target\nBackspace : Exit" running = True #état : caméra active while running: #tant que la caméra est active stream = io.BytesIO() camera.capture(stream, use_video_port=True, format='rgb') stream.seek(0) stream.readinto(rgb) stream.close() img = pygame.image.frombuffer( rgb[0:(camera.resolution[0] * camera.resolution[1] * 3)], camera.resolution, 'RGB') screen.fill(0) if img: screen.blit(img, (x, y)) pygame.display.update() for event in pygame.event.get( ): #si il se produit une action sur le clavier if event.type == pygame.KEYDOWN: if event.key == pygame.K_p: #si la touche p est enfoncée take_pic(camera) elif event.key == pygame.K_v: #si la touche v est enfoncée take_video(camera) elif event.key == pygame.K_c: #si la touche c est enfoncée print_target(camera) elif event.key == pygame.K_BACKSPACE: #si la touche retour est enfoncée running = False #état : caméra inactive quit_app(camera) #quit_app(camera) #quitte la preview et la caméra elif event.key == pygame.K_UP: #if up key is pressed startM() #start motor elif event.key == pygame.K_DOWN: #if down key is pressed stopM() elif event.key == pygame.K_SPACE: #if space key is pressed changeDirectionM() elif event.key == pygame.K_TAB: #if tab key is pressed stepM() elif event.key == pygame.K_LSHIFT: #if left shift is pressed stepmM() camera.close() pygame.display.quit()
def takeAShot(self): if self.env == 1: self.main.TextOut.addText( "[J.A.R.V.I.S.]: You have no camera installed. I will pick the last picture that was made." ) return False self.streaming = True self.btn_shot = self.window.blit(self.img_stop, self.btn_shot) self.rects_to_update.append(self.btn_shot) with picamera.PiCamera() as camera: camera.resolution = (250, 250) camera.brightness = self.brightness camera.framerate = 60 stream = io.BytesIO() while self.streaming: camera.capture(stream, use_video_port=True, format='jpeg') image = Image.open(stream) pygameimg = pygame.image.fromstring(image.tobytes(), image.size, image.mode) self.pic = self.window.blit(pygameimg, self.pic) #UPDATE screen self.rects_to_update.append(self.pic) self.display.update(self.rects_to_update) self.rects_to_update = [] #checking via pygame.event.get(pygame.MOUSEBUTTONDOWN) does have some bugs, apparently... for event in pygame.event.get(): if event.type != pygame.MOUSEBUTTONDOWN: continue if event.button == 1: #take a shot if self.btn_shot.collidepoint(event.pos): self.main.TextOut.addText( "[J.A.R.V.I.S.]: Taking picture... TIP: You can change the brightness!" ) self.streaming = False image.save("data/image_RAW.png") pygame.event.clear() self.btn_shot = self.window.blit( self.img_shot, self.btn_shot) self.rects_to_update.append(self.btn_shot) continue #Brighntess: elif self.btn_minus.collidepoint(event.pos): if self.brightness > 0: self.brightness -= 5 camera.brightness -= 5 self.main.TextOut.addText( "[J.A.R.V.I.S.]: DECREASED BRIGHTNESS. It's now at {}%!" .format(self.brightness)) else: self.main.TextOut.addText( "[J.A.R.V.I.S.]: The Brightness is already on 0%! (That's the low.)" ) elif self.btn_plus.collidepoint(event.pos): if self.brightness < 100: self.brightness += 5 camera.brightness += 5 self.main.TextOut.addText( "[J.A.R.V.I.S.]: INCREASED BRIGHTNESS. It's now at {}%!" .format(self.brightness)) else: self.main.TextOut.addText( "[J.A.R.V.I.S.]: The Brightness is already on 100%! (That's the peak.)" ) stream = io.BytesIO()
current_milli_time = lambda: int(round(time.time() * 1000)) #Initiate the camera try: camera = picamera.PiCamera() camera.resolution = (1024, 768) #camera.start_preview() # Camera warm-up time print "first sleep started" time.sleep(2) print "first sleep ended" #Image name fileName = str(current_milli_time()) + ".jpg" camera.capture(fileName) print "first captured ended" #camera.stop_preview() camera.close() print "first closed" print "1 SHOOOOOTTTTTing CSI image" time.sleep(2) #Again #camera.start_preview() camera = picamera.PiCamera() camera.resolution = (1024, 768) fileName = str(current_milli_time()) + ".jpg" camera.capture(fileName) #camera.stop_preview() camera.close() print "2 SHOOOOOTTTTTing CSI image"
sys.exit() while True: x_pix = 0 y_pix = 0 l = 0 display.fill((255, 255, 255)) for event in pygame.event.get(): if event.type == pygame.QUIT: close() break #caspture a rbg picture to the stream camera.capture(stream, 'rgb', use_video_port=True) #somehow makes us process. lack luster docs.... stream.seek(0) #iterate over all pix for y in range(h): for x in range(w): #get pixs r_vals = stream.array[y, x, 0] g_vals = stream.array[y, x, 1] b_vals = stream.array[y, x, 2] if b_vals > g_vals and b_vals > r_vals and b_vals > 175: x_pix += x
# カラーバー画像作成 colorbar_img = make_colorbar() # 実機 if setting.mode == 0: #センサ、カメラスタート sensor.start() camera.start() while(True): # 時間計測開始 #t1 = time.time() # カメラから映像を取得する camera_img1 = camera.capture() if setting.sensor: #Lepton camera_img = camera_img1[70: 430, 60: 540] else: camera_img = camera_img1 # センサデータ取得 sensordata = sensor.GetData() #print('------ Thermo Data -------') #print(*sensordata, sep='\n') #print('--------------------------') # 自動キャリブレーション Leptonは未調整 if setting.sensor == 0: GetBodyTempData.setOffsetTempData(sensordata)
def take_picture(): camera = picamera.PiCamera() camera.start_preview() sleep(5) camera.capture('/home/pi/Desktop/image.jpg') camera.stop_preview()
def get_img(source, file_name=None): """Return a 2-dimensional array of rgb pixels. """ width = init.sensing_config.data['img_width'] height = init.sensing_config.data['img_height'] if source == 'file': log.info("Getting image from file.") if None == file_name: file_name = input("Enter image name: ") img = image.imread("imgs/" + file_name) # save image to sample.png for debugging image.imsave('raw-sample.png', img) return img elif source == 'usb': log.info("Getting image from camera.") cam_id = init.sensing_config.data['camera_id'] pygame.camera.init() pygame.camera.list_cameras() cam = pygame.camera.Camera("/dev/video" + str(cam_id)) cam.start() # Take the picture init.hardware.set_pin('sensing_led', True) img = cam.get_image() init.hardware.set_pin('sensing_led', False) img = pygame.transform.scale(img, (width, height)) pixels = pygame.surfarray.array3d(img) pygame.image.save(img,"raw-sample.png") cam.stop() return pixels elif source == 'rpi': log.info("Getting image from RPi camera.") if running_on_rpi(): with picamera.PiCamera() as camera: with picamera.array.PiRGBArray(camera) as stream: # Turn on LED init.hardware.set_pin('sensing_led', True) # sleep to guarantee led is on... time.sleep(0.1) # adjust resolution for easier data processing camera.resolution = (width, height) camera.capture(stream, format='rgb') # was 'bgr' # At this point the image is available as stream.array img = stream.array # save to file camera.capture('raw-sample.png') # Turn off LED init.hardware.set_pin('sensing_led', False) return img else: log.error("Not running on RPi.") else: log.error("Invalid image source.") return None
if config["CameraBiContinious"] == "Yes" or "yes": camera.cam.start() if MyPlatform == "Linux": if config["SinglePic"] == "no": # we are not doing singlepictures SettingClass.setting("exposure_auto=3") SettingClass.setting("exposure_auto_priority=1") for SettFile in SettingFiles: imagestring = prefix+folder+"/%s/%s.tif"% (str(SettFile), loopcount) print("imagestring: %s"% imagestring) SettingClass.getsetting(str(SettFile)) #get and set settings CaptureTime = camera.capture(imagestring, loopcount) # capture image move(imagestring, SettFile) # copy to webserver print() else: # singlepictures for linux imagestring = prefix+folder+"/%s/%s.tif"% (config["SinglePicCaptureFolder"], loopcount) if config["ExAlgo"] == True: SettingClass.setting("exposure_auto=0") focuslen = 5 # meter fnumber = focuslen/0.008 exposuredur = 10 #second ev = math.log( (math.pow(fnumber,2)/exposuretime), 2) SettingClass.setting("exposure_absolute=" + str(ev))
text = font.render("Smile!", True, (128, 0, 0)) screen.blit(text, (MIDDEL_X - text.get_width() // 2, MIDDEL_Y - text.get_height() // 2)) else: #display the time text = font.render(str(count_down), True, (128, 0, 0)) screen.blit(text, (MIDDEL_X - text.get_width() // 2, MIDDEL_Y - text.get_height() // 2)) ############### #Capture State# ############### #this state captures the image elif current_state == 2: file_path = camera.capture(gp.GP_CAPTURE_IMAGE) screen.fill([255, 255, 255]) text = welcome_font.render("processing...", True, (0, 0, 0)) screen.blit(text, (MIDDEL_X - text.get_width() // 2, MIDDEL_Y - text.get_height() // 2)) next_state = 2_5 elif current_state == 2_5: target = foldername + "/images/" + file_path.name camera_file = camera.file_get(file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL) print(target) camera_file.save(target) # subprocess.call(['xdg-open', target])
def set_up(): #Width and height of screen width = 700 height = 500 #resolution of camera resolution = (700, 500) #calculate the scale of pixels on canvas w, h = resolution scaleW = width / w scaleH = height / h #setup sht pygame.init() pygame.camera.init() #set up for main video display = pygame.display.set_mode((width, height), 0, 32) pygame.display.set_caption("Blob Tracker") #set up for picamerai camera = picamera.PiCamera() stream = picamera.array.PiRGBArray(camera) camera.resolution = resolution camera.vflip = True #preview so we can see whats beeing seen. camera.start_preview(fullscreen=False, window=(100, 20, 640, 480)) while True: x_pix = 0 y_pix = 0 l = 0 display.fill((255, 255, 255)) for event in pygame.event.get(): if event.type == pygame.QUIT: close() break #caspture a rbg picture to the stream camera.capture(stream, 'rgb', use_video_port=True) #somehow makes us process. lack luster docs.... stream.seek(0) #iterate over all pix for y in range(h): for x in range(w): #get pixs r_vals = stream.array[y, x, 0] g_vals = stream.array[y, x, 1] b_vals = stream.array[y, x, 2] if b_vals > g_vals and b_vals > r_vals and b_vals > 175: x_pix += x y_pix += y l += 1 if l > 0: #calc the mean x_pix /= l y_pix /= l print('x', x_pix) print('y', y_pix) pygame.draw.circle(display, (255, 0, 0), (int(x_pix), int(y_pix)), 5, 0) else: print("nothing to report sir") stream.seek(0) stream.truncate() pygame.display.update()