程序员

视觉测距算法-目标测距,防撞预测

2020-09-05  本文已影响0人  gaoshine

视觉测距算法-目标测距,防撞预测

实际课题,车间有多个不同高程的天车,操作人员通过遥控操控天车,经常会出现较低的天车被撞的事故,计划采用通过反光标志,计算位置,通过算法实现测距和报警.
经过现场勘查,拟采用绿色的反光条拼接的矩形色块作为识别标志.

0.算法原理

distance.jpeg

我在测试环境中,尽量采用已知的尺寸的目标做测试,目前在用的iphone7手机,查询屏幕尺寸为:114.3mm(w)
拿A4纸测试测试 297mmx210mm
210mm --> 520 pix
297mm --> 380 pix
用相似三角形计算物体或者目标到相机的距离
我们将使用相似三角形来计算相机到一个已知的物体或者目标的距离。
相似三角形就是这么一回事:假设我们有一个宽度为 W 的目标或者物体。然后我们将这个目标放在距离我们的相机为 D 的位置。我们用相机对物体进行拍照并且测量物体的像素宽度 P 。这样我们就得出了相机焦距的公式:

F = (P x D) / W

phone7屏幕屏幕 W=114.3 D = 297 P = 520
F = 970
那么: D = F * W / P D=970*114.3/
最后得到计算公式

def distance_to_camera(knownWidth, focalLength, perWidth):

    # compute and return the distance from the maker to the camera

    return (knownWidth * focalLength) / perWidth

1.代码

"""

@File    :   demo.py    
@Contact :   gaoshine2008@qq.com
@License :   (C)Copyright 2018-2022, 金世达科技.微妙物联

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
8/30/20 21:43   GAOSHENG      1.0         we.iot

"""

import cv2
import numpy as np

# 中文字幕
from hanzi import put_chinese_text
ft = put_chinese_text('./font/yahei.ttf')

cap = cv2.VideoCapture(0)

while (1):

    # Take each frame
    _, frame = cap.read()
    print(frame.shape)
    # Convert BGR to HSV

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    sensitivity = 15
    green0 = [60 - sensitivity, 50, 50]
    green1 = [60 + sensitivity, 255, 255]

    blue0 = [110, 50, 50]
    blue1 = [130, 255, 255]
    lower_blue = np.array(green0)
    upper_blue = np.array(green1)

    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame, frame, mask=mask)

    # 查找最大的绿色色块
    cnts, _ = cv2.findContours(mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    Smax = 0
    (x0, y0, w0, h0) = (0, 0, 0, 0)
    for c in cnts:
        (x, y, w, h) = cv2.boundingRect(c)
        if w * h > Smax:
            (x0, y0, w0, h0) = (x, y, w, h)
            Smax = w * h
        print(x, y, w, h, w * h)

    if Smax > 600:
        cv2.rectangle(res, (x0, y0), (x0 + w0, y0 + h0), (0, 0, 255), 2)
        cv2.rectangle(frame, (x0, y0), (x0 + w0, y0 + h0), (0, 0, 255), 2)
        color_ = (0, 0, 255)  # red
        pos = (x0, y0 - 20)
        text_size = 20
        D = int(970*114.3/w0)  # 测距公式
        line = '距离:%s毫米     W:%s H:%s' % (D, str(w0), str(h0))
        res = ft.draw_text(res, pos, line, text_size, color_)
        frame = ft.draw_text(frame, pos, line, text_size, color_)



    cv2.imshow('frame', frame)
    cv2.imshow('mask', mask)
    cv2.imshow('res', res)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break
cv2.destroyAllWindows()

2.效果测试

我拿手机屏幕显示绿色背景,作为识别的色块,通过摄像头采集和处理,标注出手机屏幕的轮廓.
通过计算绿色屏幕的轮廓的宽和高.
将宽度带入距离公式,就可以得到目标和摄像头之间的距离.

demo0.gif

3.实际应用-天车防撞预警系统

Smart-Measure.jpg tianche.jpg
上一篇 下一篇

猜你喜欢

热点阅读