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
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)
def captureScreenshot(dirName): """[summary] Arguments: dirName {[type]} -- [description] """ print("==================================================================================") print("Please wait, Save Snapshot function started") print("==================================================================================") cam = Device(0, 0) cam.saveSnapshot(dirName + r"\Temp_Result\screenshot1.jpg") time.sleep(3) files = glob.glob(dirName + r"\Temp_Result/*.jpg") while len(files) > 1: os.remove(files[-1]) files.pop() cam.saveSnapshot(dirName + r"\Temp_Result\screenshot2.jpg") time.sleep(3) files = glob.glob(dirName + r"\Temp_Result/*.jpg") while len(files) > 2: os.remove(files[-1]) files.pop() del cam print("==================================================================================") print("Save Snapshot function completed") print("==================================================================================")
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
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")
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)
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')
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()
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)
def webcamshot(self, filename): # type: (str) -> Union[str, None] """ Takes a snapshot with the webcam and returns the path to the saved image (in TMP). None if could not take the snapshot. """ if not self.configuration["camshot"]: self.log.info("Skipping webcamshot.") return None temp = gettempdir() self.log.info("Taking webcamshot") if self.is_windows(): filepath = "{}_webcam.jpg".format(os.path.join(temp, filename)) try: cam = Device(devnum=0) # type: ignore if not cam: cam = Device(devnum=1) # type: ignore except Exception as ex: # pylint: disable=broad-except self.log.error("vidcap.Error: %s", ex) return None try: # Here you can modify the picture resolution # cam.setResolution(768, 576) cam.getImage() time.sleep(2) cam.saveSnapshot(filepath) except ValueError as ex: self.log.error(ex) return None else: filepath = "{}_webcam.{}".format( os.path.join(temp, filename), self.configuration["camshot_filetype"]) cmd = self.configuration["camshot"].replace("<filepath>", filepath) self.runprocess(cmd, useshell=True) if os.path.isfile(filepath): if self.configuration["camshot_filetype"] == "ppm": full_path_ = os.path.join(temp, filename) new_path_ = "{}_webcam.jpg".format(full_path_) self.runprocess(["/usr/bin/convert", filepath, new_path_]) os.unlink(filepath) filepath = new_path_ if not os.path.isfile(filepath): return None self.log.debug(filepath) return filepath
def captureScreenshot(dirName): cam = Device(0, 0) cam.saveSnapshot(dirName + r"\Temp_Result\screenshot1.jpg") time.sleep(3) files = glob.glob(dirName + r"\Temp_Result/*.jpg") while len(files) > 1: os.remove(files[-1]) files.pop() cam.saveSnapshot(dirName + r"\Temp_Result\screenshot2.jpg") time.sleep(3) files = glob.glob(dirName + r"\Temp_Result/*.jpg") while len(files) > 2: os.remove(files[-1]) files.pop()
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)
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
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
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)
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
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
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
def webcamshot(self, filename): ''' Takes a snapshot with the webcam and returns the path to the saved image (in TMP). None if could not take the snapshot. ''' if not self.configuration['camshot']: self.log.info('Skipping webcamshot.') return None temp = gettempdir() self.log.info('Taking webcamshot') if self.os_name == 'Windows': filepath = '{}_webcam.jpg'.format(os.path.join(temp, filename)) try: cam = Device(devnum=0) if not cam: cam = Device(devnum=1) except Exception as ex: self.log.error('vidcap.Error: %s', ex) return None try: # Here you can modify the picture resolution # cam.setResolution(768, 576) cam.getImage() time.sleep(1) cam.saveSnapshot(filepath) except ValueError as ex: self.log.error(ex) return None else: filepath = '{}_webcam.{}'.format( os.path.join(temp, filename), self.configuration['camshot_filetype']) cmd = self.configuration['camshot'].replace('<filepath>', filepath) self.runprocess(cmd, useshell=True) if os.path.isfile(filepath): if self.configuration['camshot_filetype'] == 'ppm': full_path_ = os.path.join(temp, filename) new_path_ = '{}_webcam.jpg'.format(full_path_) self.runprocess(['/usr/bin/convert', filepath, new_path_]) os.unlink(filepath) filepath = new_path_ if not os.path.isfile(filepath): return None return filepath
def webcamshot(filename): ''' Takes a snapshot with the webcam and returns the path to the saved image (in TMP). None if could not take the snapshot. ''' if not CONFIG['camshot']: LOG.info('Skipping webcamshot.') return None temp = tempfile.gettempdir() LOG.info('Taking webcamshot') if OS == 'Windows': filepath = '{0}{1}{2}_webcam.jpg'.format(temp, SEP, filename) try: cam = Device(devnum=0) if not cam: cam = Device(devnum=1) except Exception as ex: LOG.error('vidcap.Error: %s', ex) return None try: # Here you can modify the picture resolution #cam.setResolution(768, 576) cam.getImage() time.sleep(1) cam.saveSnapshot(filepath) except ValueError as ex: LOG.error(ex) return None else: filepath = '{0}{1}{2}_webcam.{3}'.format(temp, SEP, filename, CONFIG['camshot_filetype']) cmd = CONFIG['camshot'].replace('<filepath>', filepath) runprocess(cmd, useshell=True) if os.path.isfile(filepath): if CONFIG['camshot_filetype'] == 'ppm': new_filepath = '{0}{1}{2}_webcam.jpg'.format( temp, SEP, filename) runprocess(['/usr/bin/convert', filepath, new_filepath]) os.unlink(filepath) filepath = new_filepath if not os.path.isfile(filepath): return None return filepath
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()
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)
def webcamshot(): ''' Takes a snapshot with the webcam and returns the path to the saved image (in TMP). None if could not take the snapshot. ''' if not CONFIG['Commands']['camshot']: LOG.info('Skipping webcamshot.') return None LOG.info('Taking webcamshot') try: if OS == 'Windows': filepath = '%s%c%s_webcam.jpg' % (TMP, SEP, FILENAME) from VideoCapture import Device cam = Device(devnum=0) if not cam: cam = Device(devnum=1) if not cam: LOG.error('Error while taking webcamshot: no device available.') return None #cam.setResolution(768, 576) # Here you can modify the picture resolution cam.getImage() time.sleep(1) cam.saveSnapshot(filepath) else: filepath = '%s%c%s_webcam.%s' % (TMP, SEP, FILENAME, CONFIG['Commands']['camshot_filetype']) cmd = CONFIG['Commands']['camshot'].replace('<filepath>', filepath) runprocess(cmd, useshell=True) if os.path.isfile(filepath): if CONFIG['Commands']['camshot_filetype'] == 'ppm': new_filepath = '%s%c%s_webcam.jpg' % (TMP, SEP, FILENAME) runprocess(['/usr/bin/convert', filepath, new_filepath]) os.unlink(filepath) filepath = new_filepath except Exception as ex: LOG.error(ex) return None if not os.path.isfile(filepath): return None return filepath
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))
class WebCam(object): def __init__(self, outfilename=None): if outfilename: self.outfilename = outfilename else: outfile = tempfile.NamedTemporaryFile(suffix='.png', delete=False) self.outfilename = outfile.name outfile.close() if WIN: self.cam = Device() elif LINUX: self.callargs = [GST_COMMAND, '-v', 'v4l2src', '!', #'video/x-raw-yuv,width=320,height=240,framerate=20/1', '!', 'decodebin', '!', 'ffmpegcolorspace', '!', 'pngenc', '!', 'filesink', 'location="%s"' % (self.outfilename)] def saveSnapshot(self): if WIN: self.cam.saveSnapshot(self.outfilename) elif LINUX: if 0 != subprocess.call(self.callargs): return False return self.outfilename
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()
def getSnapShot(): cam = Device() cam.saveSnapshot("image.jpg", timestamp=3, boldfont=1)
def webcam(): # say hi! if auth(request.args.get('password')) is False: return 'authfail' from VideoCapture import Device cam = Device() cam.saveSnapshot('./static/image.jpg') return 'Taken'
def takePicture(filename): cam = Device() cam.saveSnapshot(filename)
def face_detect(filePath): options = { 'max_face_num': 5, 'face_fields': 'age,beauty,expression,faceshape' } result = client.detect(get_file_content(filePath), options) return result def face_match(filePath): result = client.match( [get_file_content('father.jpg'), get_file_content(filePath)]) return result def get_img(): cam = Device() cam.saveSnapshot('father.jpg') if __name__ == '__main__': #print face_detect('face.jpg') cam = Device() filePath = 'last.jpg' cam.saveSnapshot(filePath) result = face_match(filePath) print result['result'][0]['score'] if result['result'][0]['score'] >= 80: print 1
#coding:utf-8 from VideoCapture import Device import time import sys, pygame pygame.init() size = width, height = 620, 485 speed = [2, 2] black = 0, 0, 0 pygame.display.set_caption('视频窗口') screen = pygame.display.set_mode(size) #抓取频率,抓取一次 sleep_time_long = 0.1 #初始化摄像头 cam = Device(devnum=0, showVideoWindow=0) while 1: #抓图 cam.saveSnapshot('test.jpg', timestamp=3, boldfont=1, quality=75) #加载图像 image = pygame.image.load('test.jpg') #传送画面 screen.blit(image, speed) #显示图像 pygame.display.flip() #休眠一下,等待一分钟 time.sleep(sleep_time_long)
import serial import requests import time import webbrowser import ftplib import os from VideoCapture import Device cam = Device() cam.saveSnapshot('temp.jpg') time.sleep(1) os.remove('temp.jpg') session = ftplib.FTP("127.0.0.1") session.login("root","sandy") session.cwd('dj/images') try: file = open('number.txt',"r") except: file = open('number.txt',"w") file.write('0') file.close() ser=serial.Serial('COM14',9600)
class Webcam(): def __init__(self, webcam_name=None, webcam_id=None, **kargs): #Instantiate the logger loggerObj = Logger(__name__) self.logger = loggerObj.getLoggerInstance() self.device = None self.logger.debug( '__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 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 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 disconnect(self): del self.device self.device = None def savePicture(self, path, iterations=20, keep_all=False): if keep_all: i = path.rfind('.') img = '%s%%s%s' % (path[:i], path[i:]) for i in range(iterations): if keep_all: self.device.saveSnapshot(img % i) if i == iterations - 1: self.device.saveSnapshot(path) else: self.device.saveSnapshot(path) def connected(self): return (self.device != None)
from VideoCapture import Device cam = Device() cam.saveSnapshot('image.jpg', timestamp=3, boldfont=1)
class TouchStream(Thread): 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 = [] def run(self): avgs1 = [] avgs2 = [] for i in xrange(0,640): avgs1.append((0,0,0)) avgs2.append((0,0,0)) startdone = 0 while 1: self.count += 1 self.cam2.saveSnapshot('temp/image' + str(self.count) + '.jpg', timestamp=3, boldfont=1) self.cam1.saveSnapshot('temp/2image' + str(self.count) + '.jpg', timestamp=3, boldfont=1) img1 = InImage("temp/image" + str(self.count) + ".jpg") img2 = InImage("temp/2image" + str(self.count) + ".jpg") red1 = 0 green1 = 0 blue1 = 0 red2 = 0 green2 = 0 blue2 = 0 row = 100 row2 = 100 lines = gareth.generate_lines(100,100,100, img1.nx) lines2 = gareth.generate_lines(100,100,100, img1.nx) touch_lines = [] for x in xrange(0,(img1.nx/2)): for y in xrange(row,row+1): red1 += img1[x,y][0] green1 += img1[x,y][1] blue1 += img1[x,y][2] for x in xrange((img1.nx/2), img1.nx): for y in xrange(row,row+1): red2 += img1[x,y][0] green2 += img1[x,y][1] blue2 += img1[x,y][2] red1 /= (img1.nx/2) green1 /= (img1.nx/2) blue1 /= (img1.nx/2) red2 /= (img1.nx/2) green2 /= (img1.nx/2) blue2 /= (img1.nx/2) smallest = 10000 biggest = -1 found = False for x in xrange(0,img1.nx): if x > (img1.nx / 2): red = red2 blue = blue2 green = green2 else: red = red1 blue = blue1 green = green1 reda = avgs1[x][0] greena = avgs1[x][1] bluea = avgs1[x][2] for y in xrange(row,row+1): ored,ogreen,oblue = img1[x,y] diff = abs(ored - reda) + abs(ogreen - greena) + abs(oblue - bluea) found = False hue, sat, var = colorsys.rgb_to_hsv(red, green, blue) hue2, sat2, var2 = colorsys.rgb_to_hsv(ored, ogreen, oblue) a,b,c = colorsys.rgb_to_yiq(red, green, blue) a1,b1,c1 = colorsys.rgb_to_yiq(ored, ogreen, oblue) diff = abs(hue - hue2) + abs(sat - sat2) + abs(var - var2) diff += abs(a - a1) + abs(b - b1) + abs(c - 1) if (diff > (100 + (abs(x - (img1.nx / 2)) / 600))): found = True #if (diff > 80): # found = True diff = abs(ored - red) + abs(ogreen - green) + abs(oblue - blue) if (found and (diff > (65 + (abs(x - (img1.nx / 2)) / 600)))): touch_lines.append(((0,-100), lines[img1.nx - 1 - x])) else: avgs1[x] = (ored, ogreen,oblue) startdone += 1 red1 = 0 green1 = 0 blue1 = 0 red2 = 0 green2 = 0 blue2 = 0 for x in xrange(0,(img2.nx/2)): for y in xrange(row2,row2+1): red1 += img2[x,y][0] green1 += img2[x,y][1] blue1 += img2[x,y][2] for x in xrange((img2.nx/2), img2.nx): for y in xrange(row2,row2+1): red2 += img2[x,y][0] green2 += img2[x,y][1] blue2 += img2[x,y][2] red1 /= (img2.nx/2) green1 /= (img2.nx/2) blue1 /= (img2.nx/2) red2 /= (img2.nx/2) green2 /= (img2.nx/2) blue2 /= (img2.nx/2) print red,green,blue for x in xrange(0,img2.nx): if x > (img2.nx / 2): red = red2 blue = blue2 green = green2 else: red = red1 blue = blue1 green = green1 reda = avgs2[x][0] greena = avgs2[x][1] bluea = avgs2[x][2] for y in xrange(row2,row2+1): ored,ogreen,oblue = img2[x,y] diff = abs(ored - reda) + abs(ogreen - greena) + abs(oblue - bluea) found = False hue, sat, var = colorsys.rgb_to_hsv(red, green, blue) hue2, sat2, var2 = colorsys.rgb_to_hsv(ored, ogreen, oblue) a,b,c = colorsys.rgb_to_yiq(red, green, blue) a1,b1,c1 = colorsys.rgb_to_yiq(ored, ogreen, oblue) diff = abs(hue - hue2) + abs(sat - sat2) + abs(var - var2) diff += abs(a - a1) + abs(b - b1) + abs(c - 1) if (diff > (100 + (abs(x - (img2.nx / 2)) / 500))): found = True #if (diff > 80): # found = True diff = abs(ored - red) + abs(ogreen - green) + abs(oblue - blue) if (found and (diff > (65 + (abs(x - (img2.nx / 2)) / 500)))): touch_lines.append(((100,-100), (100 - lines[x][0], lines[x][1]))) else: avgs2[x] = (ored, ogreen,oblue) self.return_lines = touch_lines #print str(num_diff), str(smallest), str(biggest) def isTouch(self): return self.return_lines
import time, string ## Specify the amount of seconds to wait between individual captures. interval = 2 ## If you get horizontal stripes or other errors in the captured picture ## (especially at high resolutions), try setting showVideoWindow=0. cam = Device(devnum=0, showVideoWindow=1) #cam = Device(devnum=1, showVideoWindow=1) ## Using the separate programs "setPropertiesDev0/1.pyw" before capturing ## works better for some devices. ## On the other hand, some devices don't remember their state, so the ## properties have to be set at every program start. cam.displayCapturePinProperties() #cam.displayCaptureFilterProperties() print "press 'ctrl + c' to terminate" i = 0 quant = interval * .1 starttime = time.time() while 1: lasttime = now = int((time.time() - starttime) / interval) #print i cam.saveSnapshot('C:\\Windows\\Temp\\' + string.zfill(str(i), 4) + '.jpg', timestamp=3, boldfont=1) i += 1 while now == lasttime: now = int((time.time() - starttime) / interval) time.sleep(quant)
#-*- coding:utf-8 -*- from VideoCapture import Device cam = Device() cam.setResolution(320, 240) #设置显示分辨率 cam.saveSnapshot('demo.jpg') #抓取并保存图片
import serial import requests import time import webbrowser import ftplib import os from VideoCapture import Device cam = Device() cam.saveSnapshot("temp.jpg") time.sleep(1) os.remove("temp.jpg") session = ftplib.FTP("127.0.0.1") session.login("root", "sandy") session.cwd("dj/images") try: file = open("number.txt", "r") except: file = open("number.txt", "w") file.write("0") file.close() ser = serial.Serial("COM14", 9600)
import sys, pygame pygame.init() size = width, height = 1280 , 720 speed = [2, 2] black = 0, 0, 0 pygame.display.set_caption('视频窗口@dyx1024') screen = pygame.display.set_mode(size) # 抓取频率,抓取一次 SLEEP_TIME_LONG = 0.1 # 初始化摄像头 cam = Device(devnum=0, showVideoWindow=0) while True: # 抓图 cam.saveSnapshot('test.jpg', timestamp=3, boldfont=1, quality=75) # 加载图像 image = pygame.image.load('test.jpg') # 传送画面 screen.blit(image, speed) # 显示图像 pygame.display.flip() # 休眠一下,等待一分钟 time.sleep(SLEEP_TIME_LONG)
class getEmotionDataThread(QThread): _url = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect' _key = '6f290054c72e42dd9d7779f4da63b84f' _maxNumRetries = 10 emotionData = pyqtSignal(str) exception = pyqtSignal() def __init__(self): QThread.__init__(self) try: self.webcam = Device() except Exception: self.webcam = None def run(self): if(self.webcam != None): while True: primaryEmotion = self.emotionCheck() self.emotionData.emit(primaryEmotion) self.sleep(5) else: self.exception.emit() def __del__(self): self.wait() def stop(self): self.terminate() self.webcam = None ##Send image to Microsoft Emotion API for analysing def processRequest(self, json, data, headers, params): self.retries = 0 self.result = None while True: response = requests.request( 'post', self._url, json = json, data = data, headers = headers, params = params ) if response.status_code == 429: print( "Message: %s" % ( response.json()['error']['message'] ) ) if self.retries <= self._maxNumRetries: time.sleep(1) self.retries += 1 continue else: print( 'Error: failed after retrying!' ) break elif response.status_code == 200 or response.status_code == 201: if 'content-length' in response.headers and int(response.headers['content-length']) == 0: self.result = None elif 'content-type' in response.headers and isinstance(response.headers['content-type'], str): if 'application/json' in response.headers['content-type'].lower(): self.result = response.json() if response.content else None elif 'image' in response.headers['content-type'].lower(): self.result = response.content else: print( "Error code: %d" % ( response.status_code ) ) print( "Message: %s" % ( response.json()['error']['message'] ) ) break return self.result ##Capture, prep and upload local image for emotion analysing, upload it, and receive result def emotionCheck(self): presidingEmotion = "No Face Detected" self.webcam.saveSnapshot('userImage.jpg') with open( 'userImage.jpg', 'rb' ) as f: data = f.read() headers = dict() headers['Ocp-Apim-Subscription-Key'] = self._key headers['Content-Type'] = 'application/octet-stream' json = None params = {'returnFaceAttributes': 'emotion',} result = self.processRequest( json, data, headers, params ) if result is not None: for currFace in result: print(currFace['faceAttributes']['emotion'].items()) presidingEmotion = max(currFace['faceAttributes']['emotion'].items(), key=operator.itemgetter(1))[0] return presidingEmotion
class Camera: def __init__(self): self.winName = "Dad CCTV" self.recording = False self.fps = 24 device = int(raw_input("Choose System Device: ")) self.cam = Device(devnum=device) def initFile(self): self.newpath = time.strftime("%d.%m.%y"+"\\") self.fileName = time.strftime("%H.%M.%S") self.getBaseFrame() self.startWriter() def record(self): self.initFile() print self.newpath if not os.path.exists(self.newpath): os.makedirs(self.newpath) self.recording = True print "Recording... Press Ctr-C to stop" try: self.write() except KeyboardInterrupt: print "Stopped Recording File Saved As: " + self.fileName self.cleanUp() def getCurrentTime(self): time = time.strftime("%H:%M:%S") def getBaseFrame(self): self.cam.saveSnapshot("1.jpg") def getFrame(self): return numpy.array(self.cam.getImage()) def getPILFrame(self): return self.cam.getImage() def startWriter(self): img = cv2.imread("1.jpg") height,width,layers = img.shape fourcc = cv2.VideoWriter_fourcc('M','J','P','G') self.videoWriter = cv2.VideoWriter(self.newpath+self.fileName+".avi",fourcc,self.fps,(width,height)) def record5Seconds(self): recording =True self.initFile() now = time.time() future = now + 5 while time.time() < future: self.write() else: self.cleanUp() def write(self): self.videoWriter.write(self.getFrame()) def cleanUp(self): recording = False self.videoWriter.release() def isRecording(self): return self.recording
def get_img(): cam = Device() cam.saveSnapshot('father.jpg')
def getWebcamSnapshot(webcamNum, snapshotName): from VideoCapture import Device cam = Device(webcamNum) cam.saveSnapshot(snapshotName)
for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() keyinput = pygame.key.get_pressed() # returns the status of every key pressed - tuple if keyinput[K_b]: brightness -= .1 if keyinput[K_n]: brightness += .1 if keyinput[K_c]: contrast -= .1 if keyinput[K_v]: contrast += .1 if keyinput[K_q]: cam.displayCapturePinProperties() if keyinput[K_e]: cam.displayCaptureFilterProperties() if keyinput[K_t]: filename = str(time.time()) + ".jpg" cam.saveSnapshot(filename, quality=80, timestamp=0) shots += 1 if event.type == KEYDOWN: # memorizing/recalling positions for i in range(0,10): if event.key == ord(str(i)): if pygame.key.get_mods() & KMOD_CTRL: # CTRL+X remmebers position print 'CTRL+',str(i),' pressed, microscope positioned remembered' MyUnit.remembered_positions[i,:]=MyUnit.get_motors_coord_um() remembered_position_index.append(i) remembered_position_index.sort()
SLEEP_TIME_LONG = 0.0 cam = Device(devnum=0, showVideoWindow=0) print cam filename = "test.jpg" while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit() elif event.type == KEYDOWN: key = pygame.key.get_pressed() if key[97]: filename = "test" + int(time.time() // 1).__str__() + ".jpg" print filename cam.saveSnapshot(filename, timestamp=3, boldfont=1, quality=55) elif event.type == MOUSEBUTTONDOWN: pass elif event.type == MOUSEMOTION: pass elif event.type == MOUSEBUTTONUP: pass #cam.getImage(0, 0, "bl") cmd = "shut" Image = pygame.image.load(filename) #screen.fill(0,0,200) screen.blit(Image, (0, 0)) pygame.display.update()
help="path to the (optional) video file") ap.add_argument("-b", "--buffer", type=int, default=10, help="max buffer size") args = vars(ap.parse_args()) #['--video','/home/pi/python/ankitha-tests/2_e.mp4']q # define the lower and upper boundaries of the "green" # ball in the HSV color space, then initialize the # list of tracked points blueLower = (18, 28, 71) blueUpper = (49, 255, 255) pts = deque(maxlen=args["buffer"]) # grab the reference to the webcam and video writer camera = Device() camera.saveSnapshot('colorTest.jpg') fourcc = cv2.cv.CV_FOURCC(*'MSVC') out = cv2.VideoWriter('centerLeft_8psi_trial4.avi',fourcc, 10, (600,450)) #set trap location trap = (538,224) #set traps being used (solenoid number) start = '1' end = '3' #allow warm up time.sleep(1) # keep looping count = 1
from VideoCapture import Device from functions import sid cam = Device() cam.saveSnapshot('photos\photo%s.jpg' %sid(), timestamp=3, boldfont=1)
## label_image.place(x=0,y=0,width=image1.size[0],height=image1.size[1]) ## root.title('Live Webcam') ## if old_label_image is not None: ## old_label_image.destroy() ## old_label_image = label_image ## root.mainloop() # wait until user clicks the window ## except Exception, e: ## # This is used to skip anything not an image. ## # Image.open will generate an exception if it cannot open a file. ## # Warning, this will hide other errors as well. ## pass # Save an snapshot taken with the webcam. cam.saveSnapshot('snapshot.jpg', only_show=True) # Delete the webcam instance that was generated; this will free the camera from Python, # if it is not deleted, the instance will remain until the script is restarted. del cam # The buffer that is generated from the image taken. # buf, width, height = cam.getBuffer() # cam.saveSnapshot(only_show=True) # time.sleep(5) # print "Length of buffer:", len(buf), "Width of image:", width, "Height of image:", height # args = ["ffmpeg.exe", "-y", "-f", "rawvideo", "-vcodec", "rawvideo", "-i", "-", "-an", "-vcodec", "mpeg"]
import math from VideoCapture import Device import time import os #http://pydoc.org/1.6/os.html import shutil import Image cam = Device() os.mkdir('IA') #cria pasta IA #funcao que captura as imagens da webcam usando a biblioteca VideoCapture for i in range(1,16): if i==1: tiraFoto = raw_input("pressione enter para tirar a foto base") cam.saveSnapshot('im%s.jpg' %i) #tira a foto e arquiva shutil.move("im%s.jpg" %i, "IA") #move im3 para IA, removendo de onde estava print "\n \n foto base arquivada" else: tiraFoto = raw_input("pressione enter para tirar a foto %s" %i) #apenas para o usuario ter controle do momento que vai tirar as fotos cam.saveSnapshot('im%s.jpg' %i) #tira a foto e arquiva shutil.move("im%s.jpg" %i, "IA") #move im3 para IA, removendo de onde estava print "\n \n foto %s arquivada" %i if i==15: print " A correlacao de pearson esta sendo calculada..." #for i in range(1,16): #funcao que pega as imagens da webcam #cam.saveSnapshot('im%s.jpg' % i)
#-*- coding:utf-8 -*- from VideoCapture import Device cam = Device() cam.setResolution(320,240) #设置显示分辨率 cam.saveSnapshot('demo.jpg') #抓取并保存图片
#! /usr/bin/env python #coding=utf-8 from VideoCapture import Device import time ISOTIMEFORMAT='%Y-%m-%d %X' while 1: cam = Device() cam.saveSnapshot('now.jpg') time.sleep(10) print time.strftime( ISOTIMEFORMAT, time.localtime() )
import cv if __name__ == "__main__": hc = cv.Load( "E:\\Software\\Notepad++\\PythonEnv\\haarcascade_frontalface_alt.xml") while True: pygame.init() pygame.display.set_caption('FaceDetection') screen = pygame.display.set_mode([620, 485]) #³õʼ»¯ÉãÏñÍ· cam = Device(devnum=0, showVideoWindow=0) #ץͼ cam.saveSnapshot('temp.jpg', timestamp=3, boldfont=1, quality=80) #Á³²¿Ê¶±ð image = cv.LoadImage('temp.jpg', cv.CV_LOAD_IMAGE_COLOR) face = cv.HaarDetectObjects(image, hc, cv.CreateMemStorage(), 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (0, 0)) for (x, y, w, h), n in face: # print("[(%d,%d) -> (%d,%d)]" % (x,y,x+w, y+h)) cv.Rectangle(image, (int(x), int(y)), (int(x) + w, int(y) + h), (255, 255, 255), 1, 0) cv.SaveImage('temp_detec.jpg', image) #¼ÓÔØͼÏñ image = pygame.image.load('temp_detec.jpg') #´«ËÍ»Ãæ screen.blit(image, [2, 2])
import cv2.cv as cv from VideoCapture import Device cam = Device() cam.saveSnapshot('image.jpg')
#encoding:utf-8 ''' Created on 2016-7-27 测试摄像头抓拍 @author: user ''' from VideoCapture import Device as CamDevice cam0 = CamDevice(0, False) cam0.saveSnapshot("F:\\sn0.jpg") cam1 = CamDevice(1, False) cam1.saveSnapshot("F:\\sn1.jpg") cam2 = CamDevice(2, False) cam2.saveSnapshot("F:\\sn2.jpg")