![](/img/trans.png)
[英]How to convert 2D bounding box pixel coordinates (x, y, w, h) into relative coordinates (Yolo format)?
[英]How to convert Yolo format bounding box coordinates into OpenCV format
我有保存在.txt
文件中的对象的Yolo
格式边界框注释。 现在我想加载这些坐标并使用OpenCV
在图像上绘制它,但我不知道如何将这些浮点值转换为OpenCV
格式的坐标值
我尝试了这篇文章,但没有帮助,下面是我正在尝试做的示例示例
代码和输出
import matplotlib.pyplot as plt
import cv2
img = cv2.imread(<image_path>)
dh, dw, _ = img.shape
fl = open(<label_path>, 'r')
data = fl.readlines()
fl.close()
for dt in data:
_, x, y, w, h = dt.split(' ')
nx = int(float(x)*dw)
ny = int(float(y)*dh)
nw = int(float(w)*dw)
nh = int(float(h)*dh)
cv2.rectangle(img, (nx,ny), (nx+nw,ny+nh), (0,0,255), 1)
plt.imshow(img)
实际注释和图像
0 0.286972 0.647157 0.404930 0.371237
0 0.681338 0.366221 0.454225 0.418060
还有另外一个Q&A关于这个主题,而且也该接受的答案低于1个有趣的评论。 最重要的是,YOLO 坐标与图像具有不同的居中位置。 不幸的是,评论员没有提供 Python 端口,所以我在这里做了:
import cv2
import matplotlib.pyplot as plt
img = cv2.imread(<image_path>)
dh, dw, _ = img.shape
fl = open(<label_path>, 'r')
data = fl.readlines()
fl.close()
for dt in data:
# Split string to float
_, x, y, w, h = map(float, dt.split(' '))
# Taken from https://github.com/pjreddie/darknet/blob/810d7f797bdb2f021dbe65d2524c2ff6b8ab5c8b/src/image.c#L283-L291
# via https://stackoverflow.com/questions/44544471/how-to-get-the-coordinates-of-the-bounding-box-in-yolo-object-detection#comment102178409_44592380
l = int((x - w / 2) * dw)
r = int((x + w / 2) * dw)
t = int((y - h / 2) * dh)
b = int((y + h / 2) * dh)
if l < 0:
l = 0
if r > dw - 1:
r = dw - 1
if t < 0:
t = 0
if b > dh - 1:
b = dh - 1
cv2.rectangle(img, (l, t), (r, b), (0, 0, 255), 1)
plt.imshow(img)
plt.show()
因此,对于某些 Lenna 图像,这将是输出,我认为它显示了您的图像的正确坐标:
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.8.5
Matplotlib: 3.3.2
OpenCV: 4.4.0
----------------------------------------
1请为链接的答案和评论点赞。
@HansHirse 这真的很有帮助。 非常感激。 我想知道我们如何才能反向执行此操作? 就我而言,我想将 OpenCV 坐标转换为 YOLO 格式。 我尝试了堆栈溢出中的几个链接,但对我没有任何作用......这与我现在遇到的问题相同: 将 opencv 矩形坐标转换为 yolo 对象坐标以进行图像标记
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.