Standard library · AI

opencv

Computer vision with OpenCV: image processing, features, face detection, neural networks and video.

import opencv

This package binds the OpenCV library and gives most of the everyday computer vision work: color conversion, resizing, filters, edge detection and thresholds, contours, ORB and SIFT features, face detection with a cascade classifier, running DNN networks, and reading and writing video and camera frames.

Use it for real computer vision: finding objects, matching features, reading camera frames, running a detection network. For thumbnails, drawing, text on images and format conversion with no outside library, the image package is enough. To run a model file without OpenCV, see onnx.

Things to know

•

Programs link against the salam_opencv_shim library, which in turn needs OpenCV 4. If the shim is missing, the build fails at the link step or the program refuses to start with "cannot open shared object file"; it never gets as far as your code.

•

A Mat stores colour in OpenCV's blue, green, red order, but every function of this package takes and returns Color values as red, green, blue, and FromImage and ToImage convert for you.

•

Every Mat owns native memory that Salam does not track. Free each one, especially inside a loop over video frames.

•

Calls that fail return an empty Mat (or false) and leave the reason in LastError.

The examples need OpenCV, so the site only type-checks them.

Set up OpenCV

The package talks to OpenCV 4 through a small C++ shim, salam_opencv_shim, that lives in std/opencv/native of the Salam repository. On Debian or Ubuntu, install OpenCV and the build tools, build the shim, and let the loader find it:

sudo apt install libopencv-dev cmake g++
cd std/opencv
cmake -S native -B native/build -DCMAKE_BUILD_TYPE=Release
cmake --build native/build --config Release
export LD_LIBRARY_PATH=$PWD/native/build:$LD_LIBRARY_PATH

Every program on this page starts by calling Available, which reports whether OpenCV answers and returns its version through Version. The outputs shown below are what the programs printed with OpenCV 4.10 on Linux.

Find and measure shapes

The classic pipeline for counting objects is: convert to gray, threshold to a black and white mask, then find the contours of the white areas. THRESH_BINARY_INV makes dark shapes on a light background white. Contours gives the number of shapes and, for each one, its area and bounding_rect. Drawing methods such as rectangle and circle change the image in place, and a thickness of -1 fills the shape.

opencv-guide-shapes.salam
import opencv

func main:
    if not opencv.Available():
        println "OpenCV is not available:", opencv.LastError()
        ret 1
    end
    mut board := opencv.NewBlank(400, 300, 3, opencv.White())
    defer board.Free()
    board.Rectangle(40, 40, 120, 80, opencv.Black(), -1)
    board.Circle(280, 90, 50, opencv.Black(), -1)
    board.Rectangle(150, 190, 200, 70, opencv.Black(), -1)

    mut gray := board.ToGray()
    mut mask := gray.Threshold(128.0, 255.0, opencv.THRESH_BINARY_INV)
    mut found := mask.FindContours()
    defer gray.Free()
    defer mask.Free()
    defer found.Free()
    println "shapes found:", found.Count()
    repeat found.Count() in i:
        box := found.BoundingRect(i)
        println "  shape at",
            box.x,
            box.y,
            "size",
            box.width,
            "x",
            box.height,
            "area",
            found.Area(i) as int
        board.Rectangle(box.x - 3, box.y - 3, box.width + 6, box.height + 6, opencv.Red(), 2)
    end
    println "saved:", board.Save("shapes.png")
end
shapes found: 3
  shape at 150 190 size 200 x 70 area 13731
  shape at 230 40 size 101 x 101 area 7704
  shape at 40 40 size 120 x 80 area 9401
saved: true

The area is measured along the traced outline, so it comes out a little smaller than width times height.

Edge detection

canny finds edges, and works best on a gray image that has been smoothed first with gaussian_blur, so that noise does not turn into tiny false edges. The two thresholds control how strong an edge must be to start a line and to continue one. dilate thickens the result, which helps when the edges go on to a contour search. When photo.jpg is missing, the program draws a test image instead.

opencv-guide-edges.salam
import opencv

func white_pixels(m: opencv.Mat): int:
    hist := m.HistogramGray()
    ret hist.Get(255)
end

func main:
    if not opencv.Available():
        println "OpenCV is not available:", opencv.LastError()
        ret 1
    end
    mut photo := opencv.Read("photo.jpg")
    if not photo.Ok() or photo.Empty():
        println "photo.jpg not found, using a drawn test image"
        photo = opencv.NewBlank(320, 240, 3, opencv.RGB(200, 200, 200))
        photo.Circle(160, 120, 70, opencv.RGB(40, 40, 40), -1)
    end
    defer photo.Free()
    println "size:", photo.Width(), "x", photo.Height(), "channels:", photo.Channels()

    mut gray := photo.ToGray()
    mut smooth := gray.GaussianBlur(5, 1.4)
    mut edges := smooth.Canny(50.0, 150.0)
    mut thick := edges.Dilate(3, 1)
    defer gray.Free()
    defer smooth.Free()
    defer edges.Free()
    defer thick.Free()
    println "edge pixels:", white_pixels(edges), "after dilate:", white_pixels(thick)
    println "saved:", opencv.Write("edges.png", thick)
end
photo.jpg not found, using a drawn test image
size: 320 x 240 channels: 3
edge pixels: 480 after dilate: 1600
saved: true

Every method that returns a new Mat allocates; free each result, as the defer lines do, or a long running program, such as one that processes camera frames, will grow without limit.

Find a picture inside another

find_template slides a small image over a large one and reports the best position and a score between 0 and 1. That is how a test robot finds a button on a screenshot, or a program finds a logo in a scan. Check found and the score before you trust the position.

opencv-guide-template.salam
import opencv

func main:
    if not opencv.Available():
        println "OpenCV is not available:", opencv.LastError()
        ret 1
    end
    mut screen := opencv.NewBlank(640, 480, 3, opencv.RGB(230, 230, 230))
    defer screen.Free()
    screen.Rectangle(420, 300, 90, 40, opencv.RGB(30, 120, 220), -1)
    screen.PutText("OK", 445, 330, 0.9, opencv.White(), 2)
    screen.Rectangle(100, 100, 200, 60, opencv.RGB(120, 120, 120), -1)

    mut button := screen.Crop(420, 300, 90, 40)
    defer button.Free()
    hit := screen.FindTemplate(button)
    if hit.found:
        println "button at", hit.x, hit.y, "score above 0.99:", hit.score > 0.99
        screen.Rectangle(hit.x, hit.y, 90, 40, opencv.Red(), 2)
    else:
        println "button not on screen"
    end
    println "saved:", screen.Save("found.png")
end
button at 420 300 score above 0.99: true
saved: true

Write and read video

NewVideoWriter takes a file name, a four letter codec, the frames per second and the frame size; every frame you write must have that size. OpenVideo reads a file and OpenCamera(0) the first camera; read returns an empty Mat when there are no more frames. Which codecs work depends on how OpenCV was built; MJPG in an .avi file is available almost everywhere.

opencv-guide-video.salam
import opencv

func main:
    if not opencv.Available():
        println "OpenCV is not available:", opencv.LastError()
        ret 1
    end
    mut writer := opencv.NewVideoWriter("ball.avi", "MJPG", 10.0, 160, 120)
    if not writer.Ok():
        println "this OpenCV build cannot write MJPG video"
        ret 1
    end
    repeat 20 in i:
        mut frame := opencv.NewBlank(160, 120, 3, opencv.Black())
        frame.Circle(10 + i * 7, 60, 8, opencv.Green(), -1)
        writer.Write(frame)
        frame.Free()
    end
    writer.Close()

    mut video := opencv.OpenVideo("ball.avi")
    if not video.Ok():
        println "could not open ball.avi"
        ret 1
    end
    println "frames:", video.FrameCount(), "fps:", video.Fps()
    mut read := 0
    mut last := opencv.Mat {}
    until true:
        frame := video.Read()
        if frame.Empty(): break end
        read++
        last.Free()
        last = frame
    end
    println "read", read, "frames, last frame", last.Width(), "x", last.Height()
    last.Free()
    video.Close()
end
frames: 20 fps: 10
read 20 frames, last frame 160 x 120

To show frames in a window while you work, use Imshow and WaitKey; they need a desktop session. ToImage and FromImage move pictures between this package and image, for example to draw Persian text with a TrueType font.

Types

Mat

#
struct Mat

An OpenCV image or matrix with BGR channels.

NameTypeDescription
handlevoid*The internal handle.
opencv-Basics.salam
import opencv

func main:
    if not opencv.Available():
        println "OpenCV is not available:", opencv.LastError()
        ret
    end
    println opencv.Version()
    mut photo := opencv.Read("photo_en.jpg")
    if not photo.Ok() or photo.Empty():
        photo = opencv.NewBlank(320, 240, 3, opencv.White())
    end
    dims := photo.Size()
    println photo.Width(),
        photo.Height(),
        photo.Channels(),
        dims.width,
        dims.height,
        photo.Step(),
        photo.Total(),
        photo.Data() != null
    color := photo.At(10, 10)
    println color.r, color.g, color.b
    photo.SetPixel(0, 0, opencv.RGB(255, 128, 0))
    black := opencv.Zeros(10, 10, 1)
    println black.Channels(), opencv.Black().r, opencv.Red().r, opencv.Green().g, opencv.Blue().b

    gray := photo.ToGray()
    _ := photo.ToRgb()
    hsv := photo.ToHsv()
    _ := hsv.HsvToRgb()
    _ := photo.ConvertColor(opencv.COLOR_BGR2GRAY)
    _ := gray.ConvertColor(opencv.COLOR_GRAY2BGR)
    println opencv.COLOR_RGB2GRAY,
        opencv.COLOR_GRAY2RGB,
        opencv.COLOR_BGR2RGB,
        opencv.COLOR_RGB2BGR,
        opencv.COLOR_BGR2HSV,
        opencv.COLOR_HSV2BGR,
        opencv.COLOR_RGB2HSV,
        opencv.COLOR_HSV2RGB

    small := photo.Resize(160, 120, opencv.INTERP_AREA)
    _ := photo.ResizeScale(2.0, 2.0)
    _ := photo.Crop(10, 10, 100, 80)
    _ := photo.Rotate90(opencv.ROTATE_90_CW)
    _ := photo.Rotate(45.0, 1.0)
    _ := photo.Flip(opencv.FLIP_BOTH)
    _ := photo.FlipHorizontal()
    _ := photo.FlipVertical()
    println opencv.INTERP_NEAREST,
        opencv.INTERP_LINEAR,
        opencv.INTERP_CUBIC,
        opencv.INTERP_LANCZOS4,
        opencv.ROTATE_180,
        opencv.ROTATE_90_CCW,
        opencv.FLIP_VERTICAL,
        opencv.FLIP_HORIZONTAL
    copied := small.Clone()
    println copied.Save("small_en.png"), opencv.Write("gray_en.png", gray)
    copied.Free()
    photo.Free()
end

Ok

#
func Ok(): bool

Whether it is valid.

The example for this item is shown with the ones above: opencv-Basics.salam

Empty

#
func Empty(): bool

Width

#
func Width(): int

Height

#
func Height(): int

Channels

#
func Channels(): int

Size

#
func Size(): Size

The size.

opencv-Features.salam
import opencv

func main:
    mut scene := opencv.Read("scene_en.jpg")
    mut target := opencv.Read("object_en.jpg")
    mut contours := scene.ToGray().ThresholdOtsu(255.0).FindContours()
    println contours.Ok(), contours.Count()
    repeat contours.Count() in i:
        box := contours.BoundingRect(i)
        println contours.Area(i),
            contours.PointCount(i),
            contours.Point(i, 0).x,
            box.x,
            box.y,
            box.width,
            box.height
        scene.DrawContour(contours, i, opencv.Green(), 2)
    end
    contours.Free()

    corners := scene.ToGray().GoodFeatures(50, 0.01, 10.0)
    println corners.Len()
    mut keys1 := scene.DetectOrb(500)
    mut keys2 := target.DetectOrb(500)
    mut sift := scene.DetectSift(500)
    println keys1.Ok(), keys1.Count(), sift.Count()
    if keys1.Count() > 0:
        first := keys1.Get(0)
        println first.x, first.y, first.size, first.angle, first.response
    end
    matches := opencv.MatchDescriptors(
        keys1.Descriptors(), keys2.Descriptors(), 50, opencv.NORM_HAMMING
    )
    each m in matches:
        println m.query_idx, m.train_idx, m.distance
    end
    println opencv.NORM_L2
    keys1.Free()
    keys2.Free()
    sift.Free()

    found := scene.FindTemplate(target)
    println found.found, found.x, found.y, found.score
    mut quad := Vector {} as Vector<opencv.Point>
    quad.Push(opencv.Point { x = 0, y = 0 })
    quad.Push(opencv.Point { x = 400, y = 10 })
    quad.Push(opencv.Point { x = 410, y = 580 })
    quad.Push(opencv.Point { x = 5, y = 590 })
    flat := scene.WarpPerspective(quad, 420, 594)
    _ := opencv.Write("document_en.png", flat)
end

Clone

#
func Clone(): Mat

Free

#
func Free()

Frees it.

The example for this item is shown with the ones above: opencv-Basics.salam

Save

#
func Save(path: str): bool

Data

#
func Data(): void*

Step

#
func Step(): int

Total

#
func Total(): int

At

#
func At(x: int, y: int): Color

SetPixel

#
func SetPixel(x: int, y: int, c: Color)

ConvertColor

#
func ConvertColor(code: int): Mat

ToGray

#
func ToGray(): Mat

ToRgb

#
func ToRgb(): Mat

ToHsv

#
func ToHsv(): Mat

HsvToRgb

#
func HsvToRgb(): Mat

Resize

#
func Resize(width: int, height: int, interpolation: int): Mat

ResizeScale

#
func ResizeScale(fx: f64, fy: f64): Mat

Crop

#
func Crop(x: int, y: int, w: int, h: int): Mat

Rotate90

#
func Rotate90(code: int): Mat

Rotate

#
func Rotate(angle_degrees: f64, scale: f64): Mat

Flip

#
func Flip(mode: int): Mat

FlipHorizontal

#
func FlipHorizontal(): Mat

FlipVertical

#
func FlipVertical(): Mat

Blur

#
func Blur(ksize: int): Mat

GaussianBlur

#
func GaussianBlur(ksize: int, sigma: f64): Mat

MedianBlur

#
func MedianBlur(ksize: int): Mat

Canny

#
func Canny(t1: f64, t2: f64): Mat

Threshold

#
func Threshold(thresh: f64, maxval: f64, kind: int): Mat

ThresholdOtsu

#
func ThresholdOtsu(maxval: f64): Mat

AdaptiveThreshold

#
func AdaptiveThreshold(maxval: f64, method: int, kind: int, block_size: int, c: f64): Mat

HistogramGray

#
func HistogramGray(): Vector<int>

Line

#
func Line(x1: int, y1: int, x2: int, y2: int, color: Color, thickness: int)

Rectangle

#
func Rectangle(x: int, y: int, w: int, h: int, color: Color, thickness: int)

Circle

#
func Circle(cx: int, cy: int, radius: int, color: Color, thickness: int)

PutText

#
func PutText(text: str, x: int, y: int, font_scale: f64, color: Color, thickness: int)

GoodFeatures

#
func GoodFeatures(max_corners: int, quality: f64, min_dist: f64): Vector<Point>

DetectOrb

#
func DetectOrb(max_features: int): Keypoints

DetectSift

#
func DetectSift(max_features: int): Keypoints

Erode

#
func Erode(ksize: int, iterations: int): Mat

Dilate

#
func Dilate(ksize: int, iterations: int): Mat

Morphology

#
func Morphology(op: int, ksize: int): Mat

Blend

#
func Blend(other: Mat, alpha: f64, beta: f64, gamma: f64): Mat

Bitwise

#
func Bitwise(other: Mat, op: int): Mat

BitwiseNot

#
func BitwiseNot(): Mat

AbsDiff

#
func AbsDiff(other: Mat): Mat

WarpPerspective

#
func WarpPerspective(src: Vector<Point>, out_width: int, out_height: int): Mat

FindTemplate

#
func FindTemplate(template: Mat): TemplateMatch

Ellipse

#
func Ellipse(cx: int, cy: int, axis_width: int, axis_height: int, angle_degrees: f64, color: Color, thickness: int)

Polylines

#
func Polylines(pts: Vector<Point>, closed: bool, color: Color, thickness: int)

FillPoly

#
func FillPoly(pts: Vector<Point>, color: Color)

FindContours

#
func FindContours(): Contours

DrawContour

#
func DrawContour(cs: Contours, idx: int, color: Color, thickness: int)

TemplateMatch

#
struct TemplateMatch

The result of a template search.

NameTypeDescription
foundbool = falseWhether it was found.
xint = 0x.
yint = 0y.
scoref64 = 0The match score.

The example for this item is shown with the ones above: opencv-Features.salam

Size

#
struct Size

A size.

NameTypeDescription
widthint = 0The width.
heightint = 0The height.

The example for this item is shown with the ones above: opencv-Basics.salam

Point

#
struct Point

A point.

NameTypeDescription
xint = 0x.
yint = 0y.
opencv-Filters.salam
import opencv

func main:
    mut photo := opencv.Read("photo_en.jpg")
    gray := photo.ToGray()
    _ := photo.Blur(5)
    _ := photo.GaussianBlur(5, 1.5)
    _ := photo.MedianBlur(5)
    edges := gray.Canny(50.0, 150.0)
    _ := gray.Threshold(128.0, 255.0, opencv.THRESH_BINARY)
    _ := gray.ThresholdOtsu(255.0)
    _ := gray.AdaptiveThreshold(255.0, opencv.ADAPTIVE_GAUSSIAN, opencv.THRESH_BINARY, 11, 2.0)
    println opencv.THRESH_BINARY_INV,
        opencv.THRESH_TRUNC,
        opencv.THRESH_TOZERO,
        opencv.THRESH_TOZERO_INV,
        opencv.THRESH_OTSU,
        opencv.ADAPTIVE_MEAN
    println gray.HistogramGray().Len()
    _ := edges.Erode(3, 1)
    _ := edges.Dilate(3, 2)
    _ := edges.Morphology(opencv.MORPH_CLOSE, 5)
    println opencv.MORPH_OPEN, opencv.MORPH_GRADIENT, opencv.MORPH_TOPHAT, opencv.MORPH_BLACKHAT
    white := opencv.NewBlank(photo.Width(), photo.Height(), 3, opencv.White())
    _ := photo.Blend(white, 0.7, 0.3, 0.0)
    _ := photo.Bitwise(white, opencv.BITWISE_AND)
    _ := photo.Bitwise(white, opencv.BITWISE_OR)
    _ := photo.Bitwise(white, opencv.BITWISE_XOR)
    _ := photo.BitwiseNot()
    _ := photo.AbsDiff(white)
    photo.Line(0, 0, 100, 100, opencv.Red(), 2)
    photo.Rectangle(10, 10, 50, 30, opencv.Green(), 1)
    photo.Circle(80, 80, 20, opencv.Blue(), -1)
    photo.Ellipse(100, 50, 40, 20, 30.0, opencv.Black(), 2)
    photo.PutText("Salam", 10, 200, 1.0, opencv.White(), 2)
    mut points := Vector {} as Vector<opencv.Point>
    points.Push(opencv.Point { x = 0, y = 0 })
    points.Push(opencv.Point { x = 50, y = 0 })
    points.Push(opencv.Point { x = 25, y = 40 })
    photo.Polylines(points, true, opencv.Red(), 2)
    photo.FillPoly(points, opencv.Green())
    _ := opencv.Write("filtered_en.png", photo)
end

Rect

#
struct Rect

A rectangle.

NameTypeDescription
xint = 0x.
yint = 0y.
widthint = 0The width.
heightint = 0The height.

The example for this item is shown with the ones above: opencv-Filters.salam

Color

#
struct Color

A color.

NameTypeDescription
rint = 0Red.
gint = 0Green.
bint = 0Blue.

The example for this item is shown with the ones above: opencv-Basics.salam

Net

#
struct Net

A DNN neural network.

NameTypeDescription
handlevoid*The internal handle.
opencv-Detect.salam
import opencv
import image

func main:
    mut cascade := opencv.LoadCascade("haarcascade_frontalface_default.xml")
    mut photo := opencv.Read("people_en.jpg")
    if cascade.Ok():
        each face in cascade.Detect(photo.ToGray(), 1.1, 5, 100):
            photo.Rectangle(face.x, face.y, face.width, face.height, opencv.Green(), 2)
        end
    end
    cascade.Free()

    mut net := opencv.LoadNet("MobileNetSSD_en.caffemodel", "MobileNetSSD_en.prototxt")
    mut single := opencv.LoadNetSingleFile("model_en.onnx")
    if net.Ok():
        _ := net.SetInput(
            photo,
            0.007843,
            opencv.RGB(127, 127, 127),
            false,
            opencv.Size { width = 300, height = 300 }
        )
        output := net.Forward()
        _ := net.ForwardLayer("detection_out")
        each obj in opencv.ParseSSDDetections(output, photo.Width(), photo.Height(), 0.5):
            println obj.class_id, obj.confidence, obj.x, obj.y, obj.width, obj.height
        end
    end
    net.Free()
    single.Free()

    mut video := opencv.OpenVideo("clip_en.mp4")
    mut camera := opencv.OpenCamera(0)
    mut writer := opencv.NewVideoWriter("out_en.mp4", "mp4v", video.Fps(), 640, 480)
    println video.Ok(), video.FrameCount(), camera.Ok(), writer.Ok()
    opencv.CreateTrackbar("threshold", "preview", 100, 255)
    until video.Ok():
        frame := video.Read()
        if frame.Empty():
            break
        end
        level := opencv.GetTrackbarPos("threshold", "preview")
        edges := frame.ToGray().Canny(level as f64, 200.0)
        _ := writer.Write(frame)
        opencv.Imshow("preview", edges)
        if opencv.WaitKey(1) == 27:
            break
        end
    end
    opencv.SetTrackbarPos("threshold", "preview", 50)
    opencv.DestroyWindow("preview")
    opencv.DestroyAllWindows()
    video.Close()
    camera.Close()
    writer.Close()

    picture := opencv.ToImage(photo)
    println picture.width
    _ := opencv.FromImage(image.New(8, 8))
end

Ok

#
func Ok(): bool

Whether it loaded.

The example for this item is shown with the ones above: opencv-Detect.salam

SetInput

#
func SetInput(image: Mat, scale: f64, mean: Color, swap_rb: bool, size: Size): bool

Forward

#
func Forward(): Mat

Runs the network.

The example for this item is shown with the ones above: opencv-Detect.salam

ForwardLayer

#
func ForwardLayer(layer_name: str): Mat

Free

#
func Free()

Frees it.

The example for this item is shown with the ones above: opencv-Detect.salam

Detection

#
struct Detection

One object found with DNN.

NameTypeDescription
class_idint = 0The class number.
confidencef64 = 0The confidence.
xint = 0x.
yint = 0y.
widthint = 0The width.
heightint = 0The height.

The example for this item is shown with the ones above: opencv-Features.salam

VideoCapture

#
struct VideoCapture

Reads video or a camera.

NameTypeDescription
handlevoid*The internal handle.

The example for this item is shown with the ones above: opencv-Detect.salam

Ok

#
func Ok(): bool

Whether it is open.

The example for this item is shown with the ones above: opencv-Detect.salam

Read

#
func Read(): Mat

The next frame; empty at the end.

The example for this item is shown with the ones above: opencv-Detect.salam

Fps

#
func Fps(): f64

FrameCount

#
func FrameCount(): int

Close

#
func Close()

Closes it.

The example for this item is shown with the ones above: opencv-Detect.salam

VideoWriter

#
struct VideoWriter

Writes video.

NameTypeDescription
handlevoid*The internal handle.

The example for this item is shown with the ones above: opencv-Detect.salam

Ok

#
func Ok(): bool

Whether it is open.

The example for this item is shown with the ones above: opencv-Detect.salam

Write

#
func Write(frame: Mat): bool

Writes a frame.

The example for this item is shown with the ones above: opencv-Detect.salam

Close

#
func Close()

Closes it.

The example for this item is shown with the ones above: opencv-Detect.salam

Keypoint

#
struct Keypoint

One keypoint.

NameTypeDescription
xf64 = 0x.
yf64 = 0y.
sizef64 = 0The size.
anglef64 = 0The angle.
responsef64 = 0The strength.

The example for this item is shown with the ones above: opencv-Features.salam

Keypoints

#
struct Keypoints

Keypoints and descriptors.

NameTypeDescription
handlevoid*The internal handle.

The example for this item is shown with the ones above: opencv-Features.salam

Ok

#
func Ok(): bool

Whether it is valid.

The example for this item is shown with the ones above: opencv-Features.salam

Count

#
func Count(): int

Get

#
func Get(i: int): Keypoint

Keypoint i.

The example for this item is shown with the ones above: opencv-Features.salam

Descriptors

#
func Descriptors(): Mat

Match

#
struct Match

One match.

NameTypeDescription
query_idxint = 0The index in the first set.
train_idxint = 0The index in the second set.
distancef64 = 0The distance; lower means more alike.

The example for this item is shown with the ones above: opencv-Features.salam

DetectedObject

#
struct DetectedObject

A detected object.

NameTypeDescription
xint = 0x.
yint = 0y.
widthint = 0The width.
heightint = 0The height.

The example for this item is shown with the ones above: opencv-Detect.salam

CascadeClassifier

#
struct CascadeClassifier

A Haar cascade classifier; for face detection.

NameTypeDescription
handlevoid*The internal handle.

The example for this item is shown with the ones above: opencv-Detect.salam

Ok

#
func Ok(): bool

Whether it loaded.

The example for this item is shown with the ones above: opencv-Detect.salam

Detect

#
func Detect(m: Mat, scale_factor: f64, min_neighbors: int, max_results: int): Vector<DetectedObject>

Free

#
func Free()

Frees it.

The example for this item is shown with the ones above: opencv-Detect.salam

Contours

#
struct Contours

Contours.

NameTypeDescription
handlevoid*The internal handle.

The example for this item is shown with the ones above: opencv-Features.salam

Ok

#
func Ok(): bool

Whether it is valid.

The example for this item is shown with the ones above: opencv-Features.salam

Count

#
func Count(): int

PointCount

#
func PointCount(idx: int): int

Point

#
func Point(idx: int, pt_idx: int): Point

Area

#
func Area(idx: int): f64

BoundingRect

#
func BoundingRect(idx: int): Rect

Constants and variables

COLOR_BGR2GRAY

#
const COLOR_BGR2GRAY: i32 = 0

Color conversion: BGR to gray.

The example for this item is shown with the ones above: opencv-Basics.salam

COLOR_GRAY2BGR

#
const COLOR_GRAY2BGR: i32 = 1

Color conversion: gray to BGR.

The example for this item is shown with the ones above: opencv-Basics.salam

COLOR_RGB2GRAY

#
const COLOR_RGB2GRAY: i32 = 2

Color conversion: RGB to gray.

The example for this item is shown with the ones above: opencv-Basics.salam

COLOR_GRAY2RGB

#
const COLOR_GRAY2RGB: i32 = 3

Color conversion: gray to RGB.

The example for this item is shown with the ones above: opencv-Basics.salam

COLOR_BGR2RGB

#
const COLOR_BGR2RGB: i32 = 4

Color conversion: BGR to RGB.

The example for this item is shown with the ones above: opencv-Basics.salam

COLOR_RGB2BGR

#
const COLOR_RGB2BGR: i32 = 5

Color conversion: RGB to BGR.

The example for this item is shown with the ones above: opencv-Basics.salam

COLOR_BGR2HSV

#
const COLOR_BGR2HSV: i32 = 6

Color conversion: BGR to HSV.

The example for this item is shown with the ones above: opencv-Basics.salam

COLOR_HSV2BGR

#
const COLOR_HSV2BGR: i32 = 7

Color conversion: HSV to BGR.

The example for this item is shown with the ones above: opencv-Basics.salam

COLOR_RGB2HSV

#
const COLOR_RGB2HSV: i32 = 8

Color conversion: RGB to HSV.

The example for this item is shown with the ones above: opencv-Basics.salam

COLOR_HSV2RGB

#
const COLOR_HSV2RGB: i32 = 9

Color conversion: HSV to RGB.

The example for this item is shown with the ones above: opencv-Basics.salam

THRESH_BINARY

#
const THRESH_BINARY: i32 = 0

Threshold: the maximum above the threshold, zero elsewhere.

The example for this item is shown with the ones above: opencv-Filters.salam

THRESH_BINARY_INV

#
const THRESH_BINARY_INV: i32 = 1

Threshold: inverted binary.

The example for this item is shown with the ones above: opencv-Filters.salam

THRESH_TRUNC

#
const THRESH_TRUNC: i32 = 2

Threshold: values above the threshold become the threshold.

The example for this item is shown with the ones above: opencv-Filters.salam

THRESH_TOZERO

#
const THRESH_TOZERO: i32 = 3

Threshold: values below the threshold become zero.

The example for this item is shown with the ones above: opencv-Filters.salam

THRESH_TOZERO_INV

#
const THRESH_TOZERO_INV: i32 = 4

Threshold: values above the threshold become zero.

The example for this item is shown with the ones above: opencv-Filters.salam

THRESH_OTSU

#
const THRESH_OTSU: i32 = 5

Threshold: Otsu's automatic threshold.

The example for this item is shown with the ones above: opencv-Filters.salam

ADAPTIVE_MEAN

#
const ADAPTIVE_MEAN: i32 = 0

Adaptive threshold with the neighborhood mean.

The example for this item is shown with the ones above: opencv-Filters.salam

ADAPTIVE_GAUSSIAN

#
const ADAPTIVE_GAUSSIAN: i32 = 1

Adaptive threshold with a Gaussian weighted mean.

The example for this item is shown with the ones above: opencv-Filters.salam

INTERP_NEAREST

#
const INTERP_NEAREST: i32 = 0

Interpolation: nearest neighbor.

The example for this item is shown with the ones above: opencv-Basics.salam

INTERP_LINEAR

#
const INTERP_LINEAR: i32 = 1

Interpolation: bilinear.

The example for this item is shown with the ones above: opencv-Basics.salam

INTERP_CUBIC

#
const INTERP_CUBIC: i32 = 2

Interpolation: bicubic.

The example for this item is shown with the ones above: opencv-Basics.salam

INTERP_AREA

#
const INTERP_AREA: i32 = 3

Interpolation: area based, the best for shrinking.

The example for this item is shown with the ones above: opencv-Basics.salam

INTERP_LANCZOS4

#
const INTERP_LANCZOS4: i32 = 4

Interpolation: Lanczos.

The example for this item is shown with the ones above: opencv-Basics.salam

ROTATE_90_CW

#
const ROTATE_90_CW: i32 = 0

Rotate ninety degrees clockwise.

The example for this item is shown with the ones above: opencv-Basics.salam

ROTATE_180

#
const ROTATE_180: i32 = 1

Rotate one hundred and eighty degrees.

The example for this item is shown with the ones above: opencv-Basics.salam

ROTATE_90_CCW

#
const ROTATE_90_CCW: i32 = 2

Rotate ninety degrees counterclockwise.

The example for this item is shown with the ones above: opencv-Basics.salam

FLIP_VERTICAL

#
const FLIP_VERTICAL: i32 = 0

Vertical flip.

The example for this item is shown with the ones above: opencv-Basics.salam

FLIP_HORIZONTAL

#
const FLIP_HORIZONTAL: i32 = 1

Horizontal flip.

The example for this item is shown with the ones above: opencv-Basics.salam

FLIP_BOTH

#
const FLIP_BOTH: i32 = 2

Flip in both directions.

The example for this item is shown with the ones above: opencv-Basics.salam

MORPH_OPEN

#
const MORPH_OPEN: i32 = 0

Opening: erosion then dilation; removes small specks.

The example for this item is shown with the ones above: opencv-Filters.salam

MORPH_CLOSE

#
const MORPH_CLOSE: i32 = 1

Closing: dilation then erosion; fills small holes.

The example for this item is shown with the ones above: opencv-Filters.salam

MORPH_GRADIENT

#
const MORPH_GRADIENT: i32 = 2

Gradient: the outline of the shapes.

The example for this item is shown with the ones above: opencv-Filters.salam

MORPH_TOPHAT

#
const MORPH_TOPHAT: i32 = 3

Top hat.

The example for this item is shown with the ones above: opencv-Filters.salam

MORPH_BLACKHAT

#
const MORPH_BLACKHAT: i32 = 4

Black hat.

The example for this item is shown with the ones above: opencv-Filters.salam

BITWISE_AND

#
const BITWISE_AND: i32 = 0

Bitwise AND.

The example for this item is shown with the ones above: opencv-Filters.salam

BITWISE_OR

#
const BITWISE_OR: i32 = 1

Bitwise OR.

The example for this item is shown with the ones above: opencv-Filters.salam

BITWISE_XOR

#
const BITWISE_XOR: i32 = 2

Bitwise exclusive or.

The example for this item is shown with the ones above: opencv-Filters.salam

NORM_HAMMING

#
const NORM_HAMMING: i32 = 0

Hamming distance; for ORB descriptors.

The example for this item is shown with the ones above: opencv-Features.salam

NORM_L2

#
const NORM_L2: i32 = 1

Euclidean distance; for SIFT.

The example for this item is shown with the ones above: opencv-Features.salam

Functions

RGB

#
func RGB(r: int, g: int, b: int): Color

A color from red, green and blue.

The example for this item is shown with the ones above: opencv-Basics.salam

Black

#
func Black(): Color

Black.

The example for this item is shown with the ones above: opencv-Basics.salam

White

#
func White(): Color

White.

The example for this item is shown with the ones above: opencv-Basics.salam

Red

#
func Red(): Color

Red.

The example for this item is shown with the ones above: opencv-Basics.salam

Green

#
func Green(): Color

Green.

The example for this item is shown with the ones above: opencv-Basics.salam

Blue

#
func Blue(): Color

Blue.

The example for this item is shown with the ones above: opencv-Basics.salam

Read

#
func Read(path: str): Mat

Reads an image from a file.

The example for this item is shown with the ones above: opencv-Basics.salam

Write

#
func Write(path: str, m: Mat): bool

Writes an image to a file.

The example for this item is shown with the ones above: opencv-Basics.salam

NewBlank

#
func NewBlank(width: int, height: int, channels: int, fill: Color): Mat

A canvas filled with a color.

The example for this item is shown with the ones above: opencv-Basics.salam

Zeros

#
func Zeros(width: int, height: int, channels: int): Mat

A black canvas.

The example for this item is shown with the ones above: opencv-Basics.salam

Imshow

#
func Imshow(window: str, m: Mat)

Shows an image in a window.

The example for this item is shown with the ones above: opencv-Detect.salam

WaitKey

#
func WaitKey(delay_ms: int): int

Waits up to delay milliseconds for a key; the key code or -1.

The example for this item is shown with the ones above: opencv-Detect.salam

DestroyWindow

#
func DestroyWindow(window: str)

Closes a window.

The example for this item is shown with the ones above: opencv-Detect.salam

DestroyAllWindows

#
func DestroyAllWindows()

Closes all windows.

The example for this item is shown with the ones above: opencv-Detect.salam

CreateTrackbar

#
func CreateTrackbar(name: str, window: str, initial: int, max: int): bool

A slider in a window.

The example for this item is shown with the ones above: opencv-Detect.salam

GetTrackbarPos

#
func GetTrackbarPos(name: str, window: str): int

The position of a slider.

The example for this item is shown with the ones above: opencv-Detect.salam

SetTrackbarPos

#
func SetTrackbarPos(name: str, window: str, pos: int)

Sets the position.

The example for this item is shown with the ones above: opencv-Detect.salam

LoadNet

#
func LoadNet(model_path: str, config_path: str): Net

A model and its configuration, such as Caffe.

The example for this item is shown with the ones above: opencv-Detect.salam

LoadNetSingleFile

#
func LoadNetSingleFile(path: str): Net

A single file model, such as ONNX.

The example for this item is shown with the ones above: opencv-Detect.salam

ParseSSDDetections

#
func ParseSSDDetections(output: Mat, img_width: int, img_height: int, confidence_threshold: f64): Vector<Detection>

Turns SSD output into the objects whose confidence is above the threshold.

The example for this item is shown with the ones above: opencv-Detect.salam

OpenVideo

#
func OpenVideo(path: str): VideoCapture

Opens a video file.

The example for this item is shown with the ones above: opencv-Detect.salam

OpenCamera

#
func OpenCamera(index: int): VideoCapture

A camera by number.

The example for this item is shown with the ones above: opencv-Detect.salam

NewVideoWriter

#
func NewVideoWriter(path: str, fourcc: str, fps: f64, width: int, height: int): VideoWriter

A writer with a four letter codec, frames per second and a size.

The example for this item is shown with the ones above: opencv-Detect.salam

LastError

#
func LastError(): str

The message of the last error.

The example for this item is shown with the ones above: opencv-Basics.salam

Available

#
func Available(): bool

True when OpenCV reports a version. A program whose shim library is missing does not start at all, so once your code runs this is true.

The example for this item is shown with the ones above: opencv-Basics.salam

Version

#
func Version(): str

The OpenCV version.

The example for this item is shown with the ones above: opencv-Basics.salam

MatchDescriptors

#
func MatchDescriptors(desc1: Mat, desc2: Mat, max_matches: int, norm: int): Vector<Match>

The best matches between two sets of descriptors.

The example for this item is shown with the ones above: opencv-Features.salam

LoadCascade

#
func LoadCascade(path: str): CascadeClassifier

Loads a classifier from an XML file.

The example for this item is shown with the ones above: opencv-Detect.salam

FromImage

#
func FromImage(img: image.Image): Mat

From an image of the image package.

The example for this item is shown with the ones above: opencv-Detect.salam

ToImage

#
func ToImage(m: Mat): image.Image

To an image of the image package.

The example for this item is shown with the ones above: opencv-Detect.salam