Skip to content

Latest commit

 

History

History
102 lines (69 loc) · 2.57 KB

opencv.md

File metadata and controls

102 lines (69 loc) · 2.57 KB
title
使用 OpenCV

简介

对于 MaixCAM,因为使用了 Linux, 并且性能基本能够支撑使用Python版本的OpenCV,所以除了使用maix模块,你也可以直接使用cv2模块。

本文例程以及更多可以在MaixPy/examples/vision/opencv 中找到。

注意 OpenCV 的函数基本都是 CPU 计算的,能使用 maix 的模块尽量不使用 OpenCV,因为 maix 有很多函数都是经过硬件加速过的。

加载一张图片

import cv2

file_path = "/maixapp/share/icon/detector.png"
img = cv2.imread(file_path)
print(img)

因为cv2模块比较臃肿,import cv2可能会需要一点时间。

显示图像到屏幕

但是由于直接使用了官方的 OpenCV,没有对接显示,所以要显示到屏幕上需要转换成maix.image.Image对象后再用display来显示:

from maix import display, image, time
import cv2

disp = display.Display()

file_path = "/maixapp/share/icon/detector.png"
img = cv2.imread(file_path)

img_show = image.cv2image(img)
disp.show(img_show)

while not app.need_exit():
    time.sleep(1)

使用 OpenCV 函数

以边缘检测为例:

基于上面的代码,使用cv2.Canny函数即可:

from maix import image, display, app, time
import cv2

file_path = "/maixapp/share/icon/detector.png"
img0 = cv2.imread(file_path)

disp = display.Display()

while not app.need_exit():
    img = img0.copy()

    # canny method
    t = time.ticks_ms()
    edged = cv2.Canny(img, 180, 60)
    t2 = time.ticks_ms() - t

    # show by maix.display
    t = time.ticks_ms()
    img_show = image.cv2image(edged)
    print(f"edge time: {t2}ms, convert time: {time.ticks_ms() - t}ms")
    disp.show(img_show)

使用摄像头

在 PC 上, 我们使用 OpenCVVideoCapture类来读取摄像头,对于 MaixCAM, OpenCV 没有适配,我们可以用maix.camera 模块来读取摄像头,然后给OpenCV使用。

通过image.image2cv函数将maix.image.Image对象转为numpy.ndarray对象给OpenCV使用:

from maix import image, display, app, time, camera
import cv2

disp = display.Display()
cam = camera.Camera(320, 240)

while not app.need_exit():
    img = cam.read()

    # convert maix.image.Image object to numpy.ndarray object
    t = time.ticks_ms()
    img = image.image2cv(img)
    print("time: ", time.ticks_ms() - t)

    # canny method
    edged = cv2.Canny(img, 180, 60)

    # show by maix.display
    img_show = image.cv2image(edged)
    disp.show(img_show)