本文整理汇总了Python中VideoCapture.Device.getImage方法的典型用法代码示例。如果您正苦于以下问题:Python Device.getImage方法的具体用法?Python Device.getImage怎么用?Python Device.getImage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类VideoCapture.Device
的用法示例。
在下文中一共展示了Device.getImage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Webcam
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
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()
示例2: VCCamera
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
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
示例3: take_picture
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
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)
示例4: getImage
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
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
示例5: webcamshot
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
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
示例6: webcamshot
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
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
示例7: ImageCapture
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
class ImageCapture():
'''
图像采集类
'''
NoDeviceError = vidcap.error
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])
def get_frame_size(self):
'''
获取帧大小
@return: 帧的大小
'''
return self.size
def get_frame(self):
'''
获取当前帧
@return: 当前帧
'''
im_pil = self.cam.getImage().convert('RGB')
cvimg = np.array(im_pil)
return cvimg[:,:,::-1] # opencv的默认图像制式是 BGR
def release(self):
'''
释放摄像头
'''
print 'Release Camera'
del self.cam
示例8: webcamshot
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
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
示例9: Capture
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
class Capture(object):
"""Provides access to video devices."""
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 grabFrame(self):
"""Returns a snapshot from the device as PIL.Image.Image object."""
return self.dev.getImage()
def grabRawFrame(self):
"""Returns a snapshot from this device as raw pixel data.
This function returns a 4-tuple consisting of the raw pixel data as string,
the width and height of the snapshot and it's orientation, which is either
1 (top-to-bottom) or -1 (bottom-to-top).
"""
return self.dev.getBuffer + (-1,)
@staticmethod
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
示例10: do_both
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
def do_both():
L = []
i = 0
cam = Device()
thread.start_new_thread(input_thread, (L,))
photo = cam.getImage(3, 1, "tl")
photoWidth, photoHeight = photo.size
combinedImage = Image.new("RGB", (width + photoWidth, height), color=0)
startTime = time.time()
print "Press enter to stop."
while 1:
time.sleep(waitTime)
i = i + 1
istr = str(i)
combinedImage.paste(ImageGrab.grab(), (0, 0))
photo = cam.getImage(3, 1, "tl")
combinedImage.paste(photo, (width, 0))
draw = ImageDraw.Draw(combinedImage)
font = ImageFont.truetype("arialbd.ttf", 40)
draw.rectangle([(width, photoHeight), (width + photoWidth, photoHeight + height - photoHeight)], fill="black",
outline="red")
draw.text((width + 10, photoHeight + 10), datetime.now().strftime("%A, %d. %B %Y %I:%M%p"), (255, 255, 255),
font=font)
elapsed = time.time() - startTime
m, s = divmod(elapsed, 60)
h, m = divmod(m, 60)
formattedElapsed = "%d:%02d:%02d" % (h, m, s)
draw.text((width + 10, photoHeight + 60), formattedElapsed, (255, 255, 255), font=font)
combinedImage.save("imgs/" + istr + ".png")
# combinedImage.save("imgs/" + timestamp() + ".png")
print "saved" + istr
if L:
main()
break
示例11: camera
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
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()
示例12: CameraManager
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
class CameraManager(threading.Thread):
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
#self.camera.displayCapturePinProperties()
def stop(self):
self.should_stop.set()
def run(self):
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(("", 23457))
self.sock.listen(5)
while 1:
client, addr = self.sock.accept()
log("Camera connection")
self.client = client
break
fpsm = FPSMeter()
while 1:
if self.should_stop.isSet():
return
print fpsm.tick()
wait(self.freq)
data = self.get_image()
data_len = len(data)
self.client.send(pack("!I%ds" % data_len, data_len, data))
def get_image(self):
io = StringIO.StringIO()
image = self.camera.getImage().resize(self.size)
image.save(io, "JPEG", quality = 75, optimize = True)
data = io.getvalue()
io.close()
return data
示例13: MTVideoCaptureCamera
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
class MTVideoCaptureCamera(MTCameraBase):
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)
def capture_frame(self):
try:
self.frame = self.capture_device.getImage()
#pymt_logger.info("Format:" + )
self.format = GL_RGB
self.buffer = self.frame.tostring();
self.copy_buffer_to_gpu()
except Exception, e:
pymt_logger.exception("Couldn't get Image from Camera!"+ str(e))
示例14: main
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
def main():
cam = Device()
print "Getting initial image, and adjusting camera..."
initialImage = adjustCamera( cam )
initialImage.save('initialImage.jpg')
print "initial image saved and webcam adjusted..."
recordedImages = [initialImage]
end = False
while True:
time.sleep(.2)
newImage = cam.getImage()
compared = compare_images( initialImage, newImage, 70, ANY_2RGB )
amtPxChanged = totalChange( compared )
if amtPxChanged > 20000:
print "Recording..."
print amtPxChanged
# time.sleep(.2)
recordedImages.append( newImage )
compared.save('recording.jpg')#' + str(imgNum) + '.jpg')
end = True
## elif end:
## break
else:
print "not recording..."
compared.save('recording.jpg')
示例15: get_image
# 需要导入模块: from VideoCapture import Device [as 别名]
# 或者: from VideoCapture.Device import getImage [as 别名]
def get_image():
cam = Device(0)
return cam.getImage(1)