前言:
需要确定YOLOv8检测到的目标中心点的坐标,并将坐标输出至文本文档中保存。
一、plotting.py
将下面的代码插入到ultralytics/utils/plotting.py文件中。
# Calculate the center point coordinates
center_x = (p2[0] - p1[0]) / 2 + p1[0]
center_y = (p2[1] - p1[1]) / 2 + p1[1]
# Define the complete file path
base_path = "D:/YOLOv8-apple/ultralytics-main/ultralytics-main/"
file_directory = "runs/detect/location"
filename = "center.txt"
full_path = os.path.join(base_path, file_directory, filename)
# Ensure the directory exists
os.makedirs(os.path.dirname(full_path), exist_ok=True)
# Append the center coordinates to the specified file
with open(full_path, 'a') as file:
file.write(f"{center_x}, {center_y}\n")
具体插入位置如下图所示:
二、产生问题
每次运行代码可能会导致前一次的坐标信息和本次运行得到的坐标信息放在一起产生冲突。
解决:将下面代码插入到ultralytics/models/yolo/detect/predict.py文件夹中。
base_path = "D:/YOLOv8-apple/ultralytics-main/ultralytics-main/"
file_directory = "runs/detect/location"
filename = "center.txt"
full_path = os.path.join(base_path, file_directory, filename)
# Ensure the directory exists
os.makedirs(os.path.dirname(full_path), exist_ok=True)
# 清空文件内容
with open(full_path, 'w') as file:
pass # 打开文件后立即关闭,用来清空文件内容
具体插入位置如下图所示:
至此完成,运行检测程序即可自动将目标中心点坐标信息存储到指定位置的文件夹中。、
注:自己阅读代码,然后想的方法实现的,方法比较简单仅供参考。
其他方式比如改动ultralytics/engine/predictor.py或者ultralytics/engine/results.py,或其他的文件应该都能够实现。因为我能力有限才之暂时弄了这个笨拙的方式。
总结:
明确改动位置和改动目标,进一步产生改动思路,落实到具体的改动实现。