示例#1
0
def main():
    camera_server = CameraServer.getInstance()
    camera_server.enableLogging()
    # TODO Use device addresses and sides here please

    cargo_camera = UsbCamera(name=CameraConfig.cargo_name,
                             path=CameraConfig.cargo_dev_address)
    hatch_camera = UsbCamera(name=CameraConfig.hatch_name,
                             path=CameraConfig.hatch_dev_address)
    front_camera = camera_server.startAutomaticCapture(
        name=CameraConfig.front_name, path=CameraConfig.front_dev_address)

    switching_server = camera_server.addSwitchedCamera("Switched")
    switching_server.setSource(hatch_camera)

    # Use networktables to switch the source
    # -> obviously, you can switch them however you'd like
    def _listener(source, key, value, isNew):
        if str(value) == "0":
            switching_server.setSource(hatch_camera)
        elif str(value) == "1":
            switching_server.setSource(cargo_camera)

    network_table = networktables.NetworkTables.getTable("/CameraPublisher")
    network_table.putString("Selected Camera", "0")
    network_table.addEntryListener(_listener, key="Selected Camera")

    camera_server.waitForever()
示例#2
0
def main():

    NetworkTables.initialize("10.68.51.2")

    LineDetect = DetectGreenTape()
    value = 0
    sd = NetworkTables.getTable("SmartDashboard")
    ntinst = NetworkTablesInstance.getDefault()
    ntinst.startServer()

    inst = CameraServer.getInstance()
    camera1 = UsbCamera(
        "Camera1",
        "/dev/v4l/by-path/platform-3f980000.usb-usb-0:1.2:1.0-video-index0")
    camera2 = UsbCamera(
        "Camera2",
        "/dev/v4l/by-path/platform-3f980000.usb-usb-0:1.1.3:1.0-video-index0")
    camera1.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)
    camera2.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    usb1 = inst.startAutomaticCapture(camera=camera1)
    usb2 = inst.startAutomaticCapture(camera=camera2)
    usb1.setResolution(320, 240)
    usb2.setResolution(320, 240)
    cvSink = inst.getVideo(camera=camera2)
    img = np.zeros(shape=(240, 320, 3), dtype=np.uint8)
    while True:
        timestamp, img = cvSink.grabFrame(img)
        LineDetect.process(img)
        sd.putNumber('NbLinesDetectedNew', len(LineDetect.filter_lines_output))
        Xmean1 = 0
        Xmean2 = 0
        Ymean1 = 0
        Ymean2 = 0
        angle = 0
        nbLigne = len(LineDetect.filter_lines_output)
        for ligne in LineDetect.filter_lines_output:
            Xmean1 += ligne.x1
            Xmean2 += ligne.x2
            Ymean1 += ligne.y1
            Ymean2 += ligne.y2
            angle += ligne.angle()

        if nbLigne:
            Ymean1 /= nbLigne
            Ymean2 /= nbLigne
            Xmean1 /= nbLigne
            Xmean2 /= nbLigne
            angle /= nbLigne
        sd.putNumber('Xmean1', Xmean1)
        sd.putNumber('Xmean2', Xmean2)
        sd.putNumber('Ymean1', Ymean1)
        sd.putNumber('Ymean2', Ymean2)
        sd.putNumber('Angle', angle)
        time.sleep(0.1)
示例#3
0
def start_camera():
    inst = CameraServer.getInstance()
    camera = UsbCamera('Hatch Panels', '/dev/video0')

    # with open("cam.json", encoding='utf-8') as cam_config:
    #     camera.setConfigJson(json.dumps(cam_config.read()))
    camera.setResolution(VERTICAL_RES, HORIZONTAL_RES)
    camera.setFPS(FPS)
    camera.setBrightness(10)
    camera.setConfigJson("""
{
    "fps": """ + str(FPS) + """,
    "height": """ + str(HORIZONTAL_RES) + """,
    "pixel format": "mjpeg",
    "properties": [
        {
            "name": "brightness",
            "value": 0
        },
        {
            "name": "contrast",
            "value": 100
        },
        {
            "name": "saturation",
            "value": 40
        }
    ],
    "width": """ + str(VERTICAL_RES) + """
}
    """)

    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    return inst, camera
示例#4
0
def startCamera(config):
    """Start running the camera."""
    print("Starting camera '{}' on {}".format(config.name, config.path))
    inst = CameraServer.getInstance()
    camera = UsbCamera(config.name, config.path)
    server = inst.startAutomaticCapture(camera=camera, return_server=True)
    #server.setResolution(640, 360)

    camera.setConfigJson(json.dumps(config.config))
    if config.path == "/dev/video0":
        camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)
        #camera.setExposureManual(1)
        #camera.setWhiteBalanceManual(50)
        #os.system("v4l2-ctl -d /dev/video0 -c auto_exposure=1")
        #os.system("v4l2-ctl -d /dev/video0 -c exposure_time_absolute=100")
        #os.system("")
        camera.getProperty("auto_exposure").set(1)
        camera.getProperty("exposure_time_absolute").set(50)
        camera.getProperty("contrast").set(100)
        #camera.getProperty("white_balance_temperature_auto").set(0)
        #for prop in camera.enumerateProperties():
        #print(prop.getName())

    if config.streamConfig is not None:
        server.setConfigJson(json.dumps(config.streamConfig))

    return camera
示例#5
0
def startCamera(config):
    print("Starting camera '{}' on {}".format(config.name, config.path))
    inst = CameraServer.getInstance()
    camera = UsbCamera(config.name, config.path)
    server = inst.startAutomaticCapture(camera=camera, return_server=True)

    camera.setConfigJson(json.dumps(config.config))
    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    if config.streamConfig is not None:
        server.setConfigJson(json.dumps(config.streamConfig))

    cvSink = inst.getVideo()

    if config.name == "PS3 Eyecam":
        cvSrc = inst.putVideo(
            config.name + " Vision", 320,
            240)  #Change to get values from config file 160,120

    else:
        cvSrc = inst.putVideo(
            config.name + " Vision", 160,
            120)  #Change to get values from config file 160,120
    print(config.height)

    return camera, cvSink, cvSrc
示例#6
0
def startCamera(config):
    """Start running the camera."""
    print("Starting camera '{}' on {}".format(config.name, config.path))
    camera = UsbCamera(config.name, config.path)

    camera.setConfigJson(json.dumps(config.config))
    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    return camera
示例#7
0
def startCamera(config):
    """Start running the camera."""
    print("Starting camera '{}' on {}".format(config.name, config.path))
    cs = CameraServer.getInstance()
    camera = UsbCamera(config.name, config.path)
    server = cs.startAutomaticCapture(camera=camera, return_server=True)

    camera.setConfigJson(json.dumps(config.config))

    return cs, camera
def main():
    cs = CameraServer.getInstance()
    cs.enableLogging()

    usb0 = UsbCamera('Camera 0', 0)
    usb0.setFPS(10)
    usb0.setResolution(176, 144)
    usb1 = UsbCamera('Camera 1', 1)
    usb1.setFPS(10)
    usb1.setResolution(176, 144)

    # We "bounce" between these two camera objects using a Command on
    # the robot.
    cams = [usb0, usb1]

    # Add a "Switched" camera opject to Network Tables,
    # and set the source to the first camera (usb0).
    server = cs.addSwitchedCamera('Switched')
    server.setSource(cams[0])
    server.setFPS(10)
    server.setCompression(80)
    server.setResolution(176, 144)


    def _listener(source, key, value, isNew):
        '''Use networktables to switch the camera source.
        We set the camera source to the camera object in the "cams"
        dictionary. We use the bitwise Exclusive Or of "value" to index
        the array (see https://wiki.python.org/moin/BitwiseOperators for
        bit operators).

        "value" MUST be 0 (zero) or 1 (one) in order for this to work
        '''
        # print("cams[int(value)]: value: {} cams: {}".format(int(value), cams[int(value)]))
        # print("usb0: {}   usb1: {}".format(usb0, usb1))
        server.setSource(cams[int(value)])

    table = networktables.NetworkTables.getTable('/CameraPublisher')
    table.putNumber('selected', 0)
    table.addEntryListener(_listener, key='selected')

    cs.waitForever()
def startCamera(config):
    print("Starting camera '{}' on {}".format(config.name, config.path))
    inst = CameraServer.getInstance()
    camera = UsbCamera(config.name, config.path)
    server = inst.startAutomaticCapture(camera=camera, return_server=True)

    camera.setConfigJson(json.dumps(config.config))
    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    if config.streamConfig is not None:
        server.setConfigJson(json.dumps(config.streamConfig))
示例#10
0
def main():
    img = np.zeros(shape=(480, 640, 3), dtype=np.uint8)

    cs = CameraServer.getInstance()
    cs.enableLogging()

    camera0 = cs.startAutomaticCapture(dev=0)
    camera1 = UsbCamera("cam1", 1)
    camera2 = UsbCamera("cam2", 2)

    # Get a CvSink. This will capture images from the camera
    cvSink = cs.getVideo()

    cvSink.setSource(camera0)

    # (optional) Setup a CvSource. This will send images back to the Dashboard
    smartDash = networktables.NetworkTables.getTable('SmartDashboard')

    def _listener(source, key, value, isNew):
        if value == 0:
            cvSink.setSource(camera0)
        elif value == 1:
            cvSink.setSource(camera1)
        elif value == 2:
            cvSink.setSource(camera2)

    smartDash.putNumber("Num", 0)
    outputStream = cs.putVideo("Out", 320, 240)

    while True:

        smartDash.addEntryListener(_listener, key="Num")
        time, img = cvSink.grabFrame(img)
        if time == 0:
            # Send the error.
            outputStream.notifyError(cvSink.getError())
            # skip the rest of the current iteration
            continue

        # display a new image on the outputStream
        outputStream.putFrame(img)
示例#11
0
def startCamera(config):
    print("Starting camera '{}' on {}".format(config.name, config.path))
    inst = CameraServer.getInstance()
    camera = UsbCamera(config.name, config.path)

    # camera.setConfigJson(json.dumps(config.config))
    camera.setConfigJson(config_json)
    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    inst.addCamera(camera)

    return inst, camera
示例#12
0
    def startDriveCamera(self, config):
        """
        Start running a drive camera.
        """

        self.logger.logMessage("Starting camera '{}' on {}".format(
            config.name, config.path))
        camera = UsbCamera("Drive", config.path)

        camera.setConfigJson(json.dumps(config.config))
        camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

        return camera
示例#13
0
def main():
    cs = CameraServer.getInstance()
    cs.enableLogging()

    usb0 = UsbCamera("Camera 0", 0)
    usb1 = UsbCamera("Camera 1", 1)

    server = cs.addSwitchedCamera("Switched")
    server.setSource(usb0)

    # Use networktables to switch the source
    # -> obviously, you can switch them however you'd like
    def _listener(source, key, value, isNew):
        if str(value) == "0":
            server.setSource(usb0)
        elif str(value) == "1":
            server.setSource(usb1)

    table = networktables.NetworkTables.getTable("/CameraPublisher")
    table.putString("selected", "0")
    table.addEntryListener(_listener, key="selected")

    cs.waitForever()
def startCamera():
    print("Starting camera rPi on /dev/video0")
    cs = CameraServer.getInstance()
    camera = UsbCamera("rPi Camera", "/dev/video0")
    #camera.setVideoMode(VideoMode.PixelFormat.kMJPEG, 320, 240, 60)
    camera.setVideoMode(VideoMode.PixelFormat.kYUYV, 320, 240, 60)
    #camera = cs.startAutomaticCapture(name="rPi Camera", path="/dev/video0")
    server = cs.startAutomaticCapture(camera=camera, return_server=True)
    server.setCompression(25)
    server.setFPS(45)
    #camera.setResolution(320,240)
    #camera.setConfigJson(json.dumps(config.config))
    camera.getProperty('color_effects').set(3)
    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)
    return cs, camera
def startCamera(config):
    print("Starting camera '{}' on {}".format(config.name, config.path))
    # makes a server port for the camera
    inst = CameraServer.getInstance()
    # makes a connection to the camera file
    camera = UsbCamera(config.name, config.path)
    # connects the server to the camera and makes the camera send images through the server
    server = inst.startAutomaticCapture(camera=camera, return_server=True)
    
    # configures the camera to the specified dictionary
    camera.setConfigJson(json.dumps(config.config))
    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    if config.streamConfig is not None:
        server.setConfigJson(json.dumps(config.streamConfig))

    return camera
示例#16
0
def startCameras():
    global cs

    for config in cameraConfigs:
        print("Starting camera '{}' on {}".format(config.name, config.path))
        camera = UsbCamera(config.name, config.path)

        camera.setConfigJson(json.dumps(config.config))
        camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

        if config.name == "driver_cam" and config.streamConfig is not None:
            print("Starting automatic capture for camera '{}'".format(
                config.name))
            server = cs.startAutomaticCapture(camera=camera,
                                              return_server=True)
            server.setConfigJson(json.dumps(config.streamConfig))

        cameras.append(camera)
示例#17
0
def startCamera(config):
    """Start running the camera."""
    print("Starting camera '{}' on {}".format(config.name, config.path))
    inst = CameraServer.getInstance()
    camera = UsbCamera(config.name, config.path)
    server = inst.startAutomaticCapture(camera=camera, return_server=True)

    camera.setConfigJson(json.dumps(config.config))
    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    if config.streamConfig is not None:
        server.setConfigJson(json.dumps(config.streamConfig))

    if config.name == "rPi Camera 1":
        camera.getProperty("contrast").set(0)
        camera.getProperty("brightness").set(50)
        camera.getProperty("saturation").set(50)

    return camera
示例#18
0
def startCamera(config):
    """Start running the camera."""
    print("Starting camera '{}' on {}".format(config.name, config.path))
    global inst
    inst = CameraServer.getInstance()
    camera = UsbCamera(config.name, config.path)
    server = inst.startAutomaticCapture(camera=camera, return_server=True)
    # if not isSinkMade:
    #     cvSink = inst.getVideo()
    #     isSinkMade = True

    camera.setConfigJson(json.dumps(config.config))
    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    if config.streamConfig is not None:
        server.setConfigJson(json.dumps(config.streamConfig))

    print("Started camera '{}' on {}".format(config.name, config.path))
    return camera
def startCamera(config):
    """Start running the camera."""
    print("Starting camera '{}' on {}".format(config.name, config.path))
    cs = CameraServer.getInstance()
    camera = UsbCamera(config.name, config.path)
    #camera.setExposureManual(5)
    cv_sink = cs.getVideo(camera=camera)
    output_stream = cs.putVideo('output_' + config.name, config.width, config.height)
    img = np.zeros(shape=(config.height, config.width, 3), dtype=np.uint8)
    input_output.append((cv_sink, output_stream, img))
    #server = cs.startAutomaticCapture(return_server=True)

    camera.setConfigJson(json.dumps(config.config))
    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    #if config.streamConfig is not None:
        #server.setConfigJson(json.dumps(config.streamConfig))

    return camera
示例#20
0
def start_camera():
    inst = CameraServer.getInstance()
    camera = UsbCamera('Hatch Panels', '/dev/video0')
    camera.setConfigJson(picamera_config_json)
    # with open("cam.json", encoding='utf-8') as cam_config:
    #     camera.setConfigJson(json.dumps(cam_config.read()))
    #     camera.setResolution(VERTICAL_RES, HORIZONTAL_RES)
    #     camera.setFPS(FPS)
    #     camera.setBrightness(10)
    #     camera.setConfigJson("""
    # {
    #     "fps": """ + str(FPS) + """,
    #     "height": """ + str(HORIZONTAL_RES) + """,
    #     "pixel format": "mjpeg",
    #     "properties": [
    #             {
    #                 "name": "brightness",
    #                 "value": 0
    #             },
    #             {
    #                 "name": "contrast",
    #                 "value": 100
    #             },
    #             {
    #                 "name": "saturation",
    #                 "value": 100
    #             },
    #             {
    #                 "name": "color_effects",
    #                 "value": 3
    #             }
    #     ],
    #     "width": """ + str(VERTICAL_RES) + """
    # }
    #     """)
    #

    # inst.startAutomaticCapture(camera=camera)

    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    return inst, camera
示例#21
0
def main():
    
    NetworkTables.initialize("10.68.51.2")
    capture = cv2.VideoCapture("/dev/v4l/by-path/platform-3f980000.usb-usb-0:1.1.3:1.0-video-index0")
    
    
    LineDetect = DetectGreenTape()
    value = 0
    sd = NetworkTables.getTable("SmartDashboard")
    ntinst = NetworkTablesInstance.getDefault()
    ntinst.startServer()
    inst = CameraServer.getInstance()
    camera = UsbCamera("Camera1","/dev/v4l/by-path/platform-3f980000.usb-usb-0:1.2:1.0-video-index0" )
    server = inst.startAutomaticCapture(camera=camera, return_server=True)
    atexit.register(FonctionSortie, capture, server, camera)
    while True:
        
        ret, frame = capture.read()
        if ret:
            LineDetect.process(frame)
            sd.putNumber('NbLinesDEtected',len(LineDetect.filter_lines_output))    
def main():
    cs = CameraServer.getInstance()
    cs.enableLogging()

    outputStream = CvSource('camera', VideoMode.PixelFormat.kMJPEG, int(640),
                            int(480), int(15))
    cs.addCamera(outputStream)
    server = cs.addServer(name='camera', port=int(5801))
    server.setSource(outputStream)

    camera = UsbCamera(
        "cam1",
        '/dev/v4l/by-id/usb-HD_Camera_Manufacturer_USB_2.0_Camera-video-index0'
    )
    # Capture from the first USB Camera on the system
    cs.startAutomaticCapture(camera=camera)
    camera.setResolution(640, 480)

    # Get a CvSink. This will capture images from the camera
    cvSink = cs.getVideo(camera=camera)

    # Allocating new images is very expensive, always try to preallocate
    img = np.zeros(shape=(480, 640, 3), dtype=np.uint8)

    while True:
        # Tell the CvSink to grab a frame from the camera and put it
        # in the source image.  If there is an error notify the output.
        time, img = cvSink.grabFrame(img)
        if time == 0:
            # Send the output the error.
            outputStream.notifyError(cvSink.getError())
            # skip the rest of the current iteration
            continue

        #
        # Insert your image processing logic here!
        #
        cv2.imshow("stream", img)
        # (optional) send some image back to the dashboard
        outputStream.putFrame(img)
示例#23
0
def startCamera(config):
    """Start running the camera."""
    global cvSink
    global outputStream

    print("Starting camera '{}' on {}".format(config.name, config.path))
    inst = CameraServer.getInstance()
    camera = UsbCamera(config.name, config.path)
    server = inst.startAutomaticCapture(camera=camera, return_server=True)

    camera.setConfigJson(json.dumps(config.config))
    camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    if config.streamConfig is not None:
        server.setConfigJson(json.dumps(config.streamConfig))

    # Get a CvSink. This will capture images from the camera
    cvSink = inst.getVideo()

    # (optional) Setup a CvSource. This will send images back to the Dashboard
    outputStream = inst.putVideo("image", width, height)

    return camera
示例#24
0
def startCamera(config):
    print("Starting camera '{}' on {}".format(config.name, config.path))
    inst = CameraServer.getInstance()
    camera = None
    server = None

    #ADDED CODE: handle pixy camera capture by creating a cvsource, otherwise normal
    if config.pixy:
        #if the camera is a pixy, get a CvSource to put the generated images in
        global pixy_source
        pixy_source = inst.putVideo("Pixy", 51, 51)
    else:
        #if the camera is not a pixy, automatically capture it
        camera = UsbCamera(config.name, config.path)
        server = inst.startAutomaticCapture(camera=camera, return_server=True)

        camera.setConfigJson(json.dumps(config.config))
        camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

    if config.streamConfig is not None and config.pixy is False:
        server.setConfigJson(json.dumps(config.streamConfig))

    return camera
示例#25
0
    def startVisionCamera(self, config):
        """
        Start running the vision camera.
        """

        self.logger.logMessage("Starting camera '{}' on {}".format(
            config.name, config.path))
        inst = CameraServer.getInstance()
        camera = UsbCamera(config.name, config.path)

        camera.setConfigJson(json.dumps(config.config))
        camera.setConnectionStrategy(VideoSource.ConnectionStrategy.kKeepOpen)

        # Start automatic capture stream
        if (Constants.ENABLE_RAW_STREAM):
            self.logger.logMessage("Starting Raw Output Stream...")

            camera_server = inst.startAutomaticCapture(camera=camera,
                                                       return_server=True)

            if config.stream_config is not None:
                camera_server.setConfigJson(json.dumps(config.stream_config))

        return camera
示例#26
0
            solid = 100 * area / cv2.contourArea(hull)
            if (solid < solidity[0] or solid > solidity[1]):
                continue
            if (len(contour) < min_vertex_count or len(contour) > max_vertex_count):
                continue
            ratio = (float)(w) / h
            if (ratio < min_ratio or ratio > max_ratio):
                continue
            output.append(contour)
        return output



gLine = Example()

camera = UsbCamera("CammyBoi", 0)
camera.setExposureManual(10)
#camera.setConfigJson(json.dumps(json.load(open(configFile, "rt", encoding="utf-8"))))
vidSink = CvSink("Camera")
vidSink.setSource(camera)

vidSource = CvSource("Processed", VideoMode.PixelFormat.kMJPEG, 640, 480, 30)
networkStream = MjpegServer("Stream", 1181)
networkStream.setSource(vidSource)
img = np.zeros(shape=(480, 640, 3), dtype=np.uint8)

while(True):
    ret, src = vidSink.grabFrame(img)
    startTime = time.time()

    gLine.process(src)
示例#27
0
    if not readConfig():
        sys.exit(1)

    # start NetworkTables to send to smartDashboard
    ntinst = NetworkTablesInstance.getDefault()

    print("Setting up NetworkTables client for team {}".format(team))
    ntinst.startClientTeam(7539)

    SmartDashBoardValues = ntinst.getTable('SmartDashboard')

    #Start camera
    print("Connecting to camera")
    cs = CameraServer.getInstance()
    cs.enableLogging()
    Camera = UsbCamera('Cam 0', 0)
    Camera.setExposureManual(5)
    Camera.setResolution(160, 120)
    cs.addCamera(Camera)

    print("connected")

    CvSink = cs.getVideo()
    outputStream = cs.putVideo("Processed Frames", 160, 120)

    #buffer to store img data
    img = np.zeros(shape=(160, 120, 3), dtype=np.uint8)
    # loop forever
    while True:

        GotFrame, img = CvSink.grabFrame(img)
示例#28
0
def main():

    cs = CameraServer.getInstance()
    cs.enableLogging()
    outputStreamTarget = cs.putVideo("targetImage", imageResolutionSend[0], imageResolutionSend[1])
    outputStreamTargetBinary = cs.putVideo("targetImageBinary", imageResolutionSend[0], imageResolutionSend[1])
    outputStreamBall = cs.putVideo("ballImage", imageResolutionSend[0], imageResolutionSend[1])
    # outputStreamBallBinary = cs.putVideo("ballImageBinary", imageResolutionSend[0], imageResolutionSend[1])

    targetImage = np.zeros(shape=(imageResolutionRasp[1], imageResolutionRasp[0], 3), dtype=np.uint8)
    ballImage = np.zeros(shape=(imageResolutionRasp[1], imageResolutionRasp[0], 3), dtype=np.uint8)

    availableTargetCamera = targetCameraAddress in os.listdir("/dev")
    availableBallCamera = ballCameraAddress in os.listdir("/dev")

    if availableTargetCamera:
        cameraTarget = UsbCamera("Camera Target", "/dev/" + targetCameraAddress)
        cameraTarget.setResolution(imageResolutionRasp[0], imageResolutionRasp[1])
        cameraTarget.setBrightness(brightnessTarget)
        cameraTarget.setExposureManual(exposureTarget)
        cs.addCamera(cameraTarget)
        cvSinkTarget = cs.getVideo(name="Camera Target")
        cvSinkTarget.setSource(cameraTarget)

    if availableBallCamera:
        cameraBall = UsbCamera("Camera Ball", "/dev/" + ballCameraAddress)
        cameraBall.setResolution(imageResolutionRasp[0], imageResolutionRasp[1])
        cameraBall.setBrightness(brightnessBall)
        cameraBall.setExposureManual(exposureBall)
        cs.addCamera(cameraBall)
        cvSinkBall = cs.getVideo(name="Camera Ball")
        cvSinkBall.setSource(cameraBall)
    
    counter = 0
    while True:

        if availableTargetCamera:
            availableTargetCamera = targetCameraAddress in os.listdir("/dev")
        if availableBallCamera:
            availableBallCamera = ballCameraAddress in os.listdir("/dev")

        counter += 1
        textOutput = ""

        if calibration:
            
            getHSVBallParameters()
            getHSVTargetParameters()
            
            getCameraTargetParameters()
            getCameraBallParameters()

            getTargetDistanceParameters()
        
        if availableTargetCamera:
            t, targetImage = cvSinkTarget.grabFrame(targetImage)
            available, targetImage, binaryTargetImage, targetXPos, targetYPos = findTarget(targetImage)
            
            distance = calculateDistance(targetYPos)
            horizontalAngle = getHorizontalAngle(targetXPos, imageResolutionRasp)
            launcherAngle = getLauncherAngle(distance)

            if distance > 95 and distance < 240:
                cv2.rectangle(targetImage, (20, 20), (100, 100), (0, 255, 0), -1)
            
            netTableTargetAvailable.setBoolean(available)
            netTableTargetDistance.setDouble(distance)
            netTableTargetHorizontalAngle.setDouble(horizontalAngle)
            netTableTargetLauncherAngle.setDouble(launcherAngle)
            netTableTargetXPos.setDouble(targetXPos)
            netTableTargetYPos.setDouble(targetYPos)

            smallerBinaryTargetImage = cv2.resize(binaryTargetImage, (imageResolutionSend[0], imageResolutionSend[1]))
            smallerTargetImage = cv2.resize(targetImage, (imageResolutionSend[0], imageResolutionSend[1]))
            outputStreamTargetBinary.putFrame(smallerBinaryTargetImage)
            outputStreamTarget.putFrame(smallerTargetImage)
            textOutput += "Distance: {} horizontalAngle: {} launcherAngle: {} targetYPos: {}\n".format(distance, horizontalAngle, launcherAngle, targetYPos)
        else:
            textOutput += "Target Camera disabled\n"


        if availableBallCamera:
            t, ballImage = cvSinkBall.grabFrame(ballImage)
            # ballImage, binaryBallImage, ballXPos, ballYPos = findBall(ballImage)
            # angle = getHorizontalAngle(ballXPos, imageResolutionRasp)

            # netTableBallXPos.setDouble(ballXPos)
            # netTableBallYPos.setDouble(ballYPos)
            # netTableBallAngle.setDouble(angle)

            # smallerBinaryBallImage = cv2.resize(binaryBallImage, (imageResolutionSend[0], imageResolutionSend[1]))
            smallerBallImage = cv2.resize(ballImage, (imageResolutionSend[0], imageResolutionSend[1]))
            # outputStreamBallBinary.putFrame(smallerBinaryBallImage)
            outputStreamBall.putFrame(smallerBallImage)
            # textOutput += "ballXPos: {} ballYPos: {}\n".format(ballXPos, ballYPos)
        else:
            textOutput += "Ball Camera disabled\n"

        if counter % 10 == 0:
            print(textOutput)
ip = '10.30.6.2'

NetworkTables.initialize(server=ip)

lower_green = np.array([0, 255, 110])  #137 240 135 - HSV, 0,90,90 - RGB
upper_green = np.array([80, 255, 200])  #143 255 148 - HSV, 86,255,255 - RGB

camWidth = 320
camHeight = 240
center_x = camWidth * .5
margin = 20

cs = CameraServer.getInstance()
cs.enableLogging()

cam1 = UsbCamera("cam1", 0)
cam2 = UsbCamera("cam2", 1)

cam1.setResolution(camWidth, camHeight)
cam2.setResolution(camWidth, camHeight)

cam1.setExposureManual(8)
cam2.setExposureManual(8)

cvSink = cs.getVideo(camera=cam1)

outputStream = cs.putVideo("Cam1", camWidth, camHeight)

frame = np.zeros(shape=(camHeight, camWidth, 3), dtype=np.uint8)

    ntinst = NetworkTablesInstance.getDefault()
    if server:
        print("Setting up NetworkTables server")
        ntinst.startServer()
    else:
        print("Setting up NetworkTables client for team {}".format(team))
        ntinst.startClientTeam(team)

    sd = ntinst.getTable("Shuffleboard")

    img0 = np.zeros(shape=(image_height, image_width, 3), dtype=np.uint8)
    img1 = np.zeros(shape=(image_height, image_width, 3), dtype=np.uint8)

    portPath = "/dev/video0"
    cellPath = "/dev/video2"
    cameraPort = UsbCamera("PortCam", portPath)
    cameraCell = UsbCamera("CellCam", cellPath)

    inst = CameraServer.getInstance()

    inst.startAutomaticCapture(camera=cameraPort)
    inst.startAutomaticCapture(camera=cameraCell)

    cvSink0 = inst.getVideo(camera=cameraPort)
    cvSink1 = inst.getVideo(camera=cameraCell)
    #outputStream0 = inst.putVideo("PortStream", (image_width), (image_height))
    outputStream1 = inst.putVideo("CellStream", (image_width), (image_height))

    # loop forever
    while True:
        timestamp, img0 = cvSink0.grabFrame(img0)