Python pygame.camera() Examples

The following are 27 code examples of pygame.camera(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygame , or try the search function .
Example #1
Source File: camera.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def get_and_flip(self):
        # if you don't want to tie the framerate to the camera, you can check and
        # see if the camera has an image ready.  note that while this works
        # on most cameras, some will never return true.
        if 0 and self.camera.query_image():
            # capture an image

            self.snapshot = self.camera.get_image(self.snapshot)

        if 0:
            self.snapshot = self.camera.get_image(self.snapshot)
            #self.snapshot = self.camera.get_image()

            # blit it to the display surface.  simple!
            self.display.blit(self.snapshot, (0,0))
        else:
            self.snapshot = self.camera.get_image(self.display)
            #self.display.blit(self.snapshot, (0,0))


        pygame.display.flip() 
Example #2
Source File: camera.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def init_cams(self, which_cam_idx):

        # gets a list of available cameras.
        self.clist = pygame.camera.list_cameras()
        print (self.clist)

        if not self.clist:
            raise ValueError("Sorry, no cameras detected.")

        try:
            cam_id = self.clist[which_cam_idx]
        except IndexError:
            cam_id = self.clist[0]

        # creates the camera of the specified size and in RGB colorspace
        self.camera = pygame.camera.Camera(cam_id, self.size, "RGB")

        # starts the camera
        self.camera.start()

        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) 
Example #3
Source File: cameraInput.py    From crazyflieROS with GNU General Public License v2.0 6 votes vote down vote up
def start(self, device, maxSize=(1280,720)):
        #cam = self.getCam()
        if self.camTimer.isActive():
            self.stop()

        logger.info("Using camera: %s", device)

        # Open Camera
        self.cam = pygame.camera.Camera(device, maxSize)

        # Start Camera
        self.cam.start()

        # Get actual capture size
        self.size = self.cam.get_size()

        # Init surface buffer
        self.buffer = pygame.surface.Surface(self.size)
        logger.info("Detected size: %d*%d", self.size[0], self.size[1])

        # Start polling at 50hz
        self.setMaxFPS(fps=50)
        self.sigPlaying.emit(True) 
Example #4
Source File: camera.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def get_and_flip(self):
        # if you don't want to tie the framerate to the camera, you can check and
        # see if the camera has an image ready.  note that while this works
        # on most cameras, some will never return true.
        if 0 and self.camera.query_image():
            # capture an image

            self.snapshot = self.camera.get_image(self.snapshot)

        if 0:
            self.snapshot = self.camera.get_image(self.snapshot)
            #self.snapshot = self.camera.get_image()

            # blit it to the display surface.  simple!
            self.display.blit(self.snapshot, (0,0))
        else:
            self.snapshot = self.camera.get_image(self.display)
            #self.display.blit(self.snapshot, (0,0))


        pygame.display.flip() 
Example #5
Source File: camera.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def init_cams(self, which_cam_idx):

        # gets a list of available cameras.
        self.clist = pygame.camera.list_cameras()
        print (self.clist)

        if not self.clist:
            raise ValueError("Sorry, no cameras detected.")

        try:
            cam_id = self.clist[which_cam_idx]
        except IndexError:
            cam_id = self.clist[0]

        # creates the camera of the specified size and in RGB colorspace
        self.camera = pygame.camera.Camera(cam_id, self.size, "RGB")

        # starts the camera
        self.camera.start()

        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) 
Example #6
Source File: camera.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def get_and_flip(self):
        # if you don't want to tie the framerate to the camera, you can check and
        # see if the camera has an image ready.  note that while this works
        # on most cameras, some will never return true.
        if 0 and self.camera.query_image():
            # capture an image

            self.snapshot = self.camera.get_image(self.snapshot)

        if 0:
            self.snapshot = self.camera.get_image(self.snapshot)
            #self.snapshot = self.camera.get_image()

            # blit it to the display surface.  simple!
            self.display.blit(self.snapshot, (0,0))
        else:
            self.snapshot = self.camera.get_image(self.display)
            #self.display.blit(self.snapshot, (0,0))


        pygame.display.flip() 
Example #7
Source File: usb_camera_driver.py    From openag-device-software with GNU General Public License v3.0 6 votes vote down vote up
def capture(self, retry: bool = True) -> None:
        """Captures an image from a camera or set of non-unique cameras."""
        super().capture(retry=retry)

        # Capture images
        try:
            # with self.usb_camera_lock:
            self.enable_cameras(wait_for_enable=True, timeout=10)
            self.capture_images()
            self.disable_cameras(wait_for_disable=True, timeout=10)
        except DAC5578DriverError as e:
            raise exceptions.CaptureError(logger=self.logger) from e
        except Exception as e:
            message = "Unable to capture, unhandled exception: {}".format(type(e))
            self.logger.warning(message)
            raise exceptions.CaptureError(logger=self.logger) from e 
Example #8
Source File: camera.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def init_cams(self, which_cam_idx):

        # gets a list of available cameras.
        self.clist = pygame.camera.list_cameras()
        print (self.clist)

        if not self.clist:
            raise ValueError("Sorry, no cameras detected.")

        try:
            cam_id = self.clist[which_cam_idx]
        except IndexError:
            cam_id = self.clist[0]

        # creates the camera of the specified size and in RGB colorspace
        self.camera = pygame.camera.Camera(cam_id, self.size, "RGB")

        # starts the camera
        self.camera.start()

        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) 
Example #9
Source File: camera.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def get_and_flip(self):
        # if you don't want to tie the framerate to the camera, you can check and
        # see if the camera has an image ready.  note that while this works
        # on most cameras, some will never return true.
        if 0 and self.camera.query_image():
            # capture an image

            self.snapshot = self.camera.get_image(self.snapshot)

        if 0:
            self.snapshot = self.camera.get_image(self.snapshot)
            #self.snapshot = self.camera.get_image()

            # blit it to the display surface.  simple!
            self.display.blit(self.snapshot, (0,0))
        else:
            self.snapshot = self.camera.get_image(self.display)
            #self.display.blit(self.snapshot, (0,0))


        pygame.display.flip() 
Example #10
Source File: scannStart.py    From simple3dscanner with MIT License 6 votes vote down vote up
def oneSave(angleStep): #=angle
 global sMat, bb, fp 
 rr=0
 #x=startx #camera picture X
 y=sTop   #camera picture Y
 #---export xyz--- to filename.xyz 
 y=sTop+1   
 while y<height-sBott:       
    xx = sMat[y-sTop][angleStep]
    if xx!=0 and xx>-200:         
      angle=float(2*pi/(loop-1)*angleStep)
      rx=float(math.sin(angle)*xx*nasDef)
      ry=float(math.cos(angle)*xx*nasDef)
      rz = y
      co = str(rx)+" "+str(ry)+" "+str(rz)
      #cop = str(angle)+" > "+str(xx)+" > "+co
      #print cop
      fp.write(co+"\n") 
    y=y+kroky
 #time.sleep(0.2) 
Example #11
Source File: camera.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def init_cams(self, which_cam_idx):

        # gets a list of available cameras.
        self.clist = pygame.camera.list_cameras()
        print (self.clist)

        if not self.clist:
            raise ValueError("Sorry, no cameras detected.")

        try:
            cam_id = self.clist[which_cam_idx]
        except IndexError:
            cam_id = self.clist[0]

        # creates the camera of the specified size and in RGB colorspace
        self.camera = pygame.camera.Camera(cam_id, self.size, "RGB")

        # starts the camera
        self.camera.start()

        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) 
Example #12
Source File: camtracker.py    From webcam-eyetracker with GNU General Public License v3.0 6 votes vote down vote up
def available_devices():
	
	"""Returns a list of available device names or numbers; each name or
	number can be used to pass as Setup's device keyword argument
	
	arguments
	None
	
	keyword arguments
	None
	
	returns
	devlist		--	a list of device names or numbers, e.g.
					['/dev/video0','/dev/video1'] or [0,1]
	"""
	
	return pygame.camera.list_cameras()
	

# # # # #
# classes 
Example #13
Source File: camtracker.py    From webcam-eyetracker with GNU General Public License v3.0 6 votes vote down vote up
def close(self):
		
		"""Shuts down connection to the webcam and closes logfile
		
		arguments
		None
		
		keyword arguments
		None
		
		returns
		None
		"""
		
		# close camera
		self.cam.stop() 
Example #14
Source File: cameraInput.py    From crazyflieROS with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,parent=None):
        super(QtCore.QObject, self).__init__(parent)

        pygame.init() #Do we need this? Or is it done already elsewhere
        pygame.camera.init()

        self.cam = None
        self.buffer = None
        self.size = (1280, 720)


        # Get new image from camera at cam fps
        self.camTimer = QtCore.QTimer(self)
        self.camTimer.timeout.connect(self.emitNextFrame) 
Example #15
Source File: camera.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def main():
    pygame.init()
    pygame.camera.init()
    VideoCapturePlayer().main()
    pygame.quit() 
Example #16
Source File: camera.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def main():
    pygame.init()
    pygame.camera.init()
    VideoCapturePlayer().main()
    pygame.quit() 
Example #17
Source File: usb_camera_driver.py    From openag-device-software with GNU General Public License v3.0 5 votes vote down vote up
def capture_images(self) -> None:
        """Captures an image from each active camera."""
        self.logger.debug("Capturing images")

        # Get real or simulated camera paths
        if not self.simulate:
            camera_paths = usb.get_camera_paths(self.vendor_id, self.product_id)
        else:
            camera_paths = []
            for i in range(self.num_cameras):
                camera_paths.append("simulate_path")

        # Check correct number of camera paths
        num_detected = len(camera_paths)
        if num_detected != self.num_cameras:
            message = "Incorrect number of cameras detected, expected {}, detected {}".format(
                self.num_cameras, num_detected
            )
            message += ". Proceeding with capture anyway"
            self.logger.warning(message)

        # Capture an image from each active camera
        for index, camera_path in enumerate(camera_paths):

            # Get timestring in ISO8601 format
            timestring = datetime.datetime.utcnow().strftime("%Y-%m-%d-T%H:%M:%SZ")

            # Get filename for individual camera or camera instance in set
            if self.num_cameras == 1:
                filename = "{}_{}.png".format(timestring, self.name)
            else:
                filename = "{}_{}.{}.png".format(timestring, self.name, index + 1)

            # Create image path
            capture_image_path = self.capture_dir + filename
            final_image_path = self.directory + filename

            # Capture image
            self.capture_image_pygame(camera_path, capture_image_path)
            shutil.move(capture_image_path, final_image_path) 
Example #18
Source File: webcam.py    From botnet-lab with MIT License 5 votes vote down vote up
def webcam():
    client_id = "2ed32bb280dd0b8"
    pygame.camera.init()
    # pygame.camera.list_camera() #Camera detected or not
    try:
        if os.name == "nt":
            cam = pygame.camera.Camera(0, (640, 480))
        else:
            cam = pygame.camera.Camera("/dev/video0", (640, 480))
        cam.start()
    except:
        return "error finding a camera"

    img = cam.get_image()
    pygame.image.save(img, "im.png")

    headers = {"Authorization": "Client-ID 2ed32bb280dd0b8"}
    api_key = 'eb215a75b4e3b0e3604c42b98f3ab7b41656ddfb'
    url = "https://api.imgur.com/3/upload.json"
    j1 = requests.post(
        url,
        headers=headers,
        data={
            'key': api_key,
            'image': b64encode(open('im.png', 'rb').read()),
            'type': 'base64',
            'name': 'im.png',
            'title': 'screen'
        }, verify=False
    )
    os.remove('im.png')
    return json.loads(j1.text)["data"]["link"] 
Example #19
Source File: cameraInput.py    From crazyflieROS with GNU General Public License v2.0 5 votes vote down vote up
def setMaxFPS(self, fps=50):
        """ Sets the camera polling rate. How fast images are emitted ultimately depends on the camera."""
        self.camTimer.start(1000/50) 
Example #20
Source File: cameraInput.py    From crazyflieROS with GNU General Public License v2.0 5 votes vote down vote up
def stop(self):
        """Start running and polling the camera"""
        # Stop polling camera
        self.camTimer.stop()

        # Turn off camera
        if self.cam is not None:
            self.cam.stop()
            self.sigPlaying.emit(False) 
Example #21
Source File: cameraInput.py    From crazyflieROS with GNU General Public License v2.0 5 votes vote down vote up
def getDevices(self):
        return pygame.camera.list_cameras() 
Example #22
Source File: camtracker.py    From webcam-eyetracker with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, device=None, camres=(640,480)):
		
		"""Initializes a CamEyeTracker instance
		
		arguments
		None
		
		keyword arguments
		device		--	a string or an integer, indicating either
						device name (e.g. '/dev/video0'), or a
						device number (e.g. 0); None can be passed
						too, in this case Setup will autodetect a
						useable device (default = None)
		camres		--	the resolution of the webcam, e.g.
						(640,480) (default = (640,480))
		"""

		global vcAvailable
		if vcAvailable == False:
			# select a device if none was selected
			if device == None:
				available = available_devices()
				if available == []:
					raise Exception("Error in camtracker.CamEyeTracker.__init__: no available camera devices found (did you forget to plug it in?)")
				else:
					device = available[0]
			
			# start the webcam
			self.cam = pygame.camera.Camera(device, camres, 'RGB')
			self.cam.start()
		else:
			self.cam = VideoCapture.Device()
			
		# get the webcam resolution (get_size not available on all systems)
		try:
			self.camres = self.cam.get_size()
		except:
			self.camres = camres

		# default settings
		self.settings = {'pupilcol':(0,0,0), \
					'threshold':100, \
					'nonthresholdcol':(100,100,255,255), \
					'pupilpos':(-1,-1), \
					'pupilrect':pygame.Rect(self.camres[0]/2-50,self.camres[1]/2-25,100,50), \
					'pupilbounds': [0,0,0,0], \
					'':None					
					} 
Example #23
Source File: classify_capture.py    From examples-camera with Apache License 2.0 4 votes vote down vote up
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() 
Example #24
Source File: usb_camera_driver.py    From openag-device-software with GNU General Public License v3.0 4 votes vote down vote up
def disable_cameras(
        self, wait_for_disable: bool = False, timeout: float = 5, retry: bool = True
    ) -> None:
        """Disables camera by setting dac output low."""
        self.logger.debug("Disabling cameras")

        # Check if using usb mux
        if not self.usb_mux_enabled:
            self.logger.debug("Cameras always enabled, not using mux")
            return

        # Turn off usb mux channel
        try:
            channel = self.usb_mux_channel
            self.dac5578.set_low(channel=channel, retry=retry)
        except DAC5578DriverError as e:
            raise exceptions.DisableCameraError(logger=self.logger) from e

        # Check if waiting for disable
        if not wait_for_disable:
            return

        # Wait for camera to be disabled
        self.logger.debug("Waiting for cameras to become disabled")

        # Check if simulated
        if self.simulate:
            self.logger.debug("Simulated camera disable complete")
            return

        # Initialize timing variables
        start_time = time.time()

        # Loop forever
        while True:

            # Look for camera
            try:
                camera_paths = usb.get_camera_paths(self.vendor_id, self.product_id)

                # Check if all cameras are disables
                if camera_paths == []:
                    self.logger.debug("All cameras disabled")
                    return

            except Exception as e:
                raise exceptions.DisableCameraError(logger=self.logger) from e

            # Check for timeout
            if time.time() - start_time > timeout:
                message = "timed out"
                raise exceptions.DisableCameraError(message=message, logger=self.logger)

            # Update every 100ms
            time.sleep(0.1) 
Example #25
Source File: usb_camera_driver.py    From openag-device-software with GNU General Public License v3.0 4 votes vote down vote up
def enable_cameras(
        self, wait_for_enable: bool = False, timeout: float = 5, retry: bool = True
    ) -> None:
        """Enables camera by setting dac output high."""
        self.logger.debug("Enabling cameras")

        # Check if using usb mux
        if not self.usb_mux_enabled:
            self.logger.debug("Cameras always enabled, not using mux")
            return

        # Turn on usb mux channel
        try:
            channel = self.usb_mux_channel
            self.dac5578.set_high(channel=channel, retry=retry)
        except DAC5578DriverError as e:
            raise exceptions.EnableCameraError(logger=self.logger) from e

        # Check if waiting for enable
        if not wait_for_enable:
            return

        # Wait for camera to be enabled
        self.logger.debug("Waiting for cameras to become enabled")

        # Check if simulated
        if self.simulate:
            self.logger.debug("Simulated camera enable complete")
            return

        # Initialize timing variables
        start_time = time.time()

        # Loop forever
        while True:

            # Look for camera
            try:
                camera_paths = usb.get_camera_paths(self.vendor_id, self.product_id)

                # Check if camera powered down
                if len(camera_paths) == self.num_cameras:
                    self.logger.debug("All cameras enabled")
                    return

            except Exception as e:
                raise exceptions.DisableCameraError(logger=self.logger) from e

            # Check for timeout
            if time.time() - start_time > timeout:
                message = "timed out"
                raise exceptions.EnableCameraError(message=message, logger=self.logger)

            # Update every 100ms
            time.sleep(0.1) 
Example #26
Source File: usb_camera_driver.py    From openag-device-software with GNU General Public License v3.0 4 votes vote down vote up
def __init__(
            self,
            name: str,
            vendor_id: int,
            product_id: int,
            resolution: str,
            num_cameras: int = 1,
            simulate: bool = False,
            usb_mux_comms: Optional[Dict[str, Any]] = None,
            usb_mux_channel: Optional[int] = None,
            i2c_lock: Optional[threading.RLock] = None,
            mux_simulator: Optional[MuxSimulator] = None
    ) -> None:
        # pygame only supports Linux.  If not running Linux, then simulate.
        if PLATFORM is not None and PLATFORM != "osx-machine" and PLATFORM != "unknown":
            # Initialize pygame
            pygame.init()
            pygame.camera.init()
            self.simulate = simulate
            pygame_loaded = True
        else:
            self.simulate = True
            pygame_loaded = False

        super().__init__(name=name,
                         vendor_id=vendor_id,
                         product_id=product_id,
                         resolution=resolution,
                         num_cameras=num_cameras,
                         simulate=self.simulate,
                         usb_mux_comms=usb_mux_comms,
                         usb_mux_channel=usb_mux_channel,
                         i2c_lock=i2c_lock,
                         mux_simulator=mux_simulator)

        # USB camera specific setup
        # pygame only supports Linux.  If not running Linux, then simulate.
        if not pygame_loaded:
            self.logger.info(
                "Not running on Linux OS, so pygame is not supported.  Turning on simulation mode."
            )

        # Using usb mux, initialize driver
        if not self.simulate and self.usb_mux_enabled:
            try:
                self.dac5578 = DAC5578Driver(
                    name=name,
                    i2c_lock=i2c_lock,  # type: ignore
                    bus=self.bus,
                    mux=self.mux,
                    channel=self.channel,
                    address=self.address,
                    simulate=self.simulate,
                    mux_simulator=mux_simulator,
                )
                self.usb_mux_channel = usb_mux_channel
            except I2CError as e:
                raise exceptions.InitError(logger=self.logger) from e 
Example #27
Source File: gui.py    From openag_brain_box with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self):
        try:
            pygame.init()
            pygame.camera.init()
            pygame.mouse.set_visible(False)
            self.screen = pygame.display.set_mode((800,480),pygame.NOFRAME)
            self.cam_list = pygame.camera.list_cameras()
            self.webcam = pygame.camera.Camera(self.cam_list[0],(32,24))
            self.webcam.start()
            logger.info('Initialized pygame display')
        except:
            logger.warning('Unable to initialize pygame display')
        try:
            self.shared = memcache.Client(['127.0.0.1:11211'], debug=0)
            logger.info('Initialized memcache client')
        except:
            logger.warning('Unable to initialize memcache client')

        self.canny = False
        self.ph = '6.5'
        self.ec = '3.2'
        self.water_temp = '20.1'
        self.air_temp = '21.1'
        self.humidity = '38'
        self.co2 = '410'
        self.o2 = '17.1'
        # self.figure = matplotlib.pyplot.figure()
        # self.plot = self.figure.add_subplot(111)
        # self.runSeabornEx()