Exemplo n.º 1
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()
Exemplo n.º 2
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")
Exemplo n.º 3
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()
Exemplo n.º 4
0
def get_image_VC():
    from VideoCapture import Device

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

    img = cam.getImage()
    return img
Exemplo n.º 5
0
 def capture_image(self, name, resolution=(1280, 720)):
     """
     The object construction and invoking should in same thread, otherwise it will cause blocking.
     """
     logger.debug("Capture image to '%s' with resolution '%s'", name, resolution)
     from VideoCapture import Device
     cam = Device(devnum=self.devnum)
     cam.setResolution(*resolution)
     try:
         cam.saveSnapshot(name)
     except AttributeError:
         logger.exception("")
         logger.debug("Webcam capture image failed, try is again.")
         cam.saveSnapshot(name)
Exemplo n.º 6
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
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
Exemplo n.º 8
0
def camera():
    res = (640,480)
    pygame.init()
    cam = Device()
    cam.setResolution(res[0],res[1])
    screen = pygame.display.set_mode((640,480))
    pygame.display.set_caption('Webcam')
    pygame.font.init()
    font = pygame.font.SysFont("Courier",11)
     
    def disp(phrase,loc):
        s = font.render(phrase, True, (200,200,200))
        sh = font.render(phrase, True, (50,50,50))
        screen.blit(sh, (loc[0]+1,loc[1]+1))
        screen.blit(s, loc)
     
    brightness = 1.0
    contrast = 1.0
    shots = 0
     
    while 1:
        camshot = ImageEnhance.Brightness(cam.getImage()).enhance(brightness)
        camshot = ImageEnhance.Contrast(camshot).enhance(contrast)
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
        keyinput = pygame.key.get_pressed()
        #if keyinput[K_1]: brightness -= .1
        #if keyinput[K_2]: brightness += .1
        #if keyinput[K_3]: contrast -= .1
        #if keyinput[K_4]: contrast += .1
        if keyinput[K_q]: sys.exit()
        #if keyinput[K_w]: cam.displayCaptureFilterProperties()
        if keyinput[K_s]:
            filename = str(time.time()) + ".jpg"
            cam.saveSnapshot(filename, quality=80, timestamp=0)
            shots += 1
        camshot = pygame.image.frombuffer(camshot.tostring(), res, "RGB")
        screen.blit(camshot, (0,0))
        #disp("S:" + str(shots), (10,4))
        #disp("B:" + str(brightness), (10,16))
        #disp("C:" + str(contrast), (10,28))
        disp("press s to save the shot",(10,40))
        disp("press q to exit the camera",(10,52))
        pygame.display.flip()
Exemplo n.º 9
0
class myCam:
    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'
    def setProperties(self):
        self.cam.displayCapturePinProperties()
    def grab(self,fn=None,q=90):
        if fn is None:
            fn='%stest.jpg' % self.baseDir
        self.cam.saveSnapshot(filename=fn, quality=q)
    def series(self,n=1,s=None):
        if not s is None:
            self.name=s
        for i in range(n):
            self.grab('%s\\%s%03.0f.jpg' % (self.dataDir,self.name,i))
Exemplo n.º 10
0
class CameraVideoCapture(CameraBase):
    '''Implementation of CameraBase using VideoCapture
    
    :Parameters:
        `video_src` : int, default is 0
            Index of VideoCapture camera to use (0 mean default camera)
    '''

    def __init__(self, **kwargs):
        # override the default source of video
        kwargs.setdefault('video_src', 0)
        self._device = None
        super(CameraVideoCapture, self).__init__(**kwargs)
        self._format = GL_BGR

    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')

    def update(self):
        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 = pymt.Texture.create(camera_width, camera_height,
                                                format=GL_BGR)

        # update buffer
        self._buffer = data
        self._copy_to_gpu()
Exemplo n.º 11
0
class CameraVideoCapture(CameraBase):
    '''Implementation of CameraBase using VideoCapture

    :Parameters:
        `video_src` : int, default is 0
            Index of VideoCapture camera to use (0 mean default camera)
    '''
    def __init__(self, **kwargs):
        # override the default source of video
        kwargs.setdefault('video_src', 0)
        self._device = None
        super(CameraVideoCapture, self).__init__(**kwargs)
        self._format = GL_BGR

    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')

    def update(self):
        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 = pymt.Texture.create(camera_width,
                                                camera_height,
                                                format=GL_BGR)

        # update buffer
        self._buffer = data
        self._copy_to_gpu()
Exemplo n.º 12
0
                is_sending = True
                ser_socket.sendto('startRcv', cli_address)
            if message == 'quitCam':
                is_sending = False
                print 'quit camera',

    def stop(self):
        self.thread_stop = True


# 创建接收线程
receiveThread = UdpReceiver()
receiveThread.setDaemon(True)  # 该选项设置后使得主线程退出后子线程同时退出
receiveThread.start()

# 初始化摄像头
cam = Device()
cam.setResolution(320, 240)

# 主线程循环,发送视频数据
while 1:
    if is_sending:
        img = cam.getImage().resize((160, 120))
        data = img.tostring()
        ser_socket.sendto(data, cli_address)
        time.sleep(0.05)
    else:
        time.sleep(1)

receiveThread.stop()
ser_socket.close()
Exemplo n.º 13
0
from VideoCapture import Device
import ImageDraw, sys
import PIL
import os, time, datetime, thread, threading

res = (640, 480)
cam = Device(showVideoWindow=0)    #initialize camera instance
cam.setResolution(res[0],res[1])   #set resolution

shots = 0
ctr = 0

def ftp_thread(f, filename):
	'''Thread which uploads filename using spftp instance f.'''
	f.write('put '+ filename+'\n')
	
def save(ctr_array):
	'''Capture image and return its filename.'''
	print('Capturing image.')
	filetime = time.strftime("%d-%m-%Y+%H.%M.%S", time.localtime())
	filename = str(filetime) + '-' + str(ctr_array) + ".jpg"
	cam.saveSnapshot(filename, quality=80, timestamp=1)
	return filename

def diff_image(img1, img2, pix_threshold=20, img_threshold=20):
	'''Compare 2 images to detect possible motion. This funtion is 
	originally from http://huangjiahua.livejournal.com/39912.html'''
	if not img1 or not img2: return False
	resize_res = (320,240)
	img1 = img1.getdata()
	img1 = img1.resize(resize_res)
Exemplo n.º 14
0
import socket  
import Image  
from VideoCapture import Device  
cam = Device()  
cam.setResolution(320,240)  
clisocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
while 1:  
    im = cam.getImage()  
    im = im.resize((160,120))  
    da = im.tostring()  
    clisocket.sendto(da, ("127.0.0.1", 1234))  
s.close() 
Exemplo n.º 15
0
from PIL import ImageEnhance
#import MssUnitChr2 as ms
import MssUnit2 as ms # less talkative version of the MssUnit

#import UniversalLibrary as UL
import numpy as np

# camera parameters
res = (1344,1024)
#res = (640,480)
pixel_4x=[1.532,1.532] # one pixel in um at 4x, resolution 1344x1024
FRAMERATE = 25 # 25
pygame.init()
cam = Device()
cam.displayCapturePinProperties()
cam.setResolution(res[0],res[1])
screen = pygame.display.set_mode(res)
pygame.display.set_caption('CRACM Now')
pygame.font.init()
font = pygame.font.SysFont("Courier",11)      
    
brightness = 1.0
contrast = 1.0
shots = 0

# pygame control initial settings
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
moveZUp= False
from VideoCapture import Device

import cv2
import numpy

cam = Device()
cam.setResolution(640, 480)

cv2.namedWindow("preview")

while True:
    key = cv2.waitKey(20)
    if key == 27:  # exit on ESC
        break

    frame = numpy.asarray(cam.getImage())
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # display frame
    cv2.imshow("preview", frame)
Exemplo n.º 17
0
import pygame.camera
import pygame.image
import sys
import cv2
import time
from VideoCapture import Device

cam = Device()
cam.saveSnapshot('image.jpg')
cam.setResolution(160,120)

# grab first frame
colorimg = cam.getImage()
img = colorimg.convert('L')
WIDTH = img.size[0]
HEIGHT = img.size[1]
screen = pygame.display.set_mode( ( WIDTH*2, HEIGHT*2 ) )
pygame.display.set_caption("pyGame Camera View")
average = img
diff = img


while True :
    time.sleep(0.05)
    for e in pygame.event.get() :
        if e.type == pygame.QUIT :
            sys.exit()
    rgbimg = img.convert("RGB")
    mode = rgbimg.mode
    size = rgbimg.size
    data = rgbimg.tostring()
Exemplo n.º 18
0
from VideoCapture import Device
from time import sleep
import Image
import ImageFilter
import ImageChops
import ImageOps

cam = Device()
cam.setResolution(640,480)

def main():
    for ii in range(10):
        im = cam.getImage()
        im = ApplyFilterSet2(im)
        im.save('%i.jpg' % ii)
        sleep(1)

def ApplyFilterSet1(im):
    im2 = im.filter(ImageFilter.FIND_EDGES)
    im2 = im2.filter(ImageFilter.BLUR)
    im = ImageChops.multiply(im,im2)
    return im

def ApplyFilterSet2(im):
    im2 = im.filter(ImageFilter.FIND_EDGES)
    im = ImageOps.solarize(im)
    im = ImageChops.difference(im,im2)
    return im

if __name__ == "__main__":
    main()
Exemplo n.º 19
0
FULLSCREEN = 0
COLORTHRESHOLD = 60 #color threshold for motion detection, the higher the more strict (avg. 50 is ok)
SIZE = 320,240 # resolution of the screen (and camera, but can be seperated), needs to be 4/3 (I think)
CSIZE = 160,120 #compressed size, needs to be 4/3 (widescreen hack?)

#init vars
##########
#psyco.full() #PSYCO speeds up python
pygame.init() #We need to initialize pygame early on, so that certain stuff works (loading sound..)
ratio = SIZE[0]/CSIZE[0] #ratio of compression
fps = performance.FpsMeter() #an FPS meter
font = pygame.font.Font(None, 36) #a font for writing :)

#select cam and set resolution
cam = Device(devnum=0)
cam.setResolution(SIZE[0],SIZE[1])

#the pygame screen
if FULLSCREEN:
    screen = pygame.display.set_mode(SIZE, pygame.FULLSCREEN)
else:
    screen = pygame.display.set_mode(SIZE)
    
#new empty images, we will be using them in the main loop
#ni = newest image
#nci = newest compressed image
#oci = older compressed image
cci = Image.new("RGB",CSIZE,(255,255,255))
ni = Image.new("RGB",SIZE,(255,255,255))
oci = cci
photo4 = resize_photo(Image.open('mccord/1931-025-203.jpg'))

# preview has two states: JPEG image and solid rectangle (demo)
preview_images = (resize_photo(Image.open('mccord/1910-025-1030.jpg'), 478),
                  Image.new("RGB", (478,478), (0,0,0)))
        
# switch between preview ON and OFF
toggle = 1

# 0 = transparent, 255 = opaque
photo_transparency = 200

# initialization
pygame.init()
cam = Device()
cam.setResolution(camera_width,camera_height)
screen = pygame.display.set_mode(screen_resolution)
pygame.display.set_caption('Kiosk in a Cabinet')
pygame.mouse.set_visible(0)

while 1:

    # grab two images and clip button region to do motion detection
    img1 = cam.getImage()
    detect1 = img1.crop((detector_left,detector_upper,detector_right,detector_lower))
    img2 = cam.getImage()
    detect2 = img2.crop((detector_left,detector_upper,detector_right,detector_lower))

    # event handler
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
Exemplo n.º 21
0
#-*- coding:utf-8 -*-
from VideoCapture import Device

cam = Device()
cam.setResolution(320, 240)  #设置显示分辨率
cam.saveSnapshot('demo.jpg')  #抓取并保存图片
Exemplo n.º 22
0
from PIL import ImageEnhance, Image

import pygame
from pygame.locals import *

from functions import *

# Video resolution
vres = (640, 480)

# Window size
wsize = (800, 600)

# Set up the camera
cam = Device()
cam.setResolution(vres[0], vres[1])
brightness = 1.0
contrast = 1.0

# Set up the main window
pygame.init()
screen = pygame.display.set_mode(wsize)
pygame.display.set_caption("lboard")
pygame.font.init()
font = pygame.font.SysFont("Arial", 11)

# Set some default values
C_WHITE = (255, 255, 255)  # Constant
C_BLACK = (0, 0, 0)  # Constant
C_BG = (
    "Normal",
Exemplo n.º 23
0
from VideoCapture import Device
import ImageDraw, sys
import PIL
import os, time, datetime, thread, threading

res = (640, 480)
cam = Device(showVideoWindow=0)  #initialize camera instance
cam.setResolution(res[0], res[1])  #set resolution

shots = 0
ctr = 0


def ftp_thread(f, filename):
    '''Thread which uploads filename using spftp instance f.'''
    f.write('put ' + filename + '\n')


def save(ctr_array):
    '''Capture image and return its filename.'''
    print('Capturing image.')
    filetime = time.strftime("%d-%m-%Y+%H.%M.%S", time.localtime())
    filename = str(filetime) + '-' + str(ctr_array) + ".jpg"
    cam.saveSnapshot(filename, quality=80, timestamp=1)
    return filename


def diff_image(img1, img2, pix_threshold=20, img_threshold=20):
    '''Compare 2 images to detect possible motion. This funtion is 
	originally from http://huangjiahua.livejournal.com/39912.html'''
    if not img1 or not img2: return False
Exemplo n.º 24
0
#-*- coding:utf-8 -*-
from VideoCapture import Device  
cam = Device()  
cam.setResolution(320,240)   #设置显示分辨率  
cam.saveSnapshot('demo.jpg') #抓取并保存图片
photo4 = resize_photo(Image.open('mccord/1931-025-203.jpg'))

# preview has two states: JPEG image and solid rectangle (demo)
preview_images = (resize_photo(Image.open('mccord/1910-025-1030.jpg'),
                               478), Image.new("RGB", (478, 478), (0, 0, 0)))

# switch between preview ON and OFF
toggle = 1

# 0 = transparent, 255 = opaque
photo_transparency = 200

# initialization
pygame.init()
cam = Device()
cam.setResolution(camera_width, camera_height)
screen = pygame.display.set_mode(screen_resolution)
pygame.display.set_caption('Kiosk in a Cabinet')
pygame.mouse.set_visible(0)

while 1:

    # grab two images and clip button region to do motion detection
    img1 = cam.getImage()
    detect1 = img1.crop(
        (detector_left, detector_upper, detector_right, detector_lower))
    img2 = cam.getImage()
    detect2 = img2.crop(
        (detector_left, detector_upper, detector_right, detector_lower))

    # event handler
Exemplo n.º 26
0
Arquivo: 20.py Projeto: 602437897/face
from VideoCapture import Device

cam = Device()
cam.setResolution(400, 400)
cam.saveSnapshot('father.jpg')