Exemple #1
0
 def saveSnapshot(self):
     webcam_source = self.webcam_source
     if os.path.isdir(webcam_source):
         logger.debug('%s webcam choosing random image from "%s"' %
                      (self, webcam_source))
         from random import choice
         webcam_source = os.path.join(webcam_source,
                                      choice(os.listdir(webcam_source)))
     print webcam_source
     if is_file_image(webcam_source):
         logger.debug('Webcam %s returning mock image file "%s"' %
                      (self, webcam_source))
         return webcam_source
     snapshot_file = self.snapshot_file
     if not snapshot_file:
         snapshot_file = _get_tmp_filename()
         logger.debug('Using temporary file "%s"' % (snapshot_file))
     if WIN:
         try:
             cam = Device(int(self.webcam_source))
             cam.saveSnapshot(snapshot_file)
             time.sleep(1.0)
             cam.saveSnapshot(snapshot_file)
         except Exception:
             return ''
     elif LINUX:
         callargs = [self.webcam_source, '-v', 'v4l2src', '!',
                     'decodebin', '!', 'ffmpegcolorspace', '!', 'pngenc',
                     '!', 'filesink', 'location="%s"' % (snapshot_file)]
         if 0 != subprocess.call(callargs):
             return ''
     return snapshot_file
Exemple #2
0
def take_picture():
    # Start camera device
    cam = Device()

    # Some machines take longer to initialize the camera and so
    # black images can occur if the module is loaded too quickly.
    # We will keep taking images until the image is not completely
    # black.
    while True:
        img = cam.getImage()
        if not is_black(img):
            break

    # Get a quick image count in the directory
    image_count = len(
        [fi for fi in os.listdir(SNAPSHOT_DIR) if re.search('.jpg$', fi)])
    if not image_count:
        location = '\\'.join([SNAPSHOT_DIR, 'lolock']) + '.jpg'
    else:
        location = '\\'.join([SNAPSHOT_DIR, 'lolock.' + str(image_count + 1)
                              ]) + '.jpg'

    # Save image to disk
    img.save(location)

    # Unload device
    del (cam)

    # Send email if enabled
    if SEND_MAIL:
        send_email(location)
Exemple #3
0
 def capImage(self, name, resolution=(1280, 720)):
     logger.info("capture picture to %s", name)
     cam = Device()
     logger.debug("start camera")
     cam.setResolution(*resolution)
     cam.saveSnapshot(name)
     logger.debug("capture picture")
Exemple #4
0
def getImage():
    if testImg == False:
        cam = Device()
        img = cam.getImage()
        img = array(img)
    else:
        img = cv2.imread('16.jpg',0)
        img = rotateImage(img, 270)
        # img = Image.open(str(testImg) + '.jpg')
        # img = img.rotate(270)

    # img = PIL.ImageOps.fit(img, (1500,3000))
    # img = PIL.ImageOps.solarize(img,128)
    # img = PIL.ImageOps.autocontrast(img)
    # img = PIL.ImageOps.grayscale(img)
    # img = PILa2rray(img)
    # img = cv2.medianBlur(img,5)
    # img = img.mean(img, -1)
    img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \
            cv2.THRESH_BINARY, 11, 3)

    if debugImage == True:
        pyplot.imshow(img)
        pyplot.show()

    return img
Exemple #5
0
 def options(self, device_name=None, device_number=None):
     # I doubt people will have more than 5 webcams plugged in
     self.logger.debug(
         'options() called with device_name %s and device_number %s' %
         (device_name, device_number))
     opts = []
     for i in range(2):
         try:
             self.logger.debug('options - attempting to connect to %s' % i)
             d = Device(devnum=i)
             if device_name is not None and device_name == d.getDisplayName(
             ):
                 del self.device
                 self.device = d
             elif device_number is not None and device_number == i:
                 del self.device
                 self.device = d
             opts.append((i, d.getDisplayName()))
             del d
         except:
             self.logger.exception("Exception while setting webcam options")
             pass
     self.logger.debug('options() returning %s' % opts)
     if self.connected():
         self.logger.debug('options - managed to connect to a device!')
     return opts
Exemple #6
0
def take_picture():
	# Start camera device
	cam = Device()

	# Some machines take longer to initialize the camera and so 
	# black images can occur if the module is loaded too quickly. 
	# We will keep taking images until the image is not completely
	# black.
	while True:
		img = cam.getImage()
		if not is_black(img):
			break
		
	# Get a quick image count in the directory
	image_count = len([fi for fi in os.listdir(SNAPSHOT_DIR) if re.search('.jpg$',fi)])
	if not image_count:
		location = '\\'.join([SNAPSHOT_DIR,'lolock']) + '.jpg'
	else:
		location = '\\'.join([SNAPSHOT_DIR,'lolock.'+str(image_count+1)]) + '.jpg'

	# Save image to disk
	img.save(location)

	# Unload device
	del(cam)

	# Send email if enabled
	if SEND_MAIL:
		send_email(location)
Exemple #7
0
 def __init__(self):  #not using video recorder as of now
     self._cam = Device()
     self._detectedImages = []
     self._currentImage = Image.open("VSAS logo.jpg")
     self._recording = False
     self._videoRecorder = self.newRecorder()
     self._recorded = False
Exemple #8
0
class PyCamera:
    def __init__(self, device_num=0):
        self.cam = Device(device_num)
        self.resolution = self.cam.getBuffer()[1:3]

    @property
    def get(self):
        '''
        return: {'buffer':**,'pixels':**,'pg_surface':**,'resolution':**}
        '''
        # 推荐使用getImage,getImage能显著提高图像质量,并且自动完成图像的翻转等操作
        # buffer,width,height = self.cam.getBuffer()

        image = self.cam.getImage()
        buffer = image.tostring()
        sur = pygame.image.frombuffer(buffer, self.resolution, 'RGB')
        pixels = np.fromstring(buffer, dtype=np.uint8)
        return {
            'buffer': buffer,
            'pixels': pixels,
            'pg_surface': sur,
            'resolution': self.resolution
        }

    def save_to_disk(self, filename):
        self.cam.saveSnapshot(filename)
Exemple #9
0
class CameraVideoCapture(CameraBase):
    '''Implementation of CameraBase using VideoCapture
    '''
    def __init__(self, **kwargs):
        self._device = None
        super(CameraVideoCapture, self).__init__(**kwargs)
        self._format = 'rgb'

    def init_camera(self):
        # create the device
        self._device = Device(devnum=self._index, showVideoWindow=0)
        # set resolution
        try:
            self._device.setResolution(self.resolution[0], self.resolution[1])
        except:
            raise Exception('VideoCapture: Resolution not supported')

    def _update(self, dt):
        data, camera_width, camera_height = self._device.getBuffer()
        if self._texture is None:
            # first update, resize if necessary
            self.size = camera_width, camera_height
            # and create texture
            self._texture = kivy.Texture.create(size=self.size, colorfmt='bgr')
            self.dispatch('on_load')

        # update buffer
        self._buffer = data
        self._copy_to_gpu()
    def __init__(self, root):
        self.root=root
        self.root.wm_title("Video Chatting: Coded by Rogue")
        self.root.protocol('WM_DELETE_WINDOW', self.safeExit)

        self.sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        self.cam=Device()
        self.photo=ImageTk.PhotoImage(self.cam.getImage())

        p = pyaudio.PyAudio()
        self.audStream = p.open(format = self.FORMAT,
                        channels = self.CHANNELS,
                        rate = self.RATE,
                        input = True,
                        output = True,
                        frames_per_buffer = self.chunk)
        self.design()
        t1=threading.Thread(target=self.sndData)
        t2=threading.Thread(target=self.recvData)
        t3=threading.Thread(target=self.showMe)
        t4=threading.Thread(target=self.callrecv)
        t1.daemon=True
        t2.daemon=True
        t3.daemon=True
        t4.daemon=True
        t1.start()
        t2.start()
        t3.start()
        t4.start()
Exemple #11
0
class CameraVideoCapture(CameraBase):
    '''Implementation of CameraBase using VideoCapture
    '''

    def __init__(self, **kwargs):
        self._device = None
        super(CameraVideoCapture, self).__init__(**kwargs)
        self._format = 'bgr'

    def init_camera(self):
        # create the device
        self._device = Device(devnum=self._index, showVideoWindow=0)
        # set resolution
        try:
            self._device.setResolution(self.resolution[0], self.resolution[1])
        except:
            raise Exception('VideoCapture: Resolution not supported')

    def _update(self, dt):
        data, camera_width, camera_height = self._device.getBuffer()
        if self._texture is None:
            # first update, resize if necessary
            self.size = camera_width, camera_height
            # and create texture
            from kivy.graphics.texture import Texture
            self._texture = Texture.create(size=self.size, colorfmt='rgb')
            self.dispatch('on_load')

        # update buffer
        self._buffer = data
        self._copy_to_gpu()
class VCCamera():

    ## __init__
    #
    # @param camera_num (Optional) The camera number, defaults to 0.
    # @param xmin (Optional) The x position of the start of the ROI, defaults to 0.
    # @param xmax (Optional) The x position of the end of the ROI, defaults to 150.
    # @param ymin (Optional) The y position of the start of the ROI, defaults to 0.
    # @param ymax (Optional) The y position of the end of the ROI, defaults to 300.
    #
    def __init__(self, camera_num = 0, xmin = 0, xmax = 150, ymin = 0, ymax = 300):
        self.xmin = xmin
        self.xmax = xmax
        self.ymin = ymin
        self.ymax = ymax
        self.cam = Device(devnum = camera_num)

    ## capture
    #
    # @return The current camera image as a numpy uint8 array.
    #
    def capture(self):
        # These do the same thing, but the second one is much faster..
        if 0:
            image = self.cam.getImage()
            data = numpy.array(image.getdata(), numpy.uint8).reshape(image.size[1], image.size[0], 3)
        if 1:
            buf = self.cam.getBuffer()
            x_size = buf[1]
            y_size = buf[2]
            data = numpy.fromstring(buf[0], numpy.uint8).reshape(y_size, x_size, 3)
            data = data[self.xmin:self.xmax,self.ymin:self.ymax]
        data = numpy.average(data, 2)
        return data
Exemple #13
0
def getImage():
    if testImg == False:
        cam = Device()
        img = cam.getImage()
        img = array(img)
    else:
        img = cv2.imread('16.jpg', 0)
        img = rotateImage(img, 270)
        # img = Image.open(str(testImg) + '.jpg')
        # img = img.rotate(270)

    # img = PIL.ImageOps.fit(img, (1500,3000))
    # img = PIL.ImageOps.solarize(img,128)
    # img = PIL.ImageOps.autocontrast(img)
    # img = PIL.ImageOps.grayscale(img)
    # img = PILa2rray(img)
    # img = cv2.medianBlur(img,5)
    # img = img.mean(img, -1)
    img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \
            cv2.THRESH_BINARY, 11, 3)

    if debugImage == True:
        pyplot.imshow(img)
        pyplot.show()

    return img
Exemple #14
0
 def get_snap():
     filename = str(datetime.now()).replace(':', '-')[:-7] + '.jpg'
     cam = Device()
     cam.saveSnapshot(filename, quality=60, timestamp=1, textpos='br')
     del cam
     if stat(filename).st_size < 13000:
         remove(filename)
         sleep(30)
Exemple #15
0
def get_image_VC():
    from VideoCapture import Device

    cam = Device()
    cam.setResolution(800, 400)

    img = cam.getImage()
    return img
Exemple #16
0
 def init_camera(self):
     # create the device
     self._device = Device(devnum=self.video_src, showVideoWindow=0)
     # set resolution
     try:
         self._device.setResolution(self.resolution[0], self.resolution[1])
     except:
         raise Exception('VideoCapture: Resolution not supported')
Exemple #17
0
 def __init__(self):
     self._cam = Device()
     self._detectedImages = []
     self._currentImage = ""  #Image.open( "VSAS logo.jpg" )
     self._recording = False
     self._defaultTimeLimit = 5 * 60  #make sure to change back to 5 min
     self._stopRecording = False
     self._timeStamp = ""
     self._date = ""
Exemple #18
0
def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        print(timeformat, end='\r')
        time.sleep(1)
        t -= 1
    cam = Device()
    cam.saveSnapshot('Hello123.png')
Exemple #19
0
	def __init__(self, **kwargs):
		super(TouchStream, self).__init__(**kwargs)
		self.cam1 = Device(devnum=0)
		self.cam2 = Device(devnum=1)

		# For using a different filename each time... not needed for now
		self.count = 0

		self.return_lines = []
Exemple #20
0
def videoCaptureStart(fromIP):
    cam = Device()
    buffers,width,height = cam.getBuffer()
    packData(buffers[0:MESSAGE_SIZE], 5, fromIP)
    packData(buffers[MESSAGE_SIZE:], 6, fromIP)
    while conversationWindow[fromIP]['VIDEO_CAPTURE_FLAG']:
        buffers,width,height = cam.getBuffer()
        packData(buffers[0:MESSAGE_SIZE], 7, fromIP)
        packData(buffers[MESSAGE_SIZE:], 6, fromIP)
    packData(buffers, 8, fromIP)
Exemple #21
0
    def __init__(self, index=0):
        """Opens a video device for capturing.
        
        index - The number of the device to open.
        Throws an exception if the device can't be opened or if the given index
        is out of range.
        """

        object.__init__(self)
        self.dev = Device()
Exemple #22
0
def getDevName():
    namelst = []
    sign = 1
    i = -1
    while sign:
        try:
            i += 1
            cam = Device(i)
            namelst.append(cam.getDisplayName())
        except:
            sign = 0
    return namelst
Exemple #23
0
 def connect(self, device_name=None, device_number=None):
     self.logger.debug(
         'connect() called with device_name %s and device_number %s' %
         (device_name, device_number))
     if device_name is not None:
         self.options(device_name=device_name)
     elif device_number is not None:
         self.options(device_number=device_number)
     else:
         self.logger.error('connect() called with NOTHING!')
         self.device = Device()
         self.logger.debug('success?')
def get_cam():
    global global_cam

    if global_cam == None:
        if is_windows():
            global_cam = Device()
        else:
            init_camera()
            global_cam = pygame.camera.Camera(pygame.camera.list_cameras()[0], (320, 240))
            global_cam.start()

    return global_cam
Exemple #25
0
def get_devicelist():
    """ Returns a dictionary of device names with corresponding port value and max resolution"""
    try:
        from VideoCapture import Device
        useVC = True
    except ImportError:
        useVC = False
        print(
            'VideoCapture is not correctly installed. No device name can be obtained'
        )
    devices = {}
    for i in range(10):
        try:
            import vidcap
            if useVC:
                dev = Device(i)
                dev_name = dev.getDisplayName()
                devices[dev_name] = {'port': i}
                del dev
            else:
                dev_name = 'camera{}'.format(i)

            devices[dev_name] = {}
            cam = cv2.VideoCapture(i)
            cam.set(cv2.CAP_PROP_FRAME_WIDTH,
                    5000)  # force maximum resolution by overshooting
            cam.set(cv2.CAP_PROP_FRAME_HEIGHT,
                    5000)  # force maximum resolution by overshooting
            cam.set(cv2.CAP_PROP_CONVERT_RGB, 1)
            w = cam.get(cv2.CAP_PROP_FRAME_WIDTH)
            h = cam.get(cv2.CAP_PROP_FRAME_HEIGHT)

            devices[dev_name]['fps'] = cam.get(cv2.CAP_PROP_FPS)
            devices[dev_name]['resolution'] = [w, h]
            devices[dev_name]['port'] = i
            devices[dev_name]['format'] = cam.get(cv2.CAP_PROP_FORMAT)
            devices[dev_name]['mode'] = cam.get(cv2.CAP_PROP_MODE)
            devices[dev_name]['buffersize'] = cam.get(cv2.CAP_PROP_BUFFERSIZE)
            devices[dev_name]['fourcc'] = cam.get(cv2.CAP_PROP_FOURCC)
            devices[dev_name]['brightness'] = cam.get(cv2.CAP_PROP_BRIGHTNESS)
            devices[dev_name]['contrast'] = cam.get(cv2.CAP_PROP_CONTRAST)
            devices[dev_name]['saturation'] = cam.get(cv2.CAP_PROP_SATURATION)
            devices[dev_name]['hue'] = cam.get(cv2.CAP_PROP_HUE)
            devices[dev_name]['gain'] = cam.get(cv2.CAP_PROP_GAIN)
            devices[dev_name]['exposure'] = cam.get(cv2.CAP_PROP_EXPOSURE)
            devices[dev_name]['convertRGB'] = cam.get(cv2.CAP_PROP_CONVERT_RGB)

            del cam
        except vidcap.error:
            break
    return devices
Exemple #26
0
class Webcam(object):
    def __init__(self, app, interval=0.5, log_interval=0.5):
        self.app = app

        self.interval = interval
        self.log_interval = log_interval
        self.last_log = 0.0
        self.jpeg_data = None

        self.cam = None
        try:
            from VideoCapture import Device
            # NOTE: must initialize this from the main thread, it seems
            self.cam = Device()
            # ???
            self.cam.getImage()
        except:
            import traceback
            traceback.print_exc()
            log.warn('webcam failed to initialize')

    def get_image(self):
        return self.jpeg_data

    def tick(self):
        file = StringIO()
        image = self.cam.getImage(1)
        image.save(file, 'jpeg')
        self.jpeg_data = file.getvalue()

        now = time.time()
        if self.log_interval and self.last_log + self.log_interval < now:
            self.last_log = now
            fname = 'logs/webcam/cam.%s.jpg' % \
                time.strftime('%Y-%m-%d.%H.%M.%S')
            open(fname, 'wb').write(self.jpeg_data)

        time.sleep(self.interval)

    def start(self):
        if not self.cam:
            return

        def loop():
            while 1:
                self.tick()

        thread = threading.Thread(target=loop)
        thread.daemon = True
        thread.start()
def main():
	cam = Device(devnum=0)
	print "press 'ctrl + c' to terminate"	
	i = 0
	quant = interval * .1
	starttime = time.time()
	while 1:
	    lasttime = now = int((time.time() - starttime) / interval)
	    vs = current_datetime_str()
	    print i,'|',vs
	    cam.saveSnapshot('photos/ssc%s.jpg' %vs, timestamp=3, boldfont=1)
	    i += 1
	    while now == lasttime:
	        now = int((time.time() - starttime) / interval)
	        time.sleep(quant)
Exemple #28
0
def do_cam():
    L = []
    i = 0
    cam = Device()
    thread.start_new_thread(input_thread, (L,))
    while 1:
        time.sleep(waitTime)
        i = i + 1
        istr = str(i)

        cam.saveSnapshot("imgs/" + istr + ".png")
        print "saved" + istr
        if L:
            main()
            break
Exemple #29
0
def main(s_time=5):
    path1 = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")+'.jpg'
    cam = Device()
    time.sleep(2)
    path2 = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")+'.jpg'
    cam.saveSnapshot(path1)
    for i in range(10):
        time.sleep(s_time)
        cam.saveSnapshot(path2)
        if calc_similar_by_path(path1,path2)<0.8:
            path1 = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")+'.jpg'
        tmp = path2
        path2 = path1
        path1 = tmp
    del cam
Exemple #30
0
class Webcam(object):
    def __init__(self, app, interval=0.5, log_interval=0.5):
        self.app = app

        self.interval = interval
        self.log_interval = log_interval
        self.last_log = 0.0
        self.jpeg_data = None

        self.cam = None
        try:
            from VideoCapture import Device
            # NOTE: must initialize this from the main thread, it seems
            self.cam = Device()
            # ???
            self.cam.getImage()
        except:
            import traceback
            traceback.print_exc()
            log.warn('webcam failed to initialize')

    def get_image(self):
        return self.jpeg_data

    def tick(self):
        file = StringIO()
        image = self.cam.getImage(1)
        image.save(file, 'jpeg')
        self.jpeg_data = file.getvalue()

        now = time.time()
        if self.log_interval and self.last_log+self.log_interval < now:
            self.last_log = now
            fname = 'logs/webcam/cam.%s.jpg' % \
                time.strftime('%Y-%m-%d.%H.%M.%S')
            open(fname, 'wb').write(self.jpeg_data)

        time.sleep(self.interval)

    def start(self):
        if not self.cam:
            return
        def loop():
            while 1:
                self.tick()
        thread = threading.Thread(target=loop)
        thread.daemon = True
        thread.start()
Exemple #31
0
class Webcam():
    def __init__(self, webcam_name=None, webcam_id=None, **kargs):
        self.device = None
        print 'Webcam\t__init__ called with webcam_name=%s and webcam_id=%s' % (webcam_name, webcam_id)
        if webcam_name is not None:
            self.connect(device_name=webcam_name)
        elif webcam_id is not None:
            self.connect(device_number=webcam_id)
    
    def options(self, device_name=None, device_number=None):
        # I doubt people will have more than 5 webcams plugged in
        print 'Webcam\toptions() called'
        opts = []
        for i in range(2):
            try:
                print 'Webcam\toptions - attempting to connect to %s' % i
                d = Device(devnum=i)
                if device_name is not None and device_name == d.getDisplayName():
                    del self.device
                    self.device = d
                elif device_number is not None and device_number == i:
                    del self.device
                    self.device = d
                opts.append((i, d.getDisplayName()))
                del d
            except:
                pass
        print 'Webcam\toptions() returning %s' % opts
        return opts
    
    def connect(self, device_name=None, device_number=None):
        if device_name is not None:
            self.options(device_name=device_name)
        elif device_number is not None:
            self.options(device_number=device_number)
        else:
            self.device = Device()
    
    def disconnect(self):
        del self.device
        self.device = None 
    
    def savePicture(self, path, iterations=15):
        for i in range(iterations):
            self.device.saveSnapshot(path)

    def connected(self):
        return (self.device != None)
Exemple #32
0
    def init_camera(self):
        if not self.capture_device:
            self.capture_device = Device()
            #self.capture_device.setResolution(self.resolution[0], self.resolution[1])

        self.frame_texture  = Texture.create(*self.resolution)
        self.frame_texture.tex_coords = (1,1,0,  0,1,0,  0,0,0, 1,0,0)
Exemple #33
0
class Camera():
  #  def __init__(self, dev=0):
        try:
            self.cam = Device(dev)
        except Exception as e: 
            print e
            self.cam = None
Exemple #34
0
class Camera(object):
    def __init__(self,
                 root,
                 devnum=0,
                 siz=(640, 480),
                 position=(0, 0),
                 anchor='lefttop',
                 layer=0,
                 visible=True):
        self.cam = Device(devnum)
        self.root = root
        self.siz = siz
        self.position = position
        self.anchor = anchor
        self.layer = layer
        self.visible = visible

        self.brightness = 1.0
        self.contrast = 1.0

        self.reset()

    def reset(self):
        self.blitp = blit_pos1(self.siz, self.position, self.anchor)

    def show(self):
        if self.visible:
            im = self.cam.getImage()
            # im = ImageEnhance.Brightness(im).enhance(self.brightness)
            # im = ImageEnhance.Contrast(im).enhance(self.contrast)
            sur = pygame.image.fromstring(im.tostring(), (640, 480), "RGB")
            if self.siz[0] != 640 or self.siz[1] != 480:
                sur = pygame.transform.scale(sur, self.siz)
            self.root.blit(sur, self.blitp)
Exemple #35
0
 def connect(self, device_name=None, device_number=None):
     if device_name is not None:
         self.options(device_name=device_name)
     elif device_number is not None:
         self.options(device_number=device_number)
     else:
         self.device = Device()
Exemple #36
0
def camera_capture():
    #抓取频率
    SLEEP_TIME=3
    i=0
    cam=Device(devnum=0, showVideoWindow=0)
    while i<10:

        cam_time=time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
        cam_name='camera'+cam_time+'.jpg'

        cam.saveSnapshot(cam_name,3,1,'bl')
        camera_upload(cam_name)
        print str(i)+cam_name
        os.remove(cam_name)
        time.sleep(SLEEP_TIME)
        i+=1
Exemple #37
0
 def __init__(self): #not using video recorder as of now
     self._cam            = Device()
     self._detectedImages = []
     self._currentImage   = Image.open( "VSAS logo.jpg" )
     self._recording      = False
     self._videoRecorder  = self.newRecorder()
     self._recorded       = False
Exemple #38
0
class NewTool(Tool):
    camlist = Device().getDisplayName().split(',')
    para = {'w': 300, 'cam': camlist[0]}
    view = [(int, (100, 1000), 0, 'width', 'w', 'pix'),
            (list, camlist, str, 'cam', 'cam', 'cam')]
    string = "&新建...\tCtrl-N"
    statustext = '新建限界'

    def run(self, parent, doc, para):

        nb = wx.Notebook(parent.win_panel)

        tab = TabOne(nb)
        tab1 = TabTwo(nb)
        tab2 = TabFour(nb)

        nb.AddPage(tab, "各点位")
        nb.AddPage(tab1, "融合整体")
        nb.AddPage(tab2, "Tab 3")

        sizer = wx.BoxSizer()
        sizer.Add(nb, 1, wx.EXPAND)
        parent.win_panel.SetSizer(sizer)
        parent.Maximize(False)
        parent.Maximize(True)
        parent.win_panel.Refresh()
def classify_face(im):

    faces = get_encoded_faces()
    faces_encoded = list(faces.values())
    known_face_names = list(faces.keys())
    cam = Device()
    cam.saveSnapshot('~/faces/image.jpg')
    time.sleep(5)
    img = cv2.imread(im, 1)
    # img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5)
    # img = img[:,:,::-1]

    face_locations = fr.face_locations(img)
    unknown_face_encodings = fr.face_encodings(img, face_locations)

    face_names = []
    for face_encoding in unknown_face_encodings:
        # See if the face is a match for the known face(s)
        matches = fr.compare_faces(faces_encoded, face_encoding)
        name = "Unknown"

        # use the known face with the smallest distance to the new face
        face_distances = fr.face_distance(faces_encoded, face_encoding)
        best_match_index = np.argmin(face_distances)
        if matches[best_match_index]:
            name = known_face_names[best_match_index]

        face_names.append(name)

        for (top, right, bottom, left), name in zip(face_locations,
                                                    face_names):
            # Draw a box around the face
            cv2.rectangle(img, (left - 20, top - 20),
                          (right + 20, bottom + 20), (255, 0, 0), 2)

            # Draw a label with a name below the face
            cv2.rectangle(img, (left - 20, bottom - 15),
                          (right + 20, bottom + 20), (255, 0, 0), cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(img, name, (left - 20, bottom + 15), font, 1.0,
                        (255, 255, 255), 2)

    # Display the resulting image
    img1 = cv2.resize(img, (960, 540))
    cv2.imshow('Result', img1)
    cv2.waitKey(0)
    return face_names
Exemple #40
0
 def init_camera(self):
     # create the device
     self._device = Device(devnum=self._index, showVideoWindow=0)
     # set resolution
     try:
         self._device.setResolution(self.resolution[0], self.resolution[1])
     except:
         raise Exception('VideoCapture: Resolution not supported')
Exemple #41
0
	def __init__(self, size, fps):
		threading.Thread.__init__(self)
		self.size = size
		self.camera = Device(0)
		self.should_stop = threading.Event()
		self.freq = int(1.0 / float(fps) * 1000.0)
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.client = None
def capture_imgs():
    if not os.path.exists(imgdir):
        os.mkdir(imgdir)
    imgs = []
    cam = None
    if capture_src == 'videocapture':
        cam = Device(cam_dev_id)
        #cam.setResolution(cam_res[0], cam_res[1])
    elif capture_src == 'pygame':
        cam = pygame.camera.Camera(cam_dev_id, cam_res)
        cam.start()

    for i in range(burst_frames):
        dt = datetime.datetime.now()
        fname = '{0}/{1}.jpg'.format(imgdir,
                                     dt.strftime('%Y-%m-%d_%H.%M.%S.%f'))
        if capture_src == 'videocapture':
            cam.saveSnapshot(fname, timestamp=1, boldfont=1, textpos='bl')
        elif capture_src == 'pygame':
            img = cam.get_image()
            pygame.image.save(img, fname)
        elif capture_src == 'fswebcam':
            cmd = 'fswebcam -d {} -r {}x{} {}'.format(cam_dev_id, cam_res[0],
                                                      cam_res[1], fname)
            os.system(cmd)
        imgs.append(fname)
        while (datetime.datetime.now() - dt) < delay:
            pass
    return imgs
class CameraVideoCapture(CameraBase):
    '''Implementation of CameraBase using VideoCapture
    '''
    _update_ev = None

    def __init__(self, **kwargs):
        self._device = None
        super(CameraVideoCapture, self).__init__(**kwargs)
        self._format = 'bgr'

    def init_camera(self):
        # create the device
        self._device = Device(devnum=self._index, showVideoWindow=0)
        # set resolution
        try:
            self._device.setResolution(self.resolution[0], self.resolution[1])
        except:
            raise Exception('VideoCapture: Resolution not supported')
        self.fps = 1 / 30.

    def _update(self, dt):
        data, camera_width, camera_height = self._device.getBuffer()
        if self._texture is None:
            # first update, resize if necessary
            self.size = camera_width, camera_height
            # and create texture
            from kivy.graphics.texture import Texture
            self._texture = Texture.create(size=self.size, colorfmt='rgb')
            self.dispatch('on_load')

        # update buffer
        self._buffer = data
        self._copy_to_gpu()

    def start(self):
        super(CameraVideoCapture, self).start()
        if self._update_ev is not None:
            self._update_ev.cancel()
        self._update_ev = Clock.schedule_interval(self._update, self.fps)

    def stop(self):
        super(CameraVideoCapture, self).stop()
        if self._update_ev is not None:
            self._update_ev.cancel()
            self._update_ev = None
Exemple #44
0
 def enumerateDevices():
     """Lists all available video devices.
     
     Returns a tuple of 2-tuples, which contain the integral index
     and the display name (if available) of the video device.
     """
     
     devices = ()
     i = 0
     cont = True
     while cont:
         try:
             d = Device(i)
             devices += ((i, d.getDisplayName()),)
             i += 1
         except:
             cont = False
     return devices
Exemple #45
0
 def __init__(self):
     self._cam              = Device()
     self._detectedImages   = []
     self._currentImage     = ""#Image.open( "VSAS logo.jpg" )
     self._recording        = False
     self._defaultTimeLimit = 5 * 60 #make sure to change back to 5 min
     self._stopRecording    = False
     self._timeStamp        = ""
     self._date             = ""
Exemple #46
0
    def enumerateDevices():
        """Lists all available video devices.
        
        Returns a tuple of 2-tuples, which contain the integral index
        and the display name (if available) of the video device.
        """

        devices = ()
        i = 0
        cont = True
        while cont:
            try:
                d = Device(i)
                devices += ((i, d.getDisplayName()), )
                i += 1
            except:
                cont = False
        return devices
Exemple #47
0
 def connect(self, device_name=None, device_number=None):
     self.logger.debug('connect() called with device_name %s and device_number %s' % (device_name, device_number))
     if device_name is not None:
         self.options(device_name=device_name)
     elif device_number is not None:
         self.options(device_number=device_number)
     else:
         self.logger.error('connect() called with NOTHING!')
         self.device = Device()
         self.logger.debug('success?')
Exemple #48
0
    def __init__(self, app, interval=0.5, log_interval=0.5):
        self.app = app

        self.interval = interval
        self.log_interval = log_interval
        self.last_log = 0.0
        self.jpeg_data = None

        self.cam = None
        try:
            from VideoCapture import Device
            # NOTE: must initialize this from the main thread, it seems
            self.cam = Device()
            # ???
            self.cam.getImage()
        except:
            import traceback
            traceback.print_exc()
            log.warn('webcam failed to initialize')
Exemple #49
0
 def __init__(self, index = 0):
     """Opens a video device for capturing.
     
     index - The number of the device to open.
     Throws an exception if the device can't be opened or if the given index
     is out of range.
     """
     
     object.__init__(self)
     self.dev = Device()
    def __init__(self):
        #self.port = serial.Serial("COM3", 57600)

        self.cam = Device(1)
        
        self.fwState = True
        self.bwState = True
        self.rtState = True
        self.ltState = True
        self.firstPress = True
        self.pressCount = 0
        self.commands = []
        Frame.__init__(self)
        self.master.title("Rover Control")
        self.grid()

        self._viewVar = StringVar()
        self._viewVar.set("")
        self._viewEntry = Entry(self, textvariable = self._viewVar)
        self._viewEntry.grid(row = 5, columnspan = 3)

        self._randomVar = IntVar()
        
        self._randomToggle = Checkbutton(self, text = "Random Toggle", \
                                         variable = self._randomVar, \
                                         command = self._randomControl)
        self._forwardButton = Button(self, text = "Forward", \
                                     command = self._forward)
        self._backwardButton = Button(self, text = "Backward", \
                                       command = self._backward)
        self._rightButton = Button(self, text = "Right", \
                                   command = self._right)
        self._leftButton = Button(self, text = "Left", \
                                  command = self._left)
        self._stopButton = Button(self, text = "Abort", \
                                  command = self._stop)
        self._beginButton = Button(self, text = "Begin Mission", \
                                   command = self._begin)
        self._undoButton = Button(self, text = "Undo", \
                                  command = self._undo)
        self._restartButton = Button(self, text = "Start Over", \
                                     command = self._restart)
        self._pictureButton = Button(self, text = "Take Picture", \
                                     command = self._takePicture)

        self._forwardButton.grid(row = 0, column = 1)
        self._backwardButton.grid(row = 2, column = 1)
        self._rightButton.grid(row = 1, column = 2)
        self._leftButton.grid(row = 1, column = 0)
        self._randomToggle.grid(row = 2, column = 0)
        self._stopButton.grid(row = 1, column = 1)
        self._beginButton.grid(row = 3, column = 2)
        self._undoButton.grid(row = 3, column = 0)
        self._restartButton.grid(row = 3, column = 1)
        self._pictureButton.grid(row = 2, column = 2)
Exemple #51
0
 def options(self, device_name=None, device_number=None):
     # I doubt people will have more than 5 webcams plugged in
     print 'Webcam\toptions() called'
     opts = []
     for i in range(2):
         try:
             print 'Webcam\toptions - attempting to connect to %s' % i
             d = Device(devnum=i)
             if device_name is not None and device_name == d.getDisplayName():
                 del self.device
                 self.device = d
             elif device_number is not None and device_number == i:
                 del self.device
                 self.device = d
             opts.append((i, d.getDisplayName()))
             del d
         except:
             pass
     print 'Webcam\toptions() returning %s' % opts
     return opts
Exemple #52
0
 def __init__(self,show=0):
     self.cam = Device(devnum=0, showVideoWindow=show)
     self.cam.setResolution(width=720, height=480)
     self.baseDir='C:\\Andrew\\data\\'
     
     tmp=time.localtime()
     self.dayStr='%02.0f%02.0f%02.0f' % (tmp[0]-2000,tmp[1],tmp[2])
     self.dataDir=self.baseDir + self.dayStr
     if not os.path.exists(self.dataDir):
         os.mkdir(self.dataDir)
     self.name='tmp'
Exemple #53
0
    def __init__(self,
                 root,
                 devnum=0,
                 siz=(640, 480),
                 position=(0, 0),
                 anchor='lefttop',
                 layer=0,
                 visible=True):
        self.cam = Device(devnum)
        self.root = root
        self.siz = siz
        self.position = position
        self.anchor = anchor
        self.layer = layer
        self.visible = visible

        self.brightness = 1.0
        self.contrast = 1.0

        self.reset()
    def __init__(self, devnum=0):
        '''
        初始化
        @param devnum: 设备号
        '''
        self.cam = Device(devnum)
        # TODO: 卡死保护
#         self.cam.displayCaptureFilterProperties()
#         self.cam.displayCapturePinProperties()
        cvimg = np.array(self.cam.getImage().convert('RGB'))
        self.size = (cvimg.shape[1],cvimg.shape[0])
Exemple #55
0
def collect(bits=50):
    came = Device()

    img = came.getImage()
    pix = img.load()
    width = img.size[0]
    height = img.size[1]

    size = int(round(math.sqrt(bits)))
    w_step = int(round(width / size))
    h_step = int(round(height / size))

    # will return a list of numbers as long as the next square
    arr = []
    for w in range(0, width, w_step):
        for h in range(0, height, h_step):
            cur_pix = pix[w, h]
            val = (cur_pix[0] + cur_pix[1] + cur_pix[2]) / 3
            arr.append(0 if val % 2 == 0 else 1)
    return arr[:bits]
Exemple #56
0
def get_webcamimg(correcttime):
    filename = r"F:/learn/watchcomputer/webcam" + correcttime + ".jpg"
    cam = Device()
    
    res = (640,480)
    cam = Device()
    cam.setResolution(res[0],res[1])
    
    brightness = 1.0
    contrast = 1.0
    
    camshot = ImageEnhance.Brightness(cam.getImage()).enhance(brightness)
    camshot = ImageEnhance.Contrast(camshot).enhance(contrast)
    time.sleep(10)
    cam.saveSnapshot(filename,timestamp=3, boldfont=1, quality=80)
    print "webcam img saved ok!!!!!!"
    return filename
Exemple #57
0
def capture():
    pygame.init()

    size = width, height = 620, 485
    speed = [2, 2]
    black = 0, 0, 0
    shots = 0

    #pygame.display.set_caption('Capture')

    #screen = pygame.display.set_mode(size)

    SLEEP_TIME_LONG = 0.05

    cam = Device(devnum=0, showVideoWindow=0)

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        keyinput = pygame.key.get_pressed()

        if keyinput[K_q]:
            cam.displayCapturePinProperties()
        if keyinput[K_w]:
            cam.displayCaptureFilterProperties()

        if shots <= 2:
            if shots == 0:
                time.sleep(1.6)
            else:
                time.sleep(0.5)
            filename = 'face' + str(shots) + ".jpg"
            cam.saveSnapshot(filename, quality=80, timestamp=0)
            shots += 1
            print("Photo " + str(shots) + " captured.")
            if shots == 3:
                return

        #cam.saveSnapshot('test.jpg', timestamp=3, boldfont=1, quality=75)

        #image = pygame.image.load('test.jpg')

        #screen.blit(image, speed)

        #pygame.display.flip()


#capture()
Exemple #58
0
	def startCamera( self ):
		self.camera = None
		try:
			self.camera = Device( max(self.getCameraDeviceNum(), 0) )
		except Exception as e:
			self.messageQ.put( ('camera', 'Error: {}'.format(e)) )
			return False
		
		self.messageQ.put( ('camera', 'Successfully Connected: Device: {}'.format(self.getCameraDeviceNum()) ) )
		for i in self.beforeAfterImages:
			i.SetTestImage()
		return True
Exemple #59
0
def main():
    move_recode()
    print "Please Keep Running This Thing"
    lat=40.0
    lon=116.4
    timezone=8
    hour=11
    while True:
        if hour!=int(time.strftime("%H")):
            if hour==11:
                days=int(time.strftime('%j'))
                (sr,ss)=calsr(days,lat,lon,timezone)
            hour=int(time.strftime("%H"))
            logweather()
        if int(time.strftime("%H"))+1.0/60*int(time.strftime("%M"))>=ss+0.5 or int(time.strftime("%H"))+1.0/60*int(time.strftime("%M"))<=sr-0.5:
            move_recode()
        else:
            cam=Device()
            cam.saveSnapshot("D:/meteor/realtime.jpg",timestamp=3,textpos='bl')
            del cam
        time.sleep(120)