参考链接
def getBox(img_path, txt_path):
"""
:param img_path: 图片文件的路径
:param txt_path: 标签文件的路径
:return:
"""
img = cv2.imread(img_path)
h, w, _ = img.shape
with open(txt_path, "r") as fp:
contline = fp.readline().split(' ')
if len(contline)>1:
xmin = float((contline[1]).strip()) - float(contline[3].strip()) / 2
xmax = float(contline[1].strip()) + float(contline[3].strip()) / 2
ymin = float(contline[2].strip()) - float(contline[4].strip()) / 2
ymax = float(contline[2].strip()) + float(contline[4].strip()) / 2
xmin, xmax = w * xmin, w * xmax
ymin, ymax = h * ymin, h * ymax
return [xmin, ymin, xmax, ymax]
else:
return [0, 0, 0, 2, 2]
import os
import cv2
img_folder = '/share1/luli/yolov8/test/images'
label_folder = '/share1/luli/yolov8/test/labels'
jpg_files = [file for file in os.listdir(img_folder) if file.lower().endswith('.jpg')]
selected_images = jpg_files[:]
for image in selected_images:
file_nmae = image.split('.')[0]
img1 = os.path.join(img_folder, image)
print(img1)
img2 = cv2.imread(img1)
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
label_name = file_nmae + '.txt'
label = os.path.join(label_folder, label_name)
print(label)
box = getBox(img1, label)
cv2.rectangle(img2, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0), 2)
temp = img_folder.replace('images','img_label')
temp_image_path = os.path.join(temp, f"{file_nmae}_annotated.jpg")
plt.imsave(temp_image_path,img2)