def camstream(): count = 0 pygame.init() pygame.camera.init() display = pygame.display.set_mode(SIZE, 0) camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) capture = True while capture: screen = camera.get_image(screen) display.blit(screen, (0,0)) pygame.display.flip() pygame.time.wait(100) pygame.image.save(screen, "frame%d.jpg" % count) count += 1 if count > 20: break # for event in pygame.event.get(): # if event.type == QUIT: # capture = False # elif event.type == KEYDOWN and event.key == K_x: # pygame.image.save(screen, "frame%d.jpg" % count) # count += 1 camera.stop() pygame.quit() return
def capture_image_pygame(self, camera_path: str, image_path: str) -> None: """Captures an image with pygame.""" self.logger.debug("Capturing image from camera: {}".format(camera_path)) # Capture image try: # Check if simulated # if self.simulate: # message = "Simulating capture, saving image to: {}".format(image_path) # self.logger.info(message) # command = "cp {} {}".format(self.SIMULATION_IMAGE_PATH, image_path) # os.system(command) # return # Capture and save image if not self._simulate_capture(image_path): resolution_array = self.resolution.split("x") resolution = (int(resolution_array[0]), int(resolution_array[1])) camera = pygame.camera.Camera(camera_path, resolution) camera.start() image = camera.get_image() pygame.image.save(image, image_path) camera.stop() except Exception as e: raise exceptions.CaptureImageError(logger=self.logger) from e
def camstream(): bluetoothSerial = serial.Serial("/dev/rfcomm0", baudrate=9600) pygame.init() pygame.camera.init() DEVICE = pygame.camera.list_cameras() SIZE = (640, 480) FILENAME = 'capture.png' display = pygame.display.set_mode(SIZE, 0) camera = pygame.camera.Camera(DEVICE[0], SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) capture = True while capture: screen = camera.get_image(screen) display.blit(screen, (0, 0)) pygame.display.flip() isStealed = bluetoothSerial.readline().decode("utf-8") #for event in pygame.event.get(): # if event.type == QUIT: # capture = False # elif event.type == KEYDOWN and event.key == K_s: # pygame.image.save(screen, FILENAME) if isStealed == "1111" or "2222" or "3333" or "4444" or "5555" or "6666" or "7777": pygame.image.save(screen, FILENAME) camera.stop() pygame.quit() return
def anaoshots(number, fid, rid, lid, eid, camera_frame_rate): # initialize pygame.init() pygame.camera.init() # capture a image camera = pygame.camera.Camera("/dev/video0", (640, 480)) camera.start() print("open camera success") c = 1 starttime = time.time() while c <= number: # 循环读取视频帧 image = camera.get_image() pygame.image.save( image, r'../../data/test_data/' + os.listdir('../../data/test_data/')[0] + '/' + fid + '_' + rid + '_' + lid + '_' + eid + '_' + eid + '1_' + str(time.time()) + '.jpg') print('save the image', c) print(time.time() - starttime) c += 1 usetime = time.time() - starttime # sleeptime = separatedtime * c - usetime #if sleeptime > 0: time.sleep(sleeptime) print('采集结束') camera.stop()
def do_scan(self): display = pygame.display.set_mode(self.videosize, 0) pygame.display.iconify() camera = pygame.camera.Camera(self.camera, self.videosize) camera.start() screen = pygame.surface.Surface(self.videosize, 0, display) Locked = True while Locked: img = camera.get_image(screen) pygame.image.save(img, repertoire_script + 'data{}image.jpg'.format(os.sep)) img = Image.open(repertoire_script + 'data{}image.jpg'.format(os.sep)) codes = pyzbar.decode(img) if len(codes) > 0: Locked = False text = pytesseract.image_to_string(Image.open(repertoire_script + 'data{}image.jpg'.format(os.sep))) if len(text) > 0: Locked = False time.sleep(2) os.remove(repertoire_script + 'data{}image.jpg'.format(os.sep)) camera.stop() for l in codes: donnees = l.data.decode('utf-8') print(_('Données du code: {}'.format(donnees))) donnees = '{}\n{}'.format(donnees, text) try: pyperclip.copy(donnees) except: if self.debug: print(_('Impossible de copier le texte.')) self.destroy()
def __init__(self, nombre): FILENAME = str(nombre) DEVICE = '/dev/video0' SIZE = (640, 480) pygame.init() pygame.camera.init() display = pygame.display.set_mode(SIZE, 0) camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) capture = True while capture: screen = camera.get_image(screen) display.blit(screen, (0, 0)) pygame.display.flip() for event in pygame.event.get(): if event.type == KEYDOWN and event.key == K_s: os.chdir("imagenes") print("guardado") pygame.image.save(screen, FILENAME) os.chdir("..") capture = False camera.stop() pygame.quit() return
def camstream(): pygame.init() pygame.camera.init() display = pygame.display.set_mode(SIZE, 0) #try to go fullscreen #display = pygame.display.set_mode((1920,1080),pygame.FULLSCREEN) #does bot work due to resolution limit? #hide mouse pygame.mouse.set_visible(0) camera = pygame.camera.Camera(DEVICE, SIZE, "HSV") camera.start() screen = pygame.surface.Surface(SIZE, 0, display) capture = True while capture: screen = camera.get_image(screen) display.blit(screen, (0, 0)) pygame.display.flip() #this is for capturing an image for event in pygame.event.get(): if event.type == QUIT: capture = False elif event.type == KEYDOWN and event.key == K_s: pygame.image.save(screen, FILENAME) camera.stop() pygame.quit() return
def camstream(): ''' The bulk of the camera code was not written by us, since it's just here for fun and does not contribute to the actual game in any meaningful way. We use this to make a avatar for the user on the fly modified from https://gist.github.com/snim2/255151 works only in linux, or by installing some dependency in windows [not tested] ''' try: DEVICE = '/dev/video0' SIZE = (640, 480) FILENAME = 'assets/avatar.png' import pygame.camera pygame.camera.init() display = pygame.display.set_mode((800, 60 * 8), 0) camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) screen = camera.get_image(screen) pygame.image.save(screen, FILENAME) camera.stop() return except: # if camera fails to take a picture, use backup generic avatar from shutil import copyfile copyfile('assets/backupavatar.png', 'assets/avatar.png')
def camstream(): pygame.init() pygame.camera.init() display = pygame.display.set_mode((1280, 960), 0) camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) capture = True time.sleep(1) initial = camera.get_image(screen).copy() height = initial.get_height() width = initial.get_width() print(height) print(width) print(initial.get_at([0,0])) print(averagepix(initial)) while capture: initial = camera.get_image(screen).copy() screen = camera.get_image(screen) screen = surfdiff(screen,initial) derr = pygame.transform.scale2x(pygame.transform.flip(screen.copy(),True,False)) display.blit(derr,(5,5)) pygame.display.flip() #pygame.display.update() for event in pygame.event.get(): if event.type == QUIT: capture = False elif event.type == KEYDOWN and event.key == K_s: pygame.image.save(screen, FILENAME) camera.stop() pygame.quit() return
def camstream(): global capture global distance global distdelay global elwidth global elheight global formoverlay global area global distance_glob global pictureVar pygame.init() pygame.camera.init() display = pygame.display.set_mode(SIZE, 0) camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) pygame.mouse.set_visible(0) thread = Thread(target=rotaryThread) thread.start() while capture: if (not pictureVar): frame = camera.get_image(screen) frame = modFrame(frame) if (formoverlay == 1): pygame.draw.ellipse(frame, BLACK, [ 80 - (elwidth / 2), 64 - (elheight / 2), elwidth, elheight ], 3) if (formoverlay == 2): pygame.draw.rect(frame, BLACK, [ 80 - (elwidth / 2), 64 - (elheight / 2), elwidth, elheight ], 3) frame = pygame.transform.rotozoom(frame, 270, 0.8) display.fill((0, 0, 0)) display.blit(frame, (0, 0)) if (distdelay > 10): #distance = round(distanz(), 0) thread2 = Thread(target=distanz) thread2.start() distdelay = 0 if (formoverlay == 2): area = calc_area_rect(distance_glob, elwidth, elheight) elif (formoverlay == 1): area = calc_area_ellipse(distance_glob, elwidth, elheight) distdelay = distdelay + 1 displaytext("Dist: " + str(distance_glob), 18, 3, (250, 100, 100), False, display) displaytext("Area: " + str(area), 25, 1, (250, 100, 100), False, display) pygame.display.flip() for event in pygame.event.get(): handle(event) else: displaytext("Saved", 18, 2, (0, 0, 0), False, display) pygame.display.flip() camera.stop() pygame.quit() GPIO.cleanup() return
def jalankanKamera(self): DEVICE = '/dev/video0' SIZE = (640,480) FILENAME = 'capture'+str(self.penghitung)+'.png' pygame.init() pygame.camera.init() display = pygame.display.set_mode(SIZE, 0) camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) pygame.display.set_caption("Kamera Gabut qywok") capture = True while capture: screen = camera.get_image(screen) display.blit(screen, (0,0)) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: capture = False elif event.type == pygame.KEYDOWN and event.key == K_SPACE: pygame.image.save(screen, FILENAME) camera.stop() pygame.quit() self.isi.set('Mulai Lagi') self.ucapan.set("Selamat...!! gambar anda telah tersimpan...\n" "dengan nama 'capture"+str(self.penghitung)+".png' silahkan di cek di \n" "folder tempat anda menyimpan file python nya..\n" "Untuk memulai untuk memotret lagi, silahkan tekan\n" "tombol 'mulai lagi' dan ingat tekan tombol 'spasi'\n" "untuk mengambil gambar.") self.penghitung+=1 return camera.stop() pygame.quit() return
def camstream(): DEVICE = '/dev/video0' SIZE = (640, 480) FILENAME = 'capture.png' pygame.init() pygame.camera.init() display = pygame.display.set_mode(SIZE, 0) camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) capture = True while capture: screen = camera.get_image(screen) pil_string_image = pygame.image.tostring(screen,"RGBA",False) im=Image.frombytes("RGBA",(640,480),pil_string_image) im.show() time.sleep(0.5) im.close() display.blit(screen, (0,0)) pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: capture = False elif event.type == KEYDOWN and event.key == K_s: pygame.image.save(screen, FILENAME) camera.stop() pygame.quit() return
def camstream(): pygame.init() pygame.camera.init() display = pygame.display.set_mode(SIZE, 0) camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) capture = True while capture: screen = camera.get_image(screen) display.blit(screen, (0,0)) pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: capture = False elif event.type == KEYDOWN: im = pygame.image.save(screen, FILENAME) camera.stop() pygame.quit() capture = False Button_Example() camera.stop() pygame.quit() return
def capture_images(): DEVICE = '/dev/video0' SIZE = (640, 480) FILENAME = '/media/abisek/Important Files/R.K/++/Machine Learning/Projects/K/captures/capturetest' pygame.init() pygame.camera.init() display = pygame.display.set_mode(SIZE, 0) camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) capture = True count = 0 while capture: screen = camera.get_image(screen) display.blit(screen, (0, 0)) pygame.display.flip() for event in pygame.event.get(): if event.type == KEYDOWN and event.key == 113: capture = False elif event.type == KEYDOWN and event.key == 97: pygame.image.save(screen, FILENAME + str(count) + '.jpg') count += 1 camera.stop() pygame.quit()
def scan_code(device, size): pygame.init() pygame.camera.init() display = pygame.display.set_mode(size, 0) pygame.display.set_caption("Scan QR-code here") camera = pygame.camera.Camera(device, size) camera.start() screen = pygame.surface.Surface(size, 0, display) capture = True while capture: screen = camera.get_image(screen) display.blit(screen, (0, 0)) pygame.display.flip() string = pygame.image.tostring(screen, "RGBA", False) image = Image.frombytes("RGBA", size, string) codes = zbarlight.scan_codes('qrcode', image) if codes: code = codes[0] capture = False for event in pygame.event.get(): if event.type == QUIT: capture = False camera.stop() pygame.quit() code = str(code) code = code[2:len(code) - 1] return code
def camstream(): pygame.init() pygame.camera.init() display = pygame.display.set_mode(SIZE, 0) camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) capture = True while capture: screen = camera.get_image(screen) display.blit(screen, (0, 0)) pygame.display.flip() string = pygame.image.tostring(screen, "RGBA", False) image = Image.frombytes("RGBA", SIZE, string) codes = zbarlight.scan_codes('qrcode', image) if codes: print('QR codes: %s' % codes[0]) for event in pygame.event.get(): if event.type == QUIT: capture = False elif event.type == KEYDOWN and event.key == K_s: pygame.image.save(screen, FILENAME) print("saved") camera.stop() pygame.quit() return
def captureImage(): global captureSoundSeq if (captureSoundSeq == 1): sdInit.play() if (captureSoundSeq == 2): sdConf.play() if (captureSoundSeq == 3): sdBegin.play() captureSoundSeq = captureSoundSeq + 1 if (captureSoundSeq > 3): captureSoundSeq = 1 camera = pygame.camera.Camera(DEVICE, (800, 480), "RGB") camera.start() sleep(.25) camGrab = camera.get_image() #create a new animation canvas animFrame = pygame.Surface(lastScreen.get_size()) animFrame = animFrame.convert() pygame.draw.rect(animFrame, (0, 0, 0), (0, 0, 800, 480)) lastScreen.blit(animFrame, (0, 0)) capture = True camGrab = pygame.transform.flip(camGrab, False, True) while capture: if camera.query_image(): captureSurface = camera.get_image() # flipping image captureSurface = pygame.transform.flip(captureSurface, False, True) display.blit(captureSurface, (0, 0)) pygame.display.flip() if shutterButton.is_pressed: pygame.image.save(display, ("CapturedImages/" + photoFileName)) shutterSound.play() flashFrame = pygame.Surface(lastScreen.get_size()) flashFrame = flashFrame.convert() pygame.draw.rect(display, (255, 255, 255), (0, 0, 800, 480)) pygame.display.flip() sleep(.25) capture = False for event in pygame.event.get(): if event.type == QUIT: pygame.quit() appRunning = False break if event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() appRunning = False break camera.stop() return
def capture_image(): camera.start() pygame_surface = camera.get_image() camera.stop() pil_string_image = pygame.image.tostring(pygame_surface, 'RGB', False) image = Image.frombytes('RGB', (CANVAS_WIDTH, CANVAS_HEIGHT), pil_string_image) return image
def camstream(): pygame.init() clock = pygame.time.Clock() pygame.camera.init() pprint.pprint(pygame.camera.list_cameras()) display = pygame.display.set_mode(screen_size, pygame.FULLSCREEN) camera = pygame.camera.Camera(DEVICE, camera_size) camera.start() actual_camera_size = camera.get_size() pprint.pprint(actual_camera_size) screen = pygame.surface.Surface(screen_size, 0, display) frame = pygame.surface.Surface(camera_size, 0, display) detect = pygame.surface.Surface(detect_size, 0, display) capture = True while capture: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_s: capture = False elif event.type == KEYDOWN: if event.key == K_s: pygame.image.save(screen, FILENAME) elif event.key == K_q: capture = False if camera.query_image(): camera.get_image(frame) pygame.transform.scale(frame, screen_size, screen) pygame.transform.flip(screen, True, False) # make a rect in the middle of the screen capture_rect = pygame.draw.rect(screen, (255, 255, 255), (390, 230, 20, 20), 1) # get the average color of the area inside the rect capture_colour = pygame.transform.average_color( screen, capture_rect) pygame.transform.scale(screen, detect_size, detect) pygame.transform.laplacian(detect, detect) # pygame.transform.threshold(detect, capture_colour, (90, 170, 170), (0, 0, 0), 2) display.blit(screen, (0, 0)) # fill the upper left corner with that color display.fill(capture_colour, (0, 0, 24, 24)) display.blit(detect, detect_origin) pygame.display.flip() dt = clock.tick(10) camera.stop() pygame.quit() return
def signal_handler(signal, frame): print('Closing camera safefully (hopefully)') if camera: print("stopping camera") camera.stop() print("camera stopped") pygame.close() print("exiting") os._exit(0)
def camstream(): pygame.init() pygame.display.set_caption("อ่าน BARCODE & QRCODE จาก กล้องเว็บแคม USB") display = pygame.display.set_mode(SIZE0, 0, 24) f01 = pygame.font.Font("Garuda-Bold.ttf", 12) pygame.camera.init() camera = pygame.camera.Camera(DEVICE0, SIZECAM) camera.start() surfcam = pygame.surface.Surface(SIZECAM, depth=24) FPS = 25 clock = pygame.time.Clock() running = True while running: camera.get_image(surfcam) display.blit(surfcam, (0, 0)) xrect1 = pygame.Rect(0, CAMH, CAMW, 20) pygame.draw.rect(display, xcolor[0], xrect1) msgcam = "คลิกซ้าย..อ่าน BARCODE คลิกขวา..อ่าน QRCODE" display.blit(f01.render(msgcam, True, xcolor[1]), (10, CAMH)) pygame.display.flip() for event in pygame.event.get(): #event quit if event.type == QUIT: running = False elif event.type == KEYDOWN and event.key == K_q: running = False elif event.type == pygame.MOUSEBUTTONDOWN: #[1=Lclick 3=Rclick 2=Mclick 4=ScrUp 5=ScrDN] if (event.button == 1): #event zbar ximgndarray = getimg_ndarray(surfcam) xrtns = convzbar(ximgndarray) if (event.button == 3): #event zbarlight xfile = 'filecam.png' pygame.image.save(surfcam, xfile) xrtns = convzbarlight(xfile) display.blit(surfcam, (CAMW, 0)) xrect2 = pygame.Rect(CAMW, CAMH, CAMW, 20) pygame.draw.rect(display, xcolor[2], xrect2) msgzbar = xrtns[0] display.blit(f01.render(msgzbar, True, xcolor[0]), (CAMW + 10, CAMH)) pygame.display.flip() clock.tick(FPS) camera.stop() pygame.quit() return
def ampilight(): try: pixelArray = dotstar.DotStar(board.SCK, board.MOSI, X + 2 * Y, brightness=0.3, auto_write=False, baudrate=20000000) pixelArray.fill((0, 0, 0)) pygame.init() pygame.camera.init() camera = pygame.camera.Camera(DEVICE, SIZE_CAPTURE) screen = pygame.surface.Surface(SIZE_CAPTURE) tiny = pygame.surface.Surface((10, 5)) pixelMatrix = pygame.surface.Surface(SIZE_LED) camera.start() while True: camera.get_image(screen) pygame.transform.smoothscale(screen, (10, 5), tiny) pygame.transform.smoothscale(tiny, SIZE_LED, pixelMatrix) # right panel if True: idx = 0 for y in range(Y - 1): pixelArray[idx] = pixelMatrix.get_at( (X - 1 - OFFSET, Y - 1 - y))[:3] idx += 1 # top panel if True: idx = 23 for x in range(X): pixelArray[idx] = pixelMatrix.get_at( (X - 1 - x, OFFSET))[:3] idx += 1 # left panel if True: idx = 64 for y in range(Y - 1): pixelArray[idx] = pixelMatrix.get_at( (0 + OFFSET, y + 1))[:3] idx += 1 pixelArray = blackLevelCorrection(pixelArray) pixelArray.show() finally: print('stopping ...') pixelArray.fill((0, 0, 0)) camera.stop() pygame.quit() return
def savePictures(directory): camera = initializeCamera(CAM_INDEX) camera.start() user_directory = directory if not os.path.exists(user_directory): os.mkdir(user_directory) takePictures(camera, user_directory) camera.stop()
def camstream(): #--init pygame.init() display = pygame.display.set_mode(SIZE, 0) pygame.display.set_caption("ทดสอบ USB Webcam") pygame.camera.init() camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() screen = pygame.surface.Surface(SIZE, 0, display) #--loop FPS = 25 #--frame per sec clock = pygame.time.Clock() running = True while running: #camera background screen = camera.get_image(screen) #rectangle xcolor = (255, 255, 0) xrect = pygame.Rect(0, Cheight - 20, Cwidth, 20) pygame.draw.rect(screen, xcolor, xrect) display.blit(screen, (0, 0)) #text xcolor = (0, 0, 255) f00 = pygame.font.Font(None, 14) f01 = pygame.font.Font("Garuda-Bold.ttf", 12) msg = "C101: ประตูหน้า " + time.strftime(" %d-%m-%Y %I:%M:%S %p") display.blit(f01.render(msg, True, xcolor), (10, Cheight - 20)) #flip pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: running = False elif event.type == KEYDOWN and event.key == K_s: #save imagefile xfilename = FILEPATH + time.strftime("pic%Y-%m-%d--%H%M%S.jpg") pygame.image.save(display, xfilename) print(">>save image file: %s \n" % xfilename) #line_notify+image upload xrtn = LNF.line_notifyIMG("test usbcam", xfilename, headers) print("LINE>> status code, error string , total time\n ", xrtn) clock.tick(FPS) #--exit camera.stop() pygame.quit() return
def cameraStream(): #Initialize camera pygame.init() pygame.camera.init() #set window size display = pygame.display.set_mode((320,400),0) #get camera list and selet first camera cameraList = pygame.camera.list_cameras() if cameraList: camera = pygame.camera.Camera(cameraList[0],SIZE) #start the camera camera.start() sensor = DistanceSensor(echo=17, max_distance=3, trigger=4) #crate a surface to capture to screen = pygame.surface.Surface(SIZE, 0, display) working = True while working: display.fill(BLACK) #display image screen = camera.get_image(screen) #blit to the display surface display.blit(screen, (0,0)) dist = readSensor(sensor) if dist > 30: time = "MOVE" else: time = "STOP" font_big = pygame.font.Font(None, 50) # font size text_surface = font_big.render('%d cm = %s'%(dist,time),True, (255,150,0)) rect = text_surface.get_rect(center=(160,350)) # position display.blit(text_surface, rect) pygame.display.flip() pygame.display.update() events = pygame.event.get() for e in events: if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): #exit working = False camera.stop() pygame.quit() return
def eval_anaoshots(): # initialize pygame.init() pygame.camera.init() # capture a image camera = pygame.camera.Camera("/dev/video0", (640, 480)) camera.start() print("open camera success") while (True): time.sleep(0.1) with open('../param', 'r') as f: for i, line in enumerate(f): if i == 0: flag = line.strip() #开始暂停标志位 if i == 1: camera_frame_rate = line.strip() #帧率 if i == 2: camera_exposure_time = line.strip() #曝光时间 if i == 3: fid = line.strip() if i == 4: rid = line.strip() if i == 5: lid = line.strip() if i == 6: eid = line.strip() print('param1 = ', flag.rstrip()) print('camera_frame_rate = ', camera_frame_rate) separatedtime = 1 / float(camera_frame_rate) # 每隔0.1s读取一帧 if flag == '1': pass elif flag == '0': time.sleep(separatedtime) c = 0 number = 2 starttime = time.time() while True: # 循环读取视频帧 image = camera.get_image() pygame.image.save( image, r'../../data/test_data/' + os.listdir('../../data/test_data/')[0] + '/' + fid + '_' + rid + '_' + lid + '_' + eid + '_' + eid + '1_' + str(time.time()) + '.jpg') print('save the image') print(time.time() - starttime) c += 1 if c >= number: break usetime = time.time() - starttime sleeptime = separatedtime * c - usetime if sleeptime > 0: time.sleep(sleeptime) else: continue print('close') camera.stop()
def main(): default_model_dir = '../all_models' default_model = 'mobilenet_v2_1.0_224_quant_edgetpu.tflite' default_labels = 'imagenet_labels.txt' parser = argparse.ArgumentParser() parser.add_argument('--model', help='.tflite model path', default=os.path.join(default_model_dir, default_model)) parser.add_argument('--labels', help='label file path', default=os.path.join(default_model_dir, default_labels)) args = parser.parse_args() with open(args.labels, 'r') as f: pairs = (l.strip().split(maxsplit=1) for l in f.readlines()) labels = dict((int(k), v) for k, v in pairs) interpreter = common.make_interpreter(args.model) interpreter.allocate_tensors() pygame.init() pygame.camera.init() camlist = pygame.camera.list_cameras() print('By default using camera: ', camlist[-1]) camera = pygame.camera.Camera(camlist[-1], (640, 480)) width, height, channels = common.input_image_size(interpreter) camera.start() try: fps = deque(maxlen=20) fps.append(time.time()) while True: imagen = camera.get_image() imagen = pygame.transform.scale(imagen, (width, height)) input = np.frombuffer(imagen.get_buffer(), dtype=np.uint8) start_ms = time.time() common.input_tensor(interpreter)[:, :] = np.reshape( input, (common.input_image_size(interpreter))) interpreter.invoke() results = get_output(interpreter, top_k=3, score_threshold=0) inference_ms = (time.time() - start_ms) * 1000.0 fps.append(time.time()) fps_ms = len(fps) / (fps[-1] - fps[0]) annotate_text = 'Inference: {:5.2f}ms FPS: {:3.1f}'.format( inference_ms, fps_ms) for result in results: annotate_text += '\n{:.0f}% {}'.format(100 * result[1], labels[result[0]]) print(annotate_text) finally: camera.stop()
def camstream(display, camera, screen): while True: screen = camera.get_image(screen) display.blit(screen, (0,0)) pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: capture = False elif event.type == KEYDOWN and event.key == K_s: pygame.image.save(screen, FILENAME) camera.stop() pygame.quit() return
def main(): default_model_dir = '../all_models' default_model = 'mobilenet_v2_1.0_224_quant_edgetpu.tflite' default_labels = 'imagenet_labels.txt' parser = argparse.ArgumentParser() parser.add_argument('--model', help='.tflite model path', default=os.path.join(default_model_dir, default_model)) parser.add_argument('--labels', help='label file path', default=os.path.join(default_model_dir, default_labels)) args = parser.parse_args() with open(args.labels, 'r') as f: pairs = (l.strip().split(maxsplit=1) for l in f.readlines()) labels = dict((int(k), v) for k, v in pairs) interpreter = make_interpreter(args.model) interpreter.allocate_tensors() pygame.init() pygame.camera.init() camlist = pygame.camera.list_cameras() print('By default using camera: ', camlist[-1]) camera = pygame.camera.Camera(camlist[-1], (640, 480)) inference_size = input_size(interpreter) camera.start() try: last_time = time.monotonic() while True: imagen = camera.get_image() imagen = pygame.transform.scale(imagen, inference_size) start_ms = time.time() run_inference(interpreter, imagen.get_buffer().raw) results = get_classes(interpreter, top_k=3, score_threshold=0) stop_time = time.monotonic() inference_ms = (time.time() - start_ms) * 1000.0 fps_ms = 1.0 / (stop_time - last_time) last_time = stop_time annotate_text = 'Inference: {:5.2f}ms FPS: {:3.1f}'.format( inference_ms, fps_ms) for result in results: annotate_text += '\n{:.0f}% {}'.format(100 * result[1], labels[result[0]]) print(annotate_text) finally: camera.stop()
def show_camera_until(button): global screen font = pygame.font.Font(None, 36) text = font.render(u"Zum Loslegen: Roten Knopf drücken.", True, (128, 128, 128)) #screen = init_pygame() pixel_width = 1024 pixel_height = 768 camera = pygame.camera.Camera("/dev/video0",(pixel_width,pixel_height)) camera.start() while GPIO.input(button) == GPIO.HIGH: image = camera.get_image() screen.blit(image,(offset_x,offset_y)) screen.blit(text,(512 - text.get_width() // 2, 384 - text.get_height() // 2)) pygame.display.flip() sleep(0.0001) camera.stop()
def brightness(self): camera = pygame.camera.Camera(self.source, (self.width, self.height)) camera.start() time.sleep(0.1) image = camera.get_image() camera.stop() collection = [] for x in range(0, self.width): for y in range(0, self.height): r, g, b, a = image.get_at((x, y)) collection.append(self.brightnessFromRGB(r, g, b)) return math.floor(sum(collection) / len(collection))
def take_shot(): pygame.init() pygame.camera.init() camera = pygame.camera.Camera(DEVICE, SIZE) camera.start() # Stabilize the image for i in range(10): screen = camera.get_image() pygame.image.save(screen, FILENAME) camera.stop() pygame.quit() return screen
def main(): default_model_dir = "../all_models" default_model = 'mobilenet_v2_1.0_224_quant_edgetpu.tflite' default_labels = 'imagenet_labels.txt' parser = argparse.ArgumentParser() parser.add_argument('--model', help='.tflite model path', default=os.path.join(default_model_dir, default_model)) parser.add_argument('--labels', help='label file path', default=os.path.join(default_model_dir, default_labels)) args = parser.parse_args() with open(args.labels, 'r') as f: pairs = (l.strip().split(maxsplit=1) for l in f.readlines()) labels = dict((int(k), v) for k, v in pairs) engine = edgetpu.classification.engine.ClassificationEngine(args.model) pygame.init() pygame.camera.init() camlist = pygame.camera.list_cameras() camera = pygame.camera.Camera(camlist[0], (640, 480)) _, width, height, channels = engine.get_input_tensor_shape() camera.start() try: fps = deque(maxlen=20) fps.append(time.time()) while True: imagen = camera.get_image() imagen = pygame.transform.scale(imagen, (width, height)) input = np.frombuffer(imagen.get_buffer(), dtype=np.uint8) start_ms = time.time() results = engine.ClassifyWithInputTensor(input, top_k=3) inference_ms = (time.time() - start_ms) * 1000.0 fps.append(time.time()) fps_ms = len(fps) / (fps[-1] - fps[0]) annotate_text = "Inference: %5.2fms FPS: %3.1f" % (inference_ms, fps_ms) for result in results: annotate_text += "\n%.0f%% %s" % (100 * result[1], labels[result[0]]) print(annotate_text) finally: camera.stop()
def main(): #init game, camera, display pygame.init() leckerli_font = pygame.font.Font("fonts/LeckerliOne-Regular.ttf", 35) anon_font = pygame.font.Font('fonts/slkscr.ttf', 15) anon_font_bold= pygame.font.Font('fonts/slkscrb.ttf', 15) pygame.camera.init() infoObject = pygame.display.Info() #SIZE = (infoObject.current_w, infoObject.current_h) screen = pygame.display.set_mode(SIZE, 0)#FULLsurface) camera = pygame.camera.Camera(DEVICE, CAMERA_SIZE) camera.start() #initialize surfaces camera_surface = pygame.surface.Surface(CAMERA_SIZE, 0, screen) chat_surface = ChatSurface((400, SIZE[1]), leckerli_font, anon_font, anon_font_bold) print chat_surface.lines capture = True while capture: #get camera image camera_surface = camera.get_image(camera_surface) #draw the screen elements pygame.draw.rect(screen, DARK, [0, 0, SIZE[0], SIZE[1]]) #background color screen.blit(pygame.transform.scale(camera_surface, SIZE), (0,0)) #camera screen chat_surface.draw(screen) #flip the display buffers thus updating the surface pygame.display.flip() #handle events for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_q): capture = False elif event.type == KEYDOWN and event.key == K_s: pygame.image.save(camera_surface, FILENAME) #die chat_surface.stop() camera.stop() pygame.quit()
print("Imported pygame, numpy, opencv and cvEyeTracking lib") raw_input("Press Enter to capture an image (in pygame)") pygame.init() pygame.camera.init() size = width,height = 640,480 display = pygame.display.set_mode(size,0) camList = pygame.camera.list_cameras() # TODO: err if none found camera = pygame.camera.Camera(camList[0],size,"RGB") camera.start() for i in range(100): if camera.query_image(): # ready to take an image? break snapshot = camera.get_image() camera.stop() display.blit(snapshot,(0,0,)) pygame.display.flip() pygame.display.flip() print("Captured an image") raw_input("Press Enter to convert into opencv format") npy = surfarray.pixels3d(snapshot) ipl = adaptors.NumPy2Ipl(npy) print("Captured an image") raw_input("Press Enter to pass to cvEyeTrack to add a cross")
def stopCamera(self): global camera camera.stop()