def __init__(self, logger, queue, parent_queue): threading.Thread.__init__(self) self.logger = logger self.queue = queue self.parent_queue = parent_queue self.logger.debug("Video created") self.text = "Welcome to Smash Putt" # Setup screen pygame.init() pygame.mouse.set_visible(False) self.width = 1024 self.height = 768 self.screen = pygame.display.set_mode((self.width, self.height)) font_size = 60 font_width = font_size * 0.68956 font_width = font_size * 0.7 self.font = pygame.font.SysFont("Droid Sans Mono", font_size, bold=1) self.line_length = self.width / font_width camera.init() camera_size = (640, 480) self.c = camera.Camera('/dev/video0', camera_size) self.c.start() self.surface = pygame.Surface(camera_size) self.bigSurface = None self.pause = False self.foregroundColor = pygame.Color(255, 0, 0) self.black = pygame.Color(0, 0, 0) self.shadowShade = 0
def setup(self): cameras = camera.list_cameras() if CAMERA_INDEX >= len(cameras): raise Exception('Error: no camera') self._cam = camera.Camera(cameras[CAMERA_INDEX], (CAMERA_WIDTH, CAMERA_HEIGHT)) self._cam.start()
def getImage(): cam.init() k = cam.Camera(cam.list_cameras()[0]) k.start() img = k.get_image() sejv(img, "tabla.jpg") k.stop()
def __init__(self, num=0, size=(640, 640)): super().__init__(num, size) camera.init() cam = None while cam is None: cam = camera.Camera(camera.list_cameras()[num], size) # cam.set_resolution(*size) self.cam = cam
def __init__(self, save_directory,nb_photos,isReverse,duration,timer): camera.init() self.cam = camera.Camera("/dev/video0",(320,200)) self.images_cam=[] self.save_directory=save_directory self.nb_photos=nb_photos self.isReverse=isReverse self.duration=duration self.timer=timer
def __init__(self, processFunction=None, display=None, photos=None, version=None, **argd): logging.debug("Initializing Video Capture Class") #set display size in pixels = width,height displaySize = 752, 600 size = 640, 480 processRuns = 0 self.__dict__.update(argd) self.__dict__.update(locals()) #super(VideoCapturePlayer, self).__init__(**argd) if self.display is None: pygame.display.init() pygame.display.set_caption(u"Open Allure " + version) self.display = pygame.display.set_mode(self.displaySize, 0) #bring in photos self.photoSmile = pygame.image.load(photos[0]).convert() self.photoTalk = pygame.image.load(photos[1]).convert() self.photoListen = pygame.image.load(photos[2]).convert() import pygame.camera as camera camera.init() # get a list of available cameras. if sys.platform == 'darwin': self.cameraList = ['0'] # camera.list_cameras() else: self.cameraList = camera.list_cameras() if not self.cameraList: raise ValueError("Sorry, no cameras detected.") logging.info("Opening device %s, with video size (%s,%s)" % (self.cameraList[0], self.size[0], self.size[1])) # create and start the camera of the specified size in RGB colorspace self.camera = camera.Camera(self.cameraList[0], self.size, "RGB") self.camera.start() self.processClock = self.clock = pygame.time.Clock() # create a surface to capture to. for performance purposes, you want the # bit depth to be the same as that of the display surface. self.snapshot = pygame.surface.Surface(self.size, 0, self.display) # place holders for thumbnails self.snapshotThumbnail = None self.processedShotThumbnail = None
def main(): parser = argparse.ArgumentParser(description="Time to D-D-D-Duel.") parser.add_argument("saveDir", help="Directory to save photos to.") parser.add_argument("--prefix", default="ygh-photo", help="File prefix for each numbered photo.") parser.add_argument("--psm", type=int, default=6, help="psm argument for tesseract tool.") args = parser.parse_args() prefix = args.prefix save_dir = args.saveDir psm = args.psm if not os.path.exists(save_dir): os.mkdir("./%s" % save_dir) # setup camera try: pc.init() print("Cameras -> ") print(pc.list_cameras()) webcam = pc.Camera(pc.list_cameras()[0]) webcam.start() except Exception as e: print("Error encountered when setting up webcam, check it's not already in use.") print(e) raise SystemExit i = webcam.get_image() pi.save(i, "./photo.png") # let user select when to take each photo, number them consecutively. count = 0 while True: input() img = webcam.get_image() file_path = "%s/%s%d.png" % (save_dir, prefix, count) pi.save(img, file_path) print("---> Processing image %s" % file_path) try: processed_fp = "%s/processed-%s%d.png" % (save_dir, prefix, count) preprocess_image(file_path, processed_fp) # Define config parameters. # '-l eng' for using the English language # '--oem 1' for using LSTM OCR Engine # psm 6 = words as a text line? config = ("-l eng --oem 1 --psm %d" % psm) text = pytesseract.image_to_string( Image.open(file_path), config=config) print("-----text found-------") print(text) print("----------------------") except UnicodeEncodeError: print("[!] had an issue encoding to Unicode.") count += 1 pc.quit()
def capturar(self): try: webcam = camera.Camera(self.miWebcam,(640,480)) webcam.start() self.captura = webcam.get_image() webcam.stop() except Exception as e: print e
def __init__(self, device, width, height, color='RGB'): '''Intialize device ''' camera.init() if not device: device = camera.list_cameras()[0] self._cam = camera.Camera(device, (width, height), color) self._cam.start() self.running = True self.img = None Thread.__init__(self)
def __init__(self, display): pgcam.init() self.clist = pgcam.list_cameras() print(self.clist) if not self.clist: raise ValueError("sorry no camera detected") self.camera = pgcam.Camera(self.clist[0], (640, 480)) self.screen = pg.surface.Surface((640, 480), 0, display) self.camera.start() print("camera set")
def __init__(self, display): pgcam.init() self.clist = pgcam.list_cameras() print(self.clist) if not self.clist: raise ValueError("sorry no camera detected") self.width = 960 self.height = 720 self.camera = pgcam.Camera(self.clist[0], (self.width, self.height)) self.screen = pg.surface.Surface((self.width, self.height), 0, display) self.camera.start() print("camera set")
def __init__(self, is_laptop_cam, device, crop_start, crop_size): self.crop_start = crop_start self.crop_size = crop_size self.device = device self.is_laptop_cam = is_laptop_cam if is_laptop_cam: # use pygame try: pc.init() self.camera = pc.Camera(device) self.camera.start() except Exception as e: raise ValueError("Unable to setup pygame %s" % e)
def __init__(self, cfg): super().__init__(inputs=[], outputs=[ 'cam/img', ], threaded=True) self.img_w = cfg['img_w'] self.img_h = cfg['img_h'] self.image_format = cfg['image_format'] pygame.init() camera.init() cameras = camera.list_cameras() print("Using camera %s ..." % cameras[cfg['cam_source']]) self.webcam = camera.Camera(cameras[cfg['cam_source']], cfg['cam_resolution']) self.processed_frame = None self.on = True
def __init__(self): self.size = (640, 480) # create a display surface. standard pygame stuff self.display = pg.display.set_mode(self.size, 0) # this is the same as what we saw before self.clist = pgcam.list_cameras() if not self.clist: raise ValueError("Sorry, no cameras detected.") self.cam = pgcam.Camera(self.clist[0], self.size) self.cam.start() # create a surface to capture to. for performance purposes # bit depth is the same as that of the display surface. self.snapshot = pg.surface.Surface(self.size, 0, self.display)
def take_picture(given_name='test'): camera.init() list_of_cameras = camera.list_cameras() print("Found {} cameras!".format(len(list_of_cameras))) if len(list_of_cameras): my_camera = camera.Camera(list_of_cameras[0]) print("Successfully connected to the camera!") my_camera.start() surface = my_camera.get_image() print(surface) pyimage.save(surface, '{}.bmp'.format(given_name)) my_camera.stop()
def __init__(self): self.size = self.x, self.y = 800, 600 self.screen = display.set_mode(self.size) display.set_caption('Camera Simulation') self.screen.fill((0, 0, 0)) self.bg_img = image.load('space_(3840x2160).jpg') self.camera_x = 30 self.camera_y = 30 self.player_x = 40 self.player_y = 40 self.camera = camera.Camera()
def main(): camera.init() print('scaning cameras...') while 'inf': for camera_path in camera.list_cameras(): # camera_path : /dev/video0 cmr = camera.Camera(camera_path) try: cmr.start() cmr.stop() except: print('** Alert ** : (camera {} is opend)'.format(camera_path)) Thread(target=alert).start() sleep(1) sleep(1) camera.quit()
def main(): print("Loading calibration matrix....") with np.load('calib_camera.npz') as fp: mtx, dist = [fp[i] for i in ('mtx', 'dist')] pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption('Calibration') ubuntu = pygame.font.match_font('Ubuntu') font = pygame.font.Font(ubuntu, 20) font.set_bold(True) camera.init() c = camera.Camera(camera.list_cameras()[0], size) c.start() finish = False clock = pygame.time.Clock() while not finish: surf = c.get_image() img = pygame.surfarray.pixels3d(surf) img = pygame.surfarray.pixels3d(surf) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) ret, corners = cv2.findChessboardCorners(gray, (6, 6), None) img_gray = np.dstack([gray, gray, gray]) if ret: corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria) _, rvecs, tvecs = cv2.solvePnP(objp, corners2, mtx, dist) # print(rvecs.shape) imgpts, jac = cv2.projectPoints(axis, rvecs, tvecs, mtx, dist) img_gray = draw(img_gray, corners2, imgpts) gray_surf = pygame.surfarray.make_surface(img_gray) screen.blit(gray_surf, (0, 0)) clock.tick(FPS) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: finish = True c.stop()
def initCam(_camera='/dev/video0', _res=(640, 480)): '''Wants the name of the wanted camera device. Returns the device object and the resolution (w,h)''' camera.init() cam = camera.Camera(_camera, _res) if cam is None: raise Exception( 'Cannot connect to camera. Maybe in use by other program?') try: cam.start() except: raise Exception( 'Cannot connect to camera. Maybe in use by other program?') return cam
def __init__(self, input_signal, output_channel, device=0, max_freq=10, size=(WIDTH, HEIGHT), grey=True): """ Constructor for a VideoSnapshot source. @param input_signal: A channel that will pass a message when an output is desired. @param output_channel: The channel that will be passed a tagged image signal. @param device: The camera device to connect to - (0 is default) @param max_freq: We won't bother polling faster than this max frequency. @param size: A tuple containing the width and height to use for the camera device. @param grey: A boolean indicating if the image should be averaged to one channel Example useage: >>> msg = Event(tag = 1, value = go) >>> in_channel, out_channel = Channel(), Channel() >>> vid_src = VideoSnapshot(in_channel, out_channel) >>> in_channel.put(msg) >>> in_channel.put(LastEvent()) # Tells the component we are finished >>> vid_src.start() # Start the thread, it will process its input channel >>> vid_src.join() >>> img1 = out_channel.get() >>> assert out_channel.get().last == True """ super(VideoSnapshot, self).__init__(input_signal, output_channel) self.MAX_FREQUENCY = max_freq self.device = device self.size = size self.grey = grey self.snapshot = None # This is where we will save our pygame surface image logging.debug("Initialising Video Capture") camera.init() # gets a list of available cameras. self.clist = camera.list_cameras() if not self.clist: raise IOError("Sorry, no cameras detected.") logging.info("Opening device %s, with video size (%s,%s)" % (self.clist[0], self.size[0], self.size[1])) self.camera = camera.Camera(self.clist[0], self.size, "RGB")
def __init__(self, display): self.display = display camera.init() self.clist = camera.list_cameras() if not self.clist: self.is_enabled = False # raise ValueError("Nessuna WebCam trovata! :[") else: self.device = camera.Camera(self.clist[0], CAMERA_SIZE) try: self.device.start() self.is_enabled = True self.surface = py.surface.Surface(self.device.get_size(), 0, display) except: self.is_enabled = False print("Errore nell'avvio della Webcam >:[") self.surface = None
def open(self): # TODO: make async from pygame import camera camera.init() cameras = camera.list_cameras() dc = camera.Camera(cameras[self._device_index], self.default_resolution, 'RGB') dc.start() time.sleep(1) # give time for webcam to init. # 'prime' the capture context... # some webcams might not init fully until a capture # is done. so we do a capture here to force device to be ready # and query the maximum supported size self._temp_surface = dc.get_image() self._device_context = dc
def __init__(self, logger, queue, parent_queue): threading.Thread.__init__(self) self.logger = logger self.logger.debug("Creating video...") self.queue = queue self.parent_queue = parent_queue self.is_slide = False self.slide = None self.text = "Welcome!" # Setup screen pygame.init() self.clock = time.Clock() pygame.mouse.set_visible(False) self.width = settings.SCREEN_WIDTH self.height = settings.SCREEN_HEIGHT flags = 0 #pygame.DOUBLEBUF | pygame.HWSURFACE | pygame.FULLSCREEN self.screen = pygame.display.set_mode((self.width, self.height), flags) font_size = settings.FONT_SIZE self.font = pygame.font.SysFont(settings.FONT, font_size, bold=1) if settings.CAMERA: camera.init() camera_size = (640, 480) self.c = camera.Camera('/dev/video0', camera_size) self.c.start() self.surface = pygame.Surface(camera_size) self.bigSurface = None self.alert = False self.foregroundColor = pygame.Color(settings.FONT_COLOR) self.backgroundColor = pygame.Color(settings.BACKGROUND_COLOR) self.black = pygame.Color(0, 0, 0, 100) self.shadowShade = 0 self.background_image = None if settings.BACKGROUND_IMAGE: self.background_image = pygame.image.load( settings.BACKGROUND_IMAGE) self.logger.debug("Video created")
def __init__(self, context, report_to: Queue, screen_config: gui.ScreenConfig): self.tasks = Queue() self.report_to = report_to self.context = context self.screen_config = screen_config self.camera = camera.Camera(camera.list_cameras()[0], (640, 480)) if screen_config.FULLSCREEN: self.screen = pygame.display.set_mode( (screen_config.WIDTH, screen_config.HEIGHT), pygame.FULLSCREEN) else: self.screen = pygame.display.set_mode( (screen_config.WIDTH, screen_config.HEIGHT), ) self.current_menu = self.MAIN_MENU = gui.main_menu.MainMenu( context=self) self.TOP_UP_MENU = gui.top_up_menu.TopUpMenu(context=self) self.BUY_TICKET_MENU = gui.buy_ticket_menu.BuyTicketMenu(context=self) self.USE_RETURN_TICKET_MENU = gui.use_return_ticket_menu.UseReturnTicketMenu( context=self) super(FrontendController, self).__init__(target=self.handler)
def initVideo(self, cameraIndex=0): # # gets a list of available cameras. # self.cameras = pgCam.list_cameras() print('cameras= ', self.cameras) if self.cameras == []: raise ValueError("歹勢,無 攝影機。Sorry, no cameras detected. ") try: cameraId = self.cameras[cameraIndex] except IndexError: cameraId = self.cameras[0] # # creates the camera of the specified screenSize and in RGB, or HSV colorspace # self.camera = pgCam.Camera(cameraId, self.screenSize, 'HSV') #"RGB") # # starts the camera # # 這行與我們取音訊的精神很相像,應該就是 多線 的做法。 # (We take this line with the spirit of the audio is very similar, it should be is a multi-line approach.) # self.camera.start() # # create a surface 作為 videoShot to capture to. # for performance purposes, # you want the bit depth to be the same # as that of the display surface. # self.videoShot = pg.surface.Surface(self.screenSize, 0, self.screen)
def 啟動視訊(它, 攝影機編號=0): # # gets a list of available cameras. # 它.攝影機群 = pgCam.list_cameras() print('攝影機群= ', 它.攝影機群) if 它.攝影機群 == []: raise ValueError("歹勢,無 攝影機。Sorry, no cameras detected. ") try: 攝影機id = 它.攝影機群[攝影機編號] except IndexError: 攝影機id = 它.攝影機群[0] # # creates the camera of the specified 幕寬高 and in RGB, or HSV colorspace # 它.攝影機 = pgCam.Camera(攝影機id, 它.幕寬高, 'HSV') #"RGB") # # starts the camera # # 這行與我們取音訊的精神很相像,應該就是 多線 的做法。 # # 它.攝影機.start() # # create a surface 作為 攝影畫面 to capture to. # for performance purposes, # you want the bit depth to be the same # as that of the display surface. # 它.攝影畫面 = pg.surface.Surface(它.幕寬高, 0, 它.幕)
def main(): pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption('Extracción de colores') camera.init() c = camera.Camera(camera.list_cameras()[0], size) c.start() finish = False clock = pygame.time.Clock() while not finish: surf = c.get_image() img = pygame.surfarray.pixels3d(surf) hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) surf = pygame.surfarray.make_surface(hsv) screen.blit(surf, (0, 0)) pygame.display.update() clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: finish = True c.stop()
def run(self): #size = (1200,900) pygame.init() pygame.camera.init() #camera.init() self.radio1 = 2 self.radio2 = 12 screen = pygame.display.get_surface() screen.fill((0, 0, 0)) pygame.display.flip() x_s, y_s = (1200, 900) x_s, y_s = screen.get_size() clock = pygame.time.Clock() cam = camera.Camera("/dev/video0", (640, 480), "RGB") cam.set_controls(True, False) cam.start() cap = pygame.surface.Surface((640, 480), 0, screen) frames = 0 running = True while running: cap = cam.get_image(cap) rect = [] for z in range(max(20, int(frames) * 10)): x = random.random() y = random.random() if self.radio1 > self.radio2: aux = self.radio2 self.radio2 = self.radio1 self.radio1 = aux elif self.radio1 == self.radio2: self.radio2 = self.radio2 + 1 num = random.randrange(self.radio1, self.radio2, 1) rect.append( pygame.draw.circle( screen, cap.get_at((int(x * 640), int(y * 480))), (int(x * x_s), int(y * y_s)), num, 0)) pygame.display.update(rect) clock.tick() frames = clock.get_fps() #GTK events while gtk.events_pending(): gtk.main_iteration() events = pygame.event.get() for event in events: #log.debug( "Event: %s", event ) if event.type == pygame.QUIT: cam.stop() running = False elif event.type == pygame.VIDEORESIZE: pygame.display.set_mode(event.size, pygame.RESIZABLE) elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: cam.stop() running = False elif event.key == pygame.K_s: self.parent.save_image(screen) elif event.type == pygame.USEREVENT: if hasattr(event, 'action'): if event.action == 'savebutton': self.parent.save_image(screen)
def readyCamera(): cam.init() kamera = cam.Camera(cam.list_cameras()[1]) return kamera
import pygame import pygame.camera as pycam from pygame.locals import * PATH = "/dev/video0" RES = (1024, 768) FNAME = "xD.png" pygame.init() pycam.init() cam = pycam.Camera(PATH, RES) cam.start() image = cam.get_image() pygame.image.save(image, FNAME)