簡體   English   中英

如何將 Yolo 格式的邊界框坐標轉換為 OpenCV 格式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM