運城 網(wǎng)站制作企業(yè)郵箱賬號
第一章
目標:為了查看自己在標注標簽時是否準確,寫了這段代碼來將標注的框打到原圖上
第二章
步驟:進行反歸一化得到坐標畫出矩形框
第二行是目標圖片對應(yīng)的txt,第三行是目標圖片
第三章
全部代碼如下:
import cv2
import numpy as nplabel_path = 'C:/Users/23918/Desktop/01_missing_hole_01.txt'
image_path = 'C:/Users/23918/Desktop/01_missing_hole_01.jpg'# 坐標轉(zhuǎn)換,原始存儲的是YOLOv5格式
# Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
def xywh2xyxy(x, y, w, h, w1, h1, img):print("原圖寬高:\nw1={}\nh1={}".format(w1, h1))# 邊界框反歸一化x_t = x * w1y_t = y * h1w_t = w * w1h_t = h * h1print("反歸一化后輸出:\n第一個:{}\t第二個:{}\t第三個:{}\t第四個:{}\t\n\n".format(x_t, y_t, w_t, h_t))# 計算坐標top_left_x = x_t - w_t / 2top_left_y = y_t - h_t / 2bottom_right_x = x_t + w_t / 2bottom_right_y = y_t + h_t / 2print("左上x坐標:{}".format(top_left_x))print("左上y坐標:{}".format(top_left_y))print("右下x坐標:{}".format(bottom_right_x))print("右下y坐標:{}".format(bottom_right_y))# 繪圖 rectangle()函數(shù)需要坐標為整數(shù)cv2.rectangle(img, (int(top_left_x), int(top_left_y)), (int(bottom_right_x), int(bottom_right_y)), (0, 255, 0), 2)# cv2.imshow('show', img)cv2.imwrite('11.png', img)cv2.waitKey(0) # 按鍵結(jié)束cv2.destroyAllWindows()# 讀取labels
with open(label_path, 'r') as f:lines = f.read().strip().splitlines()lb = np.array([x.split() for x in lines], dtype=np.float32) # labelsprint(lb)# 讀取圖像文件
img = cv2.imread(str(image_path))
h, w = img.shape[:2]# 反歸一化并得到左上和右下坐標,畫出矩形框
for label in lb:x, y, width, height = label[:4]xywh2xyxy(x, y, width, height, w, h, img)