YOLOv5识别目标的实时坐标打印

引言

这个功能看似鸡肋,但对于无人机目标识别与追踪有重要意义,通过目标在摄像头视野的坐标位置,可以推算出无人机相对与目标的位置,从而对无人机进行位置矫正。因此,添加代码打印坐标并不是主要目的,关键在于寻找坐标信息在工程中的位置。

实现

在utils文件夹下的plot.py中plot_one_box函数下添加下面三行代码,输出目标框的五点坐标。

print("左上点的坐标为:(" + str(c1[0]) + "," + str(c1[1]) + "),右上点的坐标为(" + str(c2[0]) + "," + str(c1[1]) + ")")
print("左下点的坐标为:(" + str(c1[0]) + "," + str(c2[1]) + "),右下点的坐标为(" + str(c2[0]) + "," + str(c2[1]) + ")")
print("中心点的坐标为:(" + str((c2[0] - c1[0]) / 2 + c1[0]) + "," + str((c2[1] - c1[1]) / 2 + c1[1]) + ")")

注意,坐标原点是捕捉到画面左上角

给出修改后的plot_one_box()函数完整代码:

def plot_one_box(x, img, color=None, label=None, line_thickness=3):
    # Plots one bounding box on image img
    tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1  # line/font thickness
    color = color or [random.randint(0, 255) for _ in range(3)]
    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
    cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
    ######################################打印坐标#############################
    print("左上点的坐标为:(" + str(c1[0]) + "," + str(c1[1]) + "),右上点的坐标为(" + str(c2[0]) + "," + str(c1[1]) + ")")
    print("左下点的坐标为:(" + str(c1[0]) + "," + str(c2[1]) + "),右下点的坐标为(" + str(c2[0]) + "," + str(c2[1]) + ")")
    print("中心点的坐标为:(" + str((c2[0] - c1[0]) / 2 + c1[0]) + "," + str((c2[1] - c1[1]) / 2 + c1[1]) + ")")
    ##########################################################################    
    if label:
        tf = max(tl - 1, 1)  # font thickness
        t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
        c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
        cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)  # filled
        cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)

效果

  1. 运行图片识别

可以看到在运行结果中打印出了各个目标的位置信息

  1. 视频识别

打印出视频中每一帧图片中目标位置。

  1. 单摄像头实时检测

在30FPS的帧率下打印出每一帧的目标位置。

  1. 多摄像头实时检测

在多线程识别时仍然能有效打印出坐标。

求学路上,你我共勉(๑•̀ㅂ•́)و✧

猜你喜欢

转载自blog.csdn.net/Albert_yeager/article/details/128839453