过程记录 yolov3目标检测输出目标坐标和原图物体像素坐标比较

2023-05-16

设备:jetsonnano B01 一个usb广角摄像头
语言为python 库为opencv 框架pytorch
大家都知道yolov3的坐标变换过程比较复杂,大概要经过图片缩放,对数空间变换等等,然后在pytorch中是用一个tensor类型来表示张量的,所以一直认为目标检测的坐标是一个奇奇怪怪的值,需要经过变换才能得到原图目标的像素坐标
之前一直纠结怎么坐标转化,但今天实验之后怀疑其实检测结果的坐标转化为int数值以后跟实际原图像素坐标是一样的?
先上结果:
这是原始图片上的坐标点
在这里插入图片描述
左下角为像素坐标
(鼠标放在中间油渍的位置时显示的坐标

检测结果:
在这里插入图片描述
结果输出的坐标(转化为整数之后输出的)
在这里插入图片描述
两个坐标几乎一样,感觉其实它们两个是一个数值,而tensor类型后面多了一串小数点
完整代码
用opencv打开摄像头查看图片某点像素坐标:

import cv2
import os
import sys
import time
import datetime
import argparse
cap = cv2.VideoCapture(0)
i = 1


while(cap.isOpened()):
  ret, frame = cap.read()
  cv2.imshow('frame',frame)
  if cv2.waitKey(30) == ord('q'):
      #ret, frame = cap.read()
      cv2.imwrite('data/custom/dd/'+str(i)+".jpg",frame) 
      frame=cv2.imread('data/custom/dd/'+str(i)+".jpg")
      break

检测部分显示结果坐标:
pytorch python

        if detections is not None:
            # Rescale boxes to original image
            detections = rescale_boxes(detections, opt.img_size, img.shape[:2])
            unique_labels = detections[:, -1].cpu().unique()
            n_cls_preds = len(unique_labels)
            bbox_colors = random.sample(colors, n_cls_preds)
            for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections:

                print("\t+ Label: %s, Conf: %.5f" % (classes[int(cls_pred)], cls_conf.item()))                              
 
                box_w = x2 - x1
                box_h = y2 - y1
                centx = int((x1+x2)*0.1/2)
                centy = int((y1+y2)*0.1/2)
                thex.append(centx)
                they.append(centy)
                str1+="x:"
                str1+=str(centx)
                str1+=",y:"
                str1+=str(centy)
                area = int(box_w*0.1)*int(box_h*0.1)
                if area > 600: 
                 time = 30
                print("x和y"+str((x2+x1)/2)+","+str((y1+y2)/2))

                print("x:")
                print(int((x1+x2)/2))
                print("y:")
                print(int((y1+y2)/2))
                print(int(box_w*0.1))
                print(int(box_h*0.1))
              
                color = bbox_colors[int(np.where(unique_labels == int(cls_pred))[0])]
                # Create a Rectangle patch
                bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none")
                print(int(box_w)*int(box_h)*0.01)
                print(str1)
                if(box_w*box_h>50):
                    se.write("1".encode())
                    time.sleep(3)
                    se.write("0".encode())
                    se.write(str1.encode())
                    data_read = se.readline()
                    print(data_read.decode())
                # Add the bbox to the plot
                ax.add_patch(bbox)
                # Add label
                plt.text(
                    x1,
                    y1,
                    s=classes[int(cls_pred)],
                    color="white",
                    verticalalignment="top",
                    bbox={"color": color, "pad": 0},
                )

        # Save generated image with detections
        plt.axis("off")
        plt.gca().xaxis.set_major_locator(NullLocator())
        plt.gca().yaxis.set_major_locator(NullLocator())
        filename = os.path.basename(path).split(".")[0]
        #output_path = os.path.join("output", f"{filename}.png")
        #output_path = os.path.join("/data/custom/dd", f"{filename}.png")
        plt.savefig(filename, bbox_inches="tight", pad_inches=0.0)
        plt.close()
    if detections is not None:
    后面的代码是输出坐标的

关于目标检测的完整检测代码:(很长,熟悉的人不必看)

from __future__ import division
import serial as ser
import time
se=ser.Serial("/dev/ttyUSB0",115200,timeout=1)
from models import *
from utils.utils import *
from utils.datasets import *
from utils.augmentations import *
from utils.transforms import *
import cv2
import os
import sys
import time
import datetime
import argparse

from PIL import Image

import torch
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision import datasets
from torch.autograd import Variable

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.ticker import NullLocator
i = 1
cap = cv2.VideoCapture(0)
array_of_img = []
start = time.time()
directory_name=r'output'



while(cap.isOpened()):
  ret, frame = cap.read()
  cv2.imshow('frame',frame)
  if cv2.waitKey(30) == ord('q'):
      #ret, frame = cap.read()
      cv2.imwrite('data/custom/dd/'+str(i)+".jpg",frame) 
      frame=cv2.imread('data/custom/dd/'+str(i)+".jpg")
      break
# When everything done, release the capture

cap.release()

cv2.destroyAllWindows()


washtime = []
thex = []
they = []
area = 0
str1=""
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--image_folder", type=str, default="data/samples", help="path to dataset")
    parser.add_argument("--model_def", type=str, default="config/yolov3.cfg", help="path to model definition file")
    parser.add_argument("--weights_path", type=str, default="weights/yolov3.weights", help="path to weights file")
    parser.add_argument("--class_path", type=str, default="data/coco.names", help="path to class label file")
    parser.add_argument("--conf_thres", type=float, default=0.8, help="object confidence threshold")
    parser.add_argument("--nms_thres", type=float, default=0.4, help="iou thresshold for non-maximum suppression")
    parser.add_argument("--batch_size", type=int, default=1, help="size of the batches")
    parser.add_argument("--n_cpu", type=int, default=0, help="number of cpu threads to use during batch generation")
    parser.add_argument("--img_size", type=int, default=416, help="size of each image dimension")
    parser.add_argument("--checkpoint_model", type=str, help="path to checkpoint model")
    opt = parser.parse_args()
    print(opt)

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    os.makedirs("output", exist_ok=True)

    # Set up modella
    model = Darknet(opt.model_def, img_size=opt.img_size).to(device)

    if opt.weights_path.endswith(".weights"):
        # Load darknet weights
        model.load_darknet_weights(opt.weights_path)
    else:
        # Load checkpoint weights
        model.load_state_dict(torch.load(opt.weights_path))

    model.eval()  # Set in evaluation mode

    dataloader = DataLoader(
        ImageFolder(opt.image_folder, transform= \
            transforms.Compose([DEFAULT_TRANSFORMS, Resize(opt.img_size)])),
        batch_size=opt.batch_size,
        shuffle=False,
        num_workers=opt.n_cpu,
    )

    classes = load_classes(opt.class_path)  # Extracts class labels from file

    Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor

    imgs = []  # Stores image paths
    img_detections = []  # Stores detections for each image index

    print("\nPerforming object detection:")
    prev_time = time.time()
    for batch_i, (img_paths, input_imgs) in enumerate(dataloader):
        # Configure input
        input_imgs = Variable(input_imgs.type(Tensor))

        # Get detections
        with torch.no_grad():
            detections = model(input_imgs)
            detections = non_max_suppression(detections, opt.conf_thres, opt.nms_thres)

        # Log progress
        current_time = time.time()
        inference_time = datetime.timedelta(seconds=current_time - prev_time)
        prev_time = current_time
        print("\t+ Batch %d, Inference Time: %s" % (batch_i, inference_time))

        # Save image and detections
        imgs.extend(img_paths)
        img_detections.extend(detections)

    # Bounding-box colors
    cmap = plt.get_cmap("tab20b")
    colors = [cmap(i) for i in np.linspace(0, 1, 20)]

    print("\nSaving images:")
    # Iterate through images and save plot of detections
    for img_i, (path, detections) in enumerate(zip(imgs, img_detections)):

        print("(%d) Image: '%s'" % (img_i, path))

        # Create plot
        img = np.array(Image.open(path))
        plt.figure()
        fig, ax = plt.subplots(1)
        ax.imshow(img)

        # Draw bounding boxes and labels of detections
        if detections is not None:
            # Rescale boxes to original image
            detections = rescale_boxes(detections, opt.img_size, img.shape[:2])
            unique_labels = detections[:, -1].cpu().unique()
            n_cls_preds = len(unique_labels)
            bbox_colors = random.sample(colors, n_cls_preds)
            for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections:

                print("\t+ Label: %s, Conf: %.5f" % (classes[int(cls_pred)], cls_conf.item()))                              
 
                box_w = x2 - x1
                box_h = y2 - y1
                centx = int((x1+x2)*0.1/2)
                centy = int((y1+y2)*0.1/2)
                thex.append(centx)
                they.append(centy)
                str1+="x:"
                str1+=str(centx)
                str1+=",y:"
                str1+=str(centy)
                area = int(box_w*0.1)*int(box_h*0.1)
                if area > 600: 
                 time = 30
                print("x和y"+str((x2+x1)/2)+","+str((y1+y2)/2))

                print("x:")
                print(int((x1+x2)/2))
                print("y:")
                print(int((y1+y2)/2))
                print(int(box_w*0.1))
                print(int(box_h*0.1))
              
                color = bbox_colors[int(np.where(unique_labels == int(cls_pred))[0])]
                # Create a Rectangle patch
                bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none")
                print(int(box_w)*int(box_h)*0.01)
                print(str1)
                if(box_w*box_h>50):
                    se.write("1".encode())
                    time.sleep(3)
                    se.write("0".encode())
                    se.write(str1.encode())
                    data_read = se.readline()
                    print(data_read.decode())
                # Add the bbox to the plot
                ax.add_patch(bbox)
                # Add label
                plt.text(
                    x1,
                    y1,
                    s=classes[int(cls_pred)],
                    color="white",
                    verticalalignment="top",
                    bbox={"color": color, "pad": 0},
                )

        # Save generated image with detections
        plt.axis("off")
        plt.gca().xaxis.set_major_locator(NullLocator())
        plt.gca().yaxis.set_major_locator(NullLocator())
        filename = os.path.basename(path).split(".")[0]
        #output_path = os.path.join("output", f"{filename}.png")
        #output_path = os.path.join("/data/custom/dd", f"{filename}.png")
        plt.savefig(filename, bbox_inches="tight", pad_inches=0.0)
        plt.close()

串口:

se.write("50".encode())
print("缓存中的字节数")
print(se.inWaiting())
time.sleep(2)
se.write("100".encode())
print("缓存中的字节数")
print(se.inWaiting())#:返回接收缓存中的字节数
data = se.readline()
print(data.decode())
data = se.readline()
print(data.decode())
print(se.inWaiting())
se.write("my87u".encode())
print("缓存中的字节数")
print(se.inWaiting())
se.flush() #等待所有数据写出。
data = se.readline()
print(data.decode())
data = se.readline()
print(data.decode())

参数:

    parser = argparse.ArgumentParser()
    parser.add_argument("--image_folder", type=str, default="data/custom/dd2", help="path to dataset")
    parser.add_argument("--model_def", type=str, default="config/yolov3-custom.cfg", help="path to model definition file")
    parser.add_argument("--weights_path", type=str, default="checkpoints/ckpt_86.pth", help="path to weights file")
    parser.add_argument("--class_path", type=str, default="data/custom/classes.names", help="path to class label file")
    parser.add_argument("--conf_thres", type=float, default=0.8, help="object confidence threshold")
    parser.add_argument("--nms_thres", type=float, default=0.4, help="iou thresshold for non-maximum suppression")
    parser.add_argument("--batch_size", type=int, default=1, help="size of the batches")
    parser.add_argument("--n_cpu", type=int, default=0, help="number of cpu threads to use during batch generation")
    parser.add_argument("--img_size", type=int, default=416, help="size of each image dimension")
    parser.add_argument("--checkpoint_model",type=str,default="checkpoints/ckpt_86.pth", help="path to checkpoint model")
    opt = parser.parse_args()
    print(opt)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

过程记录 yolov3目标检测输出目标坐标和原图物体像素坐标比较 的相关文章

  • Ajax详解及使用Ajax时的返回值类型有哪些?

    Ajax详解 Ajax 61 异步 JavaScript 和 XML Ajax 是一种用于创建快速动态网页的技术 通过在后台与服务器进行少量数据交换 xff0c Ajax 可以使网页实现异步更新 这意味着可以在不重新加载整个网页的情况下 x
  • ubuntu20.04双系统分区

    一 分四个区 xff0c 记录下 主分区和逻辑分区目前感觉没啥影响 但是有的电脑可能数量会有限制 boot引导分区 500M 交换分区 xff0c 16G及以下与内存大小一致 根目录 xff0c 如果要安装cuda之类的尽量50G以上吧 其
  • Vins-Fusion运行kitti,euroc和tum数据集并使用evo评估

    基于ubuntu18 04 VIns Fusion 1 修改程序输出位姿信息修改为TUM格式 为了方便评估 xff0c 先将程序的输出位姿信息修改为tum格式 xff0c 需要做如下改动 1 1 回环输出位姿文件pose graph cpp
  • JETSON ORIN NX 烧录系统镜像

    所需环境 xff1a Ubuntu 操作系统 本方法适用于SDKManager 找不到套件的情况 xff01 解决方法如下 xff1a 进入NVIDIA官网 xff08 Jetson Linux 35 2 1 NVIDIA Develope
  • 解决Komodo上自带D435可以打开而外接D435i打不开的原因

    解决Komodo上自带D435可以打开而外接D435i打不开的原因 因为Komodo上装的realsense SDK 和realsense ros版本不对应以及版本太低的原因 xff0c 所以各种问题 按照realsense和realsen
  • C++泛型编程,标准模板库(STL)

    C 43 43 的特点就是添加了面向对象和泛型 面向对象是用类实现的 xff0c 泛型是用模板实现的 xff0c C 43 43 的标准模板库 STL 是泛型一个实例 xff0c 已经被集成到C 43 43 xff0c STL是一些常用的数
  • [工程编写]CMakeLists.txt 如何编写

    最近开始写一些SLAM工程 xff0c 所以对涉及到的内容做一些整理 xff0c 那么要做的第一件事情就是编写一个CMakeLists txt 本文那任乾大佬在知乎关于雷达自动驾驶SLAM的工程距离 1 信息指定 cmake版本确定 xff
  • 在执行 pip install 时遇到错误: ERROR: Complete output from command python setup.py egg_info:

    在执行 pip install 时遇到错误 xff1a pip install U docker compose ERROR Complete output from command python setup py egg info ERR
  • 树莓派登录问题

    在使用树莓派的过程中 xff0c 多次遇到了开机后输入正确密码却被重复多次要求输入的情况 xff0c 在查看他人经验后 xff0c 总结出以下两种情况及可行的方法 不确定密码是否正确 参考博客 纸末 树莓派忘记密码的解决方法 1 xff0c
  • 什么是SDK和API?

    SDK xff1a 在搭建环境的时候知道的sdk xff0c 但并不知道有什么用 SDK Software Development Kit 翻译成中文就是 34 软体开发工具组 34 是用来帮一个 产品 或 平台 开发应用程式的工具组 xf
  • 华为开发者大会总结——个人总结

    方舟编译器 xff08 开源 xff09 xff1a 干掉Java虚拟机 将java代码直接编译成机器码 xff0c 静态语义好编译 xff0c 核心是静态编译出动态语义 xff08 通过华为编译实验室的核心专利 xff09 xff0c 代
  • LoRa关键参数 1、扩频因子(SF) 2、编码率(CR) 3、信号带宽(BW) 4、LoRa信号带宽BW、符号速率Rs和数据速率DR的关系 5、

    LoRa 学习 xff1a LoRa 关键参数 xff08 扩频因子 xff0c 编码率 xff0c 带宽 xff09 的设定及解释 1 扩频因子 xff08 SF xff09 2 编码率 xff08 CR xff09 3 信号带宽 xff
  • MarkDown的语法

    使用MarkDoown时应该注意些什么呢 目录 一 添加标题 二 引用代码块 三 嵌入图片 1 本地图片 2 互联网图片 四 快捷键使用 五 分界线的使用 一 添加标题 在文字前加入相应数量的 一级标题 二级标题 三级标题 四级标题 五级标
  • python试爬李毅吧贴子标题,爬虫最初级

    注 xff1a 以下所有python代码均运行于2 7 0 最近想抓点数据存起来 xff0c 开始捣鼓python 爬虫技术以前没接触过 xff0c 这一回就当练手 xff0c 从零开始 xff0c 从最原始的方式开始 先定个小目标 xff
  • Activity的生命周期

    图来自百度百科 onCreate 启动activity时被调用 xff0c 用于进行初始化操作 xff08 加载布局 绑定事件等 xff09 xff0c 不应在onCreate 中做过多的不必要操作 xff0c 避免造成打开activity
  • Activity的启动模式

    以下为读书笔记 xff1a 实际项目中 xff0c 我们要通过特定的需求 xff0c 为每个活动指定恰当的启动模式 Android一共有4种启动模式 xff1a standard singleTop singleTask singleIns
  • PID参数 Ziegler-Nichols基于时域响应曲线的整定 反应曲线法

    PID控制器是工业过程控制中广泛采用的一种控制器 xff0c 其中 xff0c P I D分别为比例 xff08 Proportion xff09 积分 xff08 Integral xff09 微分 xff08 Differential
  • 郑学坚《微型计算机原理及应用》考点精讲 36讲

    链接 xff1a https pan baidu com s 12 vGBRrjOd UtO8P4e9bow 提取码 xff1a tqmp 当初考研时买的网课 xff0c 现在也用不着了 xff0c 赠与有缘人 书籍记录着别人多年时光总结出
  • 几种常用排序算法

    排序算法代码如下 xff1a void Sort Algorithm Bubble Sort int amp nums const int len bool haschange 61 true for int i 61 0 i lt len
  • 四旋翼姿态解算

    代码思路如下 xff1a 姿态解算 void IMU update float dT imu state st state float gyr VEC XYZ s32 acc VEC XYZ s16 mag val VEC XYZ imu

随机推荐

  • 树莓派4B-基于MCP2515的CAN通信过程记录篇

    本文主要记录使用树莓派4B xff0c 通过外接MCP2515模块来实现CAN通信 xff0c 使用基于Can utils实现CAN消息的收发 准备工作 xff1a 树莓派MCP2515模块杜邦线若干 知乎上一篇较为详细的参考 xff0c
  • nuxt踩坑集

    目录结构 assets 资源文件 用于组织未编译的静态资源如 LESS SASS或 JavaScript components 组件 layouts page 模板页面 xff0c 默认为 default vue可以在这个目录下创建全局页面
  • 记录个人在安装D435i驱动时出现的问题及解决方案

    目录 1 驱动安装 xff1a 2 启动Intel RealSense Viewer后报错No Frames Recevied 3 Record时报错Error opening file 1 驱动安装 xff1a 参考这篇博客 xff1a
  • 深度学习常见的优化算法

    文章目录 1 梯度下降算法 xff08 batch gradient descent BGD 2 随机梯度下降法 xff08 Stochastic gradient descent SGD 3 小批量梯度下降 Mini batch grad
  • vscode如何链接github

    1 首先安装配置好vscode xff1a https code visualstudio com download 然后下载git xff1a https git scm com download 根据自己的电脑选择相应的版本的下载就好了
  • 串口(uart)开发流程

    UART概述 UART全称 xff0c Universal Asynchronous Receiver and Transmitter UART xff0c 一般是每个单片机或开发板必备的一个功能模块 xff0c 可以用来调试 xff0c
  • *33.硬中断和软中断是什么?区别?

    1 硬中断 硬件中断 像磁盘 xff0c 网卡 xff0c 键盘 xff0c 时钟等 2 软中断 软件中断 进程产生 区别 xff1a xff08 产生机制 处理顺序 可否屏蔽 中断信号由来 xff09 1 软中断的发生的时间是由程序控制的
  • gazebo学习时遇到的问题(PX4篇)

    最近在研究如何使用UAV xff0c 由于是初学者 xff0c 不好直接上手实体无人机 xff0c 因此考虑通过在gazebo中模拟的方式进行一下无人机的简单使用模拟 xff0c 于是了解到了PX4这个东西 xff0c 他不仅支持固件写入
  • 阿里云服务器的搭建和部署(小白教程)

    阿里云服务器的搭建和部署 xff08 小白教程 xff09 一 购买服务器二 管理云服务器三 环境配置1 JDK的配置与下载2 tomcat的配置与下载3 MySQL的安装与配置 四 外网访问服务器 个人推荐阿里云 因为里面有一个大学生的云
  • 一篇带你搞懂Python3 中的 def __init__

    在学习python 100 days时 xff0c 在面向对象编程基础的那一块 xff0c 封装一个class时 xff0c 突然出现def init 的方法 xff0c 刚开始时 xff0c 对他的理解很模糊 xff0c 为什么定义一个类
  • 时间序列异常检测综述

    1 Introduction 时序异常检测几个可以运用的点 xff1a 1 欺诈检测 2 工业数据检测 简介一下 xff1a 异常检测很久之前就有了 最早可以追溯到 J Fox 1972 Outliers in Time Series Jo
  • Linux基础----Makefile(1)

    前言 刚开始学习Linux xff0c 这些那真的是新知识 xff0c 由于感觉将来FPGA的学习会越来越靠近软件的方向发展 xff0c 所以觉得有必要好好地学习一下嵌入式的东西 xff0c 因此有必要把学习的过程记录下来 xff0c 方便
  • 【OpenCV】ChArUco标定板角点的检测Detection of ChArUco Corners

    opencv3 4 15源文档链接 link ChArUco标定板角点的检测 GoalSource codeCharuco板创建ChArUco板检测ChArUco姿势估计 ArUco标记和板的快速检测和多功能性是非常有用的 然而 xff0c
  • 错误 MSB3721

    错误 MSB3721 命令 C Program Files NVIDIA GPU Computing Toolkit CUDA v10 2 bin nvcc exe gencode 61 arch 61 compute 30 code 61
  • 倒立摆状态反馈控制——分析、建模与仿真(matlab)

    倒立摆状态反馈控制 引言 倒立摆是机器人学中一个非常重要的模型 xff0c 火箭 导弹 独轮车 双足机器人 四足机器人 xff0c 基本都是倒立摆的变形 问题描述 关于倒立摆的问题描述如下 xff1a 如图所示的倒立摆系统 摆的关节连接在一
  • docker pull rabbitmq:management 怎样指定版本

    docker pull rabbitmq 3 8 1 management
  • git 命令学习

    git 命令学习 git clone https github com zhaji01 notes git 克隆远程仓库 git status 本地仓库状态 git add lt file gt 把修改 xff08 包括创建 修改 删除 解
  • 【实例记录】在ubuntu上运行python实现与单片机多线程串口通信

    文章目录 工具步骤 工具 工具 xff1a 自己电脑双系统的ubuntu18 04 单片机esp8266 一个usb转ttl模块 xff0c ubuntu上已经下载了python的3 6和pip xff0c 还需要pip install s
  • 【过程记录 】windows和ubuntu两台电脑局域网进行socket通信收发数据和传输文件

    实验图片和前期准备 xff1a ubuntu作为服务端 xff0c windows客户端传输数据和文件 xff1a windows作为服务端 xff0c ubuntu作为客户端 xff1a 实验图片和前期准备 xff1a 服务端发送和接受i
  • 过程记录 yolov3目标检测输出目标坐标和原图物体像素坐标比较

    设备 xff1a jetsonnano B01 一个usb广角摄像头 语言为python 库为opencv 框架pytorch 大家都知道yolov3的坐标变换过程比较复杂 xff0c 大概要经过图片缩放 xff0c 对数空间变换等等 xf