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): """[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("==================================================================================")
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 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)
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
class Camera(): # def __init__(self, dev=0): try: self.cam = Device(dev) except Exception as e: print e self.cam = 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
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()
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 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
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 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 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 get_image_VC(): from VideoCapture import Device cam = Device() cam.setResolution(800, 400) img = cam.getImage() return img
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 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 __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 = ""
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 getDevName(): namelst = [] sign = 1 i = -1 while sign: try: i += 1 cam = Device(i) namelst.append(cam.getDisplayName()) except: sign = 0 return namelst
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
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
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 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()
class MediaTrans: def __init__(self, sclint): self.audiobuffersize = 200 self.framerate = 3000 self.channels = 1 self.sampwidth = 2 self.vserverport = 9365 self.aserverport = 9366 self.netserverhost = "166.111.180.60" self.netserverport = 8000 self.mesport = 9355 self.vsendthread = 1 self.vreavthread = 1 self.asendthread = 1 self.areavthread = 1 self.ischatting = False self.chatlock = threading.Lock() self.chatuser = "" #正在聊天对象的学号 self.sclint = sclint #从外部传入的Socket,已经和服务器建立好连接 self.sclintlock = threading.Lock() # self.sendthread=threading.Thread(target=self.Send,name="SendThread",args=(cam,)) # self.sendthread.setDaemon(1) # self.sendthread.start() def SendVideo(self, username): userIp = "" self.sclintlock.acquire() try: self.sclint.sendall("q" + username) #查询在线状态 feebback = self.sclint.recv(1024) if not feebback.startswith('n') and not feebback.startswith('Ple'): userIp = feebback except Exception, e: print e self.sclintlock.release() if userIp == "": print "用户不在线或无法连接终止视频发送" return False cam = Device() vclints = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) vclints.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) while self.ischatting == True: im = cam.getImage() im = im.resize((160, 120)) da = im.tostring() vclints.sendto(da, (userIp, self.vserverport))
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 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
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 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]
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()