Esempio n. 1
0
class MyVideoCapture:
    def __init__(self, video_source=0, ser_num=0):
        self.vs = video_source
        if (video_source == 0):
            # Open the video source
            self.vid = cv2.VideoCapture(video_source)
            if not self.vid.isOpened():
                raise ValueError("Unable to open video source", video_source)

            # Get video source width and height
            self.width = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)
            self.height = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
        else:
            self.live = False
            self.color = False
            self.stop_video = threading.Event()
            self.ser_num = ser_num
            self.exposure = 3.16
            self.filter = (255, 255, 255)
            self.width = 640
            self.height = 512
            self.terminate = False
            self.rec_state = 0
            self.cap_state = 0
            self.init_camera()
            self.stopEvent = threading.Event()
            self.thread = threading.Thread(target=self.videoLoop, args=())
            self.thread.start()
            while (True):
                time.sleep(0.001)
                if (self.live == True):
                    break

    def set_filter(self, filter):
        if (filter != None):
            self.filter = filter

    def set_color(self, color):
        self.cam.color_gray(color)

    def set_exposure(self, exposure):
        self.exposure = (pow(10.0, (exposure + 20.0) / 10.0)) / 1000.0
        self.cam.set_exposure(self.exposure)

    def capture(self, directory):
        if not os.path.exists(directory + "/images"):
            os.makedirs(directory + "/images")
        self.cap_state = 1
        self.directory = directory

    def set_rec_state(self, state, directory):
        if (state == 1):
            if not os.path.exists(directory + "/videos"):
                os.makedirs(directory + "/videos")
            fourcc = cv2.VideoWriter_fourcc(*'XVID')
            self.out = cv2.VideoWriter(
                directory + "/videos/video-" +
                time.strftime("%d-%m-%Y-%H-%M-%S") + ".avi", fourcc,
                self.frame_rate, (640, 512))
        else:
            self.out.release()
        self.rec_state = state

    def init_camera(self):
        ns = locate_ns(host="camacholab.ee.byu.edu")
        objs = str(ns.list())
        while (True):
            temp_str = objs[objs.find('\'') + 1:-1]
            temp_obj = temp_str[0:temp_str.find('\'')]
            if (temp_obj[0:5] == "UC480"):
                temp_ser_no = int(temp_obj[6:len(temp_obj)])
                if (temp_ser_no == self.ser_num):
                    cam_str = temp_obj
            if (objs.find(',') == -1):
                break
            objs = objs[objs.find(',') + 1:-1]
        try:
            cam_str
        except NameError:
            raise Exception("Camera with serial number " + str(self.ser_num) +
                            " could not be found")
        self.cam = Proxy(ns.lookup(cam_str))

        self.cam.start(exposure=65)
        ip_address = self.cam.start_capture(self.color)
        self.clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.clientsocket.connect((str(ip_address), PORT))

        self.time_s = 0
        self.frame_rate = 0
        self.count = -1

    def bayer_convert(self, bayer):
        if (self.color):
            ow = (bayer.shape[0] // 4) * 4
            oh = (bayer.shape[1] // 4) * 4

            R = bayer[0::2, 0::2]
            B = bayer[1::2, 1::2]
            G0 = bayer[0::2, 1::2]
            G1 = bayer[1::2, 0::2]
            G = G0[:oh, :ow] // 2 + G1[:oh, :ow] // 2
            bayer_R = np.array(R, dtype=np.uint8).reshape(512, 640)
            bayer_G = np.array(G, dtype=np.uint8).reshape(512, 640)
            bayer_B = np.array(B, dtype=np.uint8).reshape(512, 640)

            dStack = np.clip(
                np.dstack(
                    (bayer_B * (BRIGHTNESS / 5), bayer_G * (BRIGHTNESS / 5),
                     bayer_R * (BRIGHTNESS / 5))), 0, 255).astype('uint8')
        else:
            bayer_T = np.array(bayer, dtype=np.uint8).reshape(512, 640)
            dStack = np.clip((np.dstack(
                ((bayer_T * (self.filter[2] / 255)) * (BRIGHTNESS / 5),
                 (bayer_T * (self.filter[1] / 255)) * (BRIGHTNESS / 5),
                 (bayer_T * (self.filter[0] / 255)) * (BRIGHTNESS / 5)))), 0,
                             255).astype('uint8')
            #dStack = np.clip((np.dstack(((0.469 + bayer_T*0.75 - (bayer_T^2)*0.003)*(BRIGHTNESS/5),(bayer_T*0.95)*(BRIGHTNESS/5),(0.389 + bayer_T*1.34 - (bayer_T^2)*0.004)*(BRIGHTNESS/5)))),0,255).astype('uint8')
        #dStack = np.clip(np.dstack((bayer,bayer,bayer)),0,255).astype('uint8')
        return dStack

    def videoLoop(self):
        while not self.stop_video.is_set():
            if (self.count >= 0):
                t = time.time() - self.time_s
                self.frame_rate = (self.frame_rate * self.count +
                                   1 / t) / (self.count + 1)

            self.time_s = time.time()
            if (self.count < 50):
                self.count = self.count + 1
            else:
                self.count = 1

            msg = b''
            new_msg = True
            msg_len = None
            imList = None
            while True:
                if new_msg:
                    sub_msg = self.clientsocket.recv(HEADERSIZE)
                    msg_len = int((sub_msg[:HEADERSIZE]))
                    new_msg = False
                else:
                    sub_msg = self.clientsocket.recv(32800)
                    msg += sub_msg
                    if len(msg) == msg_len:
                        imList = pickle.loads(msg)
                        break

            if (imList.size == 327680):
                self.color = False
                self.count = 0
            else:
                self.color = True
                self.count = 0
            dStack = self.bayer_convert(imList)

            if (self.cap_state == 1):
                cv2.imwrite(
                    self.directory + "/images/frame-" +
                    time.strftime("%d-%m-%Y-%H-%M-%S") + ".jpg", dStack)
                self.cap_state = 0

            if (self.rec_state == 1):
                self.out.write(dStack)

            self.frame = cv2.cvtColor(dStack, cv2.COLOR_BGR2RGB)

            if (self.terminate == True):
                self.clientsocket.send(b'b')
                self.live = False
                break
            self.clientsocket.send(b'g')
            self.live = True

    def get_frame(self):
        if (self.vs == 0):
            if self.vid.isOpened():
                ret, frame = self.vid.read()
                if ret:
                    # Return a boolean success flag and the current frame converted to BGR
                    return (ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
                else:
                    return (ret, None)
            else:
                return (ret, None)
        else:
            return (True, self.frame)

    # Release the video source when the object is destroyed
    def __del__(self):
        if (self.vs == 0):
            if self.vid.isOpened():
                self.vid.release()
        else:
            self.terminate = True
            while (True):
                time.sleep(0.001)
                if (self.live == False):
                    break
            self.cam.close()
            self.stop_video.set()
            try:
                self.out.release()
            except AttributeError:
                pass
Esempio n. 2
0
# -*- coding: utf-8 -*-
#
# Copyright © PyroLab Project Contributors
# Licensed under the terms of the GNU GPLv3+ License
# (see pyrolab/__init__.py for details)
"""
Kinesis KCube Driver Example
============================

This example demonstrates the use of the Thorlabs KCube DC Servo controlling a 
Z825B translational stage using PyroLab. 
"""

from pyrolab.api import NameServerConfiguration, Proxy, locate_ns

nscfg = NameServerConfiguration(host="yourdomain.com")
nscfg.update_pyro_config()

# Be considerate; don't stay connected to the nameserver too long.
with locate_ns() as ns:
    motor = Proxy(ns.lookup("Z825B_PyroName"))

motor.autoconnect()
print(motor.get_position())
motor.close()