Exemple #1
0
#
# 2009, 2010 Fredrik Portstrom
#
# I, the copyright holder of this file, hereby release it into the
# public domain. This applies worldwide. In case this is not legally
# possible: I grant anyone the right to use this work for any
# purpose, without any conditions, unless such conditions are
# required by law.

from PIL import Image
import select
import time
import v4l2capture

# Open the video device.
video = v4l2capture.Video_device("/dev/video0")

# Suggest an image size to the device. The device may choose and
# return another size if it doesn't support the suggested one.
size_x, size_y = video.set_format(1280, 1024)

# Create a buffer to store image data in. This must be done before
# calling 'start' if v4l2capture is compiled with libv4l2. Otherwise
# raises IOError.
video.create_buffers(1)

# Start the device. This lights the LED if it's a camera that has one.
video.start()

# Wait a little. Some cameras take a few seconds to get bright enough.
time.sleep(2)
Exemple #2
0
import pyqtgraph as pg
import pyqtgraph.ptime as ptime
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.console
import cv2
import numpy as np
import imutils
import v4l2capture
import select
from pyqtgraph.dockarea import *

workspace_Xmax, workspace_Ymax = 400, 400 # Maximum workspace in millimeter

### Camera init ###
width, height = 1920, 1080
cap = v4l2capture.Video_device("/dev/video2")
size_x, size_y = cap.set_format(width, height, fourcc='MJPG')
cap.create_buffers(1)
cap.queue_all_buffers()
cap.start()
### UI init ###
app = QtGui.QApplication([])
win = QtGui.QMainWindow()
area = DockArea()
win.setCentralWidget(area)
win.resize(1920,1080)
win.setWindowTitle('Pony Slayer: Mile Stone I')

updateTime = ptime.time()
fps = 0
mousePoint = None
Exemple #3
0
if args.multilog == 'false':
    args.multilog = False
else:
    args.multilog = True
print(args)
log_file = 'video{}-error.log'.format(args.device_id)
if os.path.exists(log_file):
    print(os.popen('tail -100 {}'.format(log_file)).read())
    os.remove(log_file)
logging.basicConfig(filename=log_file, level=logging.INFO)

cams = os.popen('ls /dev/video*').read().split()

# Open the video device.

video = v4l2capture.Video_device(cams[args.device_id])
# config
if args.auto_mode:
    video.set_exposure_auto(3)  # 设置为手动曝光模式 1是手动 3是自动
else:
    video.set_exposure_auto(1)
    video.set_exposure_absolute(args.exp)  # 设置曝光参数
video.set_auto_white_balance(1)  # 设置白平衡
size_x, size_y = video.set_format(args.width, args.height,
                                  fourcc='MJPG')  # 设置图像分辨率

# dpath = "video{}-save-file".format(args.device_id)
dpath = "video-save-file"


def create_dir(dpath):
Exemple #4
0
import re
import numpy as np
import cv2

fnames = glob.glob(sys.argv[1] + "/*.jpg")
ids = [
    int(_) for _ in filter(lambda t: t,
                           [re.findall(ur'0+(\d*)', _)[0] for _ in fnames])
]
next_id = max(ids) + 1 if ids else 1
print next_id

v_num = 1 if len(sys.argv) < 3 else int(sys.argv[2])
vids = range(v_num)
# Open the video device.
videos = [v4l2capture.Video_device("/dev/video%s" % _) for _ in vids]

# Suggest an image size to the device. The device may choose and
# return another size if it doesn't support the suggested one.
for video in videos:
    size_x, size_y = video.set_format(1920, 1080)

    video.create_buffers(1)

    video.start()
# Create a buffer to store image data in. This must be done before
# calling 'start' if v4l2capture is compiled with libv4l2. Otherwise
# raises IOError.

# Start the device. This lights the LED if it's a camera that has one.
Exemple #5
0
def detect():
    url = "http://192.168.0.27:5000/face/detect"
    capture_name = 'video1'
    try:
        camera = v4l2capture.Video_device('/dev/' + capture_name)
        camera.set_format(1280, 720)
        camera.create_buffers(10)
        camera.start()
    except IOError:
        print("No such file or directory: /dev/" + capture_name)
    time.sleep(2)
    camera.queue_all_buffers()

    top = 270
    left = 350
    down = 719
    right = 780

    while True:
        start_time = time.time()
        readable, _, _ = select.select([camera], (), ())
        for camera in readable:
            image_data = camera.read_and_queue()
            image = Image.frombytes("RGB", (1280, 720), image_data)
            img = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
            img_crop = img[top:down, left:right]
            img_encode = cv2.imencode('.jpg', img_crop)[1]

            b64encode_start_time = time.time()
            base64_data = base64.b64encode(img_encode)
            b64encode_elapsed_time = time.time() - b64encode_start_time

            base64_data_string = base64_data.decode()
            timestamp = int(round(time.time() * 1000))
            image_name = datetime.datetime.now().strftime(
                '%Y_%m_%d_%H_%M_%S') + '_' + str(timestamp) + ".jpg"
            json_data = {}
            json_data['image_name'] = image_name
            json_data['image_data'] = base64_data_string
            headers = {'Content-Type': 'application/json'}
            data = json.dumps(json_data)

            request_start_time = time.time()
            req = urllib2.Request(url, headers=headers, data=data)
            resp = urllib2.urlopen(req).read().decode()
            request_elapsed_time = time.time() - request_start_time

            resp_data = json.loads(resp)
            if resp_data['face_count'] > 0:
                image.save('./Images/' + str(timestamp) + ".jpg")
            '''
			img = cv2.imread(image_path)
			for i in range(resp_data['face_count']):
				face_node = resp_data['face_list'][i]	
				left_up_x = face_node['x']
				left_up_y = face_node['y']
				right_down_x = face_node['x'] + face_node['width']
				right_down_y = face_node['y'] + face_node['height']
				cv2.rectangle(img, (left_up_x, left_up_y), (right_down_x, right_down_y), (255,0,0), 3)
			cv2.imwrite(os.path.join('Images', image_name), img)
			'''
        elapsed_time = time.time() - start_time
        print("\n")
        print("elapsed_time: %dms" % (int(round(elapsed_time * 1000))))
Exemple #6
0
#!/usr/bin/env python

import numpy as np
import cv2
import os
import v4l2capture
import select
#import imutils

if __name__ == '__main__':
    #cap = cv2.VideoCapture(0)
    #cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 1920)      # <-- this doesn't work. OpenCV tries to set VIDIO_S_CROP instead of the frame format
    #cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 1080)

    # Open the video device.
    video = v4l2capture.Video_device("/dev/video1")
    video1 = v4l2capture.Video_device("/dev/video2")
    video2 = v4l2capture.Video_device("/dev/video3")
    video3 = v4l2capture.Video_device("/dev/video4")

    #set FPS
    # video.set_fps(30)
    # video1.set_fps(30)

    #set RESOLUTION
    size_x, size_y = video.set_format(768, 1024, fourcc='MJPG')
    size_x, size_y = video1.set_format(768, 1024, fourcc='MJPG')
    size_x, size_y = video2.set_format(768, 1024, fourcc='MJPG')
    size_x, size_y = video3.set_format(768, 1024, fourcc='MJPG')
    print "device chose {0}x{1} res".format(size_x, size_y)
Exemple #7
0
        self.thread = WebcamThread(*args, **kwargs)
        self.thread.start()

    def capture(self, *args, **kwargs):
        self.thread.capture(*args, **kwargs)

    def get_img(self, *args, **kwargs):
        return self.thread.get_img(*args, **kwargs)

    def close(self):
        self.thread.close()
        self.thread.join()


if __name__ == "__main__":
    import os
    file_names = [x for x in os.listdir("/dev") if x.startswith("video")]
    file_names.sort()
    for file_name in file_names:
        path = "/dev/" + file_name
        print path
        try:
            video = v4l2capture.Video_device(path)
            driver, card, bus_info, capabilities = video.get_info()
            print "    driver:       %s\n    card:         %s" \
                "\n    bus info:     %s\n    capabilities: %s" % (
                    driver, card, bus_info, ", ".join(capabilities))
            video.close()
        except IOError, e:
            print "    " + str(e)
Exemple #8
0
import v4l2capture
import numpy as np
import sys
import os
import cv2 as cv
import shutil
import time
import pygame.camera as camera

camera.init()
cams = camera.list_cameras()

# Open the video device.
num = sys.argv[1]
val = int(sys.argv[2])
video = v4l2capture.Video_device(cams[int(num)])
# config
video.set_exposure_auto(1)
video.set_exposure_absolute(val)
video.set_auto_white_balance(1)
#video.set_white_balance_temperature(4600)
#video.set_focus_auto(1)
size_x, size_y = video.set_format(3264, 2448, fourcc='MJPG')

dpath = "press_save" + num

if not os.path.exists(dpath):
    os.mkdir(dpath)
'''
if os.path.exists(dpath):
    shutil.rmtree(dpath)
Exemple #9
0
def cap(f, w, h):
    i = 0
    while i < 10:
        try:

            video = v4l2capture.Video_device("/dev/video0")
            #size_x, size_y = video.set_format(640, 480,fourcc = 'MJPG')
            size_x, size_y = video.set_format(640, 480)
            video.set_fps(1)
            video.create_buffers(1)
            video.queue_all_buffers()
            video.start()

            print('cap 1')
            #time.sleep(1)
            select.select((video, ), (), ())
            print('cap 2')
            #image_data = video.read_and_queue()
            image_data = video.read()
            video.close()
            print('cap 3')
            image = Image.frombytes("RGB", (size_x, size_y), image_data)
            image.save(f)
            #f = open(f,'wb')
            #f.write(image_data)
            print('cap 4')
            print "Saved ", f, "(Size: " + str(size_x) + " x " + str(
                size_y) + ")"
            return 0, size_x, size_y

        except Exception as e:
            print 'exception 1:', str(e)

            try:
                video.close()
            except Exception as e:
                print('exception 2', str(e))

            try:
                print('try to reset camera to recovery')
                #os.system('rm usb.txt')
                os.system('lsusb > usb.txt')
                f2 = open('usb.txt', 'rb')
                s = f2.read()
                f2.close()
                s2 = s.split('\n')
                #print(s2)
                for d in s2:
                    #print d
                    if d.find('Sunplus') > 0:
                        s3 = d.split(' ')
                        bus_cam = s3[1][0:3]
                        dev_cam = s3[3][0:3]

                        #print('cam Bus:',bus_cam)
                        #print('cam Dev:',dev_cam)
                        reset_cmd = './reset /dev/bus/usb/' + bus_cam + '/' + dev_cam
                        #print('reset_cmd:',reset_cmd)

                os.system(reset_cmd)
                print('reset usb cam:', reset_cmd)
                #time.sleep(3)
            except Exception as e:
                print('exception 3', str(e))

            i += 1

    return -1, 0, 0
Exemple #10
0
# required by law.

from PIL import Image
import select
import v4l2capture
import numpy as np
import sys

#需要输入两个参数
'''
example:python3 capture_picture.py 0 700 
'''
# Open the video device.
num=sys.argv[1]  
val =int(sys.argv[2]) #设置曝光值
video = v4l2capture.Video_device("/dev/video{}".format(num)) 
video.set_exposure_auto(1)
video.set_exposure_absolute(val)
# Suggest an image size to the device. The device may choose and
# return another size if it doesn't support the suggested one.
size_x, size_y = video.set_format(3364, 2448)

# Create a buffer to store image data in. This must be done before
# calling 'start' if v4l2capture is compiled with libv4l2. Otherwise
# raises IOError.
video.create_buffers(10)

# Send the buffer to the device. Some devices require this to be done
# before calling 'start'.
video.queue_all_buffers()
Exemple #11
0
    def run(self):
        state = np.matrix('0.0;0.0;0.0;0.0') # x, y, xd, yd,

        # P and Q matrices for EKF
        P = np.matrix('10.0,0.0,0.0,0.0; \
                    0.0,10.0,0.0,0.0; \
                    0.0,0.0,10.0,0.0; \
                    0.0,0.0,0.0,10.0' )


        Q = np.matrix('2.0,0.0,0.0,0.0; \
                    0.0,2.0,0.0,0.0; \
                    0.0,0.0,2.0,0.0; \
                    0.0,0.0,0.0,2.0')

        measurement = np.matrix('0;0')
        np.set_printoptions(formatter={'float': lambda x: "{0:0.2f}".format(x)})

        # print basic info
        print('python ' + platform.python_version())
        print('opencv ' + cv2.__version__)
        print('numpy ' + np.version.version)



        # def main():
        # open camera

        video = v4l2capture.Video_device("/dev/video0")
        size_x, size_y = video.set_format(FRAME_WIDTH, FRAME_HEIGHT, fourcc='MJPG')
        video.create_buffers(1)
        video.queue_all_buffers()
        video.start()
        start_time = time.time()

        prev_time = time.time()
        i = 0
        counter = 0
        stop_time = time.time() + 10
        while(True):
            if time.time() > stop_time:
                break

            now_time = time.time()
            dt = now_time - prev_time

            i+=1
            counter += 1
            # run the model every 0.01 s
            if (dt > 0.005):
                prev_time = now_time

                state, P, J = run_EKF_model(state, P, Q, dt)

            # read camera
            # ret, frame = cap.read()
            select.select((video,), (), ())
            image_data = video.read_and_queue()
            raw_image = np.fromstring(image_data, dtype='uint8')
            frame = cv2.imdecode(raw_image, cv2.IMREAD_UNCHANGED)
            # frame = cv2.imdecode(np.frombuffer(image_data, dtype=np.uint8), cv2.IMREAD_COLOR)
            ret = True;
            print("frame: {}".format(i))
            if ret == True:

                # For initilization, process the whole image, otherwise, utilize the predicted position
                if i < 10:
                    mask, cimg, (x,y,r) = recognize_center_without_EKF(frame)
                else:
                    mask, cimg, (x,y,r) = recognize_center(frame,state[0],state[1])

                # if i == 5:
                #     break
                # if x==0:
                #     continue
                measurement[0] = x
                measurement[1] = y
                if(measurement[0] != 0) and (measurement[1] != 0):
                    print("run EKF")
                    state, P = run_EKF_measurement(state, measurement, P)
                else:
                    print("no motion detected, continue")
                    # i = 0
                    # continue
                print("x: {}, state 0: {}".format(x,state[0]))
                if(x != 0):
                    cv2.circle(cimg, (int(x), int(y)), 50, (255), 5)

                if(state[0] != 0):
                    cv2.circle(cimg, (int(state[0]),int(state[1])), 20, (255), 3)

                msg = camera_pose_xyt_t()
                msg.x = state[0]
                msg.y = state[1]
                self.lc.publish("CAMERA_POSE_CHANNEL", msg.encode())
                # pixel_coord = np.array([state[0],state[1],1])
                # world_2d_coord = transform_camera_to_2d(pixel_coord)
                # print(world_2d_coord)
                # cv2.imshow('all',cimg)

            # close
            if cv2.waitKey(0) & 0xFF == ord('q'):
                break


        print("Time {}, frames: {}".format(time.time()-start_time, counter))
        # clean up
        video.close()
        cv2.destroyAllWindows()
Exemple #12
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--delay",
        default=0,
        dest="delay",
        help="Number of seconds to wait between starting the camera and taking "
        "the picture. Some cameras take a few seconds to get bright enough. "
        "[default: %(default)s]",
        type=float)
    parser.add_argument(
        "--image-size-x",
        default=1280,
        dest="image_size_x",
        help="The width of the image to capture. [default: %(default)s]",
        type=int)
    parser.add_argument(
        "--image-size-y",
        default=1024,
        dest="image_size_y",
        help="The height of the image to capture. [default: %(default)s]",
        type=int)
    parser.add_argument("--quiet", action="store_true", dest="quiet")
    parser.add_argument(
        "--output",
        default="image.jpg",
        dest="output_path",
        help="Path of the image file to save. [default: %(default)s]")
    parser.add_argument(
        "--video-device",
        default="/dev/video0",
        dest="video_device_path",
        help="Path of the video device to open. [default: %(default)s]")
    options = parser.parse_args()

    # Open the video device.
    video = v4l2capture.Video_device(options.video_device_path)

    # Suggest an image size to the device. The device may choose and
    # return another size if it doesn't support the suggested one.
    size_x, size_y = video.set_format(options.image_size_x,
                                      options.image_size_y)

    # Create a buffer to hold image data. This must be done before calling
    # 'start' if v4l2capture is compiled with libv4l2. Otherwise raises IOError.
    video.create_buffers(1)

    if options.delay:
        # Start the device. This lights the LED if it's a camera that has one.
        video.start()

        # Wait a little. Some cameras take a few seconds to get bright enough.
        time.sleep(options.delay)

        # Send the buffer to the device.
        video.queue_all_buffers()
    else:
        # Send the buffer to the device. Some devices require this to be done
        # before calling 'start'.
        video.queue_all_buffers()

        # Start the device. This lights the LED if it's a camera that has one.
        video.start()

    # Wait for the device to fill the buffer.
    select.select((video, ), (), ())

    # The rest is easy :-)
    image_data = video.read()
    video.close()
    image = Image.frombytes("RGB", (size_x, size_y), image_data)
    image.save(options.output_path)
    if not options.quiet:
        print "Saved file '%s' (Size: %s x %s)" % (options.output_path, size_x,
                                                   size_y)
    img = Image.fromarray(mask)
    img = img.resize((120, 120), Image.ANTIALIAS)
    img = np.array(img).astype(np.float32)
    img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    img = img.transpose((2, 0, 1))
    img = img[(2, 1, 0), :, :] / 255.0
    img = np.expand_dims(img, axis=0)
    return img


if __name__ == "__main__":
    cout = 0
    save_path = path + "/model/" + save_path

    video = v4l2capture.Video_device(camera)
    video.set_format(424, 240, fourcc='MJPG')
    video.create_buffers(1)
    video.queue_all_buffers()
    video.start()

    place = fluid.CPUPlace()
    exe = fluid.Executor(place)
    exe.run(fluid.default_startup_program())
    [infer_program, feeded_var_names,
     target_var] = fluid.io.load_inference_model(dirname=save_path,
                                                 executor=exe)

    vel = int(vels)
    lib_path = path + "/lib" + "/libart_driver.so"
    so = cdll.LoadLibrary
Exemple #14
0
vid_dev="/dev/video0"
if len(sys.argv) > 1: led_dev = sys.argv[1]
if len(sys.argv) > 2: vid_dev = sys.argv[2]
if len(sys.argv) > 3: width   = sys.argv[3]
if len(sys.argv) > 4: height  = sys.argv[4]

if len(sys.argv) > 1 and (sys.argv[1] == '-h' or sys.argv[1] == '-?' or sys.argv[1] == '--help'):
  print "v4l2capture_dots.py V"+version
  print "\nUsage: %s [led_dev [video_dev [width [height]]]]" % sys.argv[0]
  print "\ndefaults:\n\tled_dev=%s\n\tvideo_dev=%s\n\twidth=%d\n\theight=%d" % (led_dev, vid_dev, width, height)

# Open the LED_controller
kachel = lumitile.lumitile(port=led_dev, base=1)

# Open the video device.
video = v4l2capture.Video_device(vid_dev)

def image_to_dots(img, w=10, h=None, rows=2, pad=0, hflip=False, vflip=False):
  if h == None:
    # h = 3 * rows + 2    # we watch a third around the center. Two lines border minimum.
    h = int((2*pad+w)/4.*3.)
  strip=img.resize((w,h))
  # strip.save("image.jpg")
  # print "Saved image.jpg (Size: " + str(size_x) + " x " + str(size_y) + ")"
  min_rgb = 255
  max_rgb = 0

  y = int((h-rows)/2)

  for x in range(pad,pad+width):
    for r in range(rows):