# UVC & Mono Camera

This example demonstrates how to use a mono camera on your OAK device to function as a webcam. The UVC feature allows you to use
your OAK device as a regular webcam in applications like OpenCV's cv2.VideoCapture(), native camera apps, and more.

### How It Works:

The [MonoCamera](https://docs.luxonis.com/software/depthai-components/nodes/mono_camera.md) node outputs image data in the GRAY8
format. However, the [UVC](https://docs.luxonis.com/software/depthai-components/nodes/uvc.md) node expects the data in NV12
format. To bridge this gap, an intermediary
[ImageManip](https://docs.luxonis.com/software/depthai-components/nodes/image_manip.md) node is used to convert the GRAY8 output
from the MonoCamera node to NV12 format, which is then passed to the UVC node for streaming.

### Similar samples:

 * [UVC & Color Camera](https://docs.luxonis.com/software/depthai/examples/uvc_rgb.md)
 * [UVC & Disparity](https://docs.luxonis.com/software/depthai/examples/uvc_disparity.md)

## Setup

Please run the [install script](https://github.com/luxonis/depthai-python/blob/main/examples/install_requirements.py) to download
all required dependencies. Please note that this script must be ran from git context, so you have to download the
[depthai-python](https://github.com/luxonis/depthai-python) repository first and then run the script

```bash
git clone https://github.com/luxonis/depthai-python.git
cd depthai-python/examples
python3 install_requirements.py
```

For additional information, please follow the [installation guide](https://docs.luxonis.com/software/depthai/manual-install.md).

## Code used for testing

```python
import cv2

# Initialize the VideoCapture object to use the default camera (camera index 0 is webcam)
cap = cv2.VideoCapture(1)

# Check if the camera opened successfully
if not cap.isOpened():
    print("Error: Could not open camera.")
    exit()

# Loop to continuously get frames from the camera
while True:
    ret, frame = cap.read()

    if not ret:
        print("Error: Could not read frame.")
        break

    cv2.imshow('Video Feed', frame)

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

cap.release()
cv2.destroyAllWindows()
```

## Source code

#### Python

```python
#!/usr/bin/env python3

import time

import depthai as dai

pipeline = dai.Pipeline()

# Define a source - left mono (grayscale) camera
mono_left = pipeline.createMonoCamera()

mono_left.setResolution(dai.MonoCameraProperties.SensorResolution.THE_720_P)
mono_left.setBoardSocket(dai.CameraBoardSocket.CAM_B)

# Create an UVC (USB Video Class) output node
uvc = pipeline.createUVC()

# Manip for frame type conversion
manip = pipeline.createImageManip()
manip.initialConfig.setResize(1280, 720)
manip.initialConfig.setFrameType(dai.RawImgFrame.Type.NV12)
manip.setMaxOutputFrameSize(int(1280*720*1.5))

# Linking
manip.out.link(uvc.input)
mono_left.out.link(manip.inputImage)

# Note: if the pipeline is sent later to device (using startPipeline()),
# it is important to pass the device config separately when creating the device
config = dai.Device.Config()
config.board.uvc = dai.BoardConfig.UVC(1280, 720)
config.board.uvc.frameType = dai.ImgFrame.Type.NV12
# config.board.uvc.cameraName = "My Custom Cam"
pipeline.setBoardConfig(config.board)

# Standard UVC load with depthai
with dai.Device(pipeline) as device:
    # Dot projector
    device.setIrLaserDotProjectorBrightness(765)
    print("\nDevice started, please keep this process running")
    print("and open an UVC viewer to check the camera stream.")
    print("\nTo close: Ctrl+C")

    # Doing nothing here, just keeping the host feeding the watchdog
    while True:
        try:
            time.sleep(0.1)
        except KeyboardInterrupt:
            break
```

## Pipeline

### examples/uvc_mono.pipeline.json

```json
{
  "pipeline": {
    "connections": [
      {
        "node1Id": 2,
        "node1Output": "out",
        "node1OutputGroup": "",
        "node2Id": 1,
        "node2Input": "in",
        "node2InputGroup": ""
      },
      {
        "node1Id": 0,
        "node1Output": "out",
        "node1OutputGroup": "",
        "node2Id": 2,
        "node2Input": "inputImage",
        "node2InputGroup": ""
      }
    ],
    "globalProperties": {
      "calibData": null,
      "cameraTuningBlobSize": null,
      "cameraTuningBlobUri": "",
      "leonCssFrequencyHz": 700000000.0,
      "leonMssFrequencyHz": 700000000.0,
      "pipelineName": null,
      "pipelineVersion": null,
      "sippBufferSize": 18432,
      "sippDmaBufferSize": 16384,
      "xlinkChunkSize": -1
    },
    "nodes": [
      [
        0,
        {
          "id": 0,
          "ioInfo": [
            [
              [
                "",
                "inputControl"
              ],
              {
                "blocking": true,
                "group": "",
                "id": 1,
                "name": "inputControl",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "out"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 2,
                "name": "out",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "raw"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 3,
                "name": "raw",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "frameEvent"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 4,
                "name": "frameEvent",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ]
          ],
          "name": "MonoCamera",
          "properties": {
            "boardSocket": 1,
            "cameraName": "",
            "fps": 30.0,
            "imageOrientation": -1,
            "initialControl": {
              "aeLockMode": false,
              "aeMaxExposureTimeUs": 0,
              "aeRegion": {
                "height": 0,
                "priority": 0,
                "width": 0,
                "x": 0,
                "y": 0
              },
              "afRegion": {
                "height": 0,
                "priority": 0,
                "width": 0,
                "x": 0,
                "y": 0
              },
              "antiBandingMode": 0,
              "autoFocusMode": 3,
              "awbLockMode": false,
              "awbMode": 0,
              "brightness": 0,
              "captureIntent": 0,
              "chromaDenoise": 0,
              "cmdMask": 0,
              "contrast": 0,
              "controlMode": 0,
              "effectMode": 0,
              "expCompensation": 0,
              "expManual": {
                "exposureTimeUs": 0,
                "frameDurationUs": 0,
                "sensitivityIso": 0
              },
              "frameSyncMode": 0,
              "lensPosAutoInfinity": 0,
              "lensPosAutoMacro": 0,
              "lensPosition": 0,
              "lensPositionRaw": 0.0,
              "lowPowerNumFramesBurst": 0,
              "lowPowerNumFramesDiscard": 0,
              "lumaDenoise": 0,
              "saturation": 0,
              "sceneMode": 0,
              "sharpness": 0,
              "strobeConfig": {
                "activeLevel": 0,
                "enable": 0,
                "gpioNumber": 0
              },
              "strobeTimings": {
                "durationUs": 0,
                "exposureBeginOffsetUs": 0,
                "exposureEndOffsetUs": 0
              },
              "wbColorTemp": 0
            },
            "isp3aFps": 0,
            "numFramesPool": 3,
            "numFramesPoolRaw": 3,
            "rawPacked": null,
            "resolution": 0
          }
        }
      ],
      [
        1,
        {
          "id": 1,
          "ioInfo": [
            [
              [
                "",
                "in"
              ],
              {
                "blocking": true,
                "group": "",
                "id": 5,
                "name": "in",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": true
              }
            ]
          ],
          "name": "UVC",
          "properties": {
            "gpioInit": [],
            "gpioStreamOff": [],
            "gpioStreamOn": []
          }
        }
      ],
      [
        2,
        {
          "id": 2,
          "ioInfo": [
            [
              [
                "",
                "inputConfig"
              ],
              {
                "blocking": true,
                "group": "",
                "id": 6,
                "name": "inputConfig",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "inputImage"
              ],
              {
                "blocking": true,
                "group": "",
                "id": 7,
                "name": "inputImage",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": true
              }
            ],
            [
              [
                "",
                "out"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 8,
                "name": "out",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ]
          ],
          "name": "ImageManip",
          "properties": {
            "initialConfig": {
              "cropConfig": {
                "cropRatio": 1.0,
                "cropRect": {
                  "xmax": 0.0,
                  "xmin": 0.0,
                  "ymax": 0.0,
                  "ymin": 0.0
                },
                "cropRotatedRect": {
                  "angle": 0.0,
                  "center": {
                    "x": 0.0,
                    "y": 0.0
                  },
                  "size": {
                    "height": 0.0,
                    "width": 0.0
                  }
                },
                "enableCenterCropRectangle": false,
                "enableRotatedRect": false,
                "normalizedCoords": true,
                "widthHeightAspectRatio": 1.0
              },
              "enableCrop": false,
              "enableFormat": true,
              "enableResize": true,
              "formatConfig": {
                "colormap": 0,
                "colormapMax": 255,
                "colormapMin": 0,
                "flipHorizontal": false,
                "flipVertical": false,
                "type": 22
              },
              "interpolation": -1,
              "resizeConfig": {
                "bgBlue": 0,
                "bgGreen": 0,
                "bgRed": 0,
                "enableRotation": false,
                "enableWarp4pt": false,
                "enableWarpMatrix": false,
                "height": 720,
                "keepAspectRatio": true,
                "lockAspectRatioFill": false,
                "normalizedCoords": true,
                "rotationAngleDeg": 0.0,
                "warpBorderReplicate": false,
                "warpFourPoints": [],
                "warpMatrix3x3": [],
                "width": 1280
              },
              "reusePreviousImage": false,
              "skipCurrentImage": false
            },
            "meshHeight": 0,
            "meshUri": "",
            "meshWidth": 0,
            "numFramesPool": 4,
            "outputFrameSize": 1382400
          }
        }
      ]
    ]
  }
}
```

### Need assistance?

Head over to [Discussion Forum](https://discuss.luxonis.com/) for technical support or any other questions you might have.
