利用opencv在图片中绘制YOLO标签文件(.txt)中的矩形框:
import cv2
import os
def cut_one_image(img_path, txt_path):
# 读取txt文件信息
def read_list(txt_path):
pos = []
with open(txt_path, 'r') as file_to_read:
while True:
lines = file_to_read.readline() # 整行读取数据
if not lines:
break
pass
# 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,'字符。
p_tmp = [float(i) for i in lines.split(' ')]
pos.append(p_tmp) # 添加新读取的数据
# Efield.append(E_tmp)
pass
return pos
# txt转换为box
def convert(size, box):
print(size) # h,w
xmin = (box[1] - box[3] / 2.) * size[1]
xmax = (box[1] + box[3] / 2.) * size[1]
ymin = (box[2] - box[4] / 2.) * size[0]
ymax = (box[2] + box[4] / 2.) * size[0]
box = (int(xmin), int(ymin), int(xmax), int(ymax))
return box
image = cv2.imread(img_path)
pos = read_list(txt_path)
for i in range(len(pos)):
box = convert(image.shape, pos[i])
image = cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 1)
cv2.imshow('000001', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# save_path = path + '_' + str(i) + '.jpg'
# print(save_path)
# img = image[box[1]:box[3], box[0]:box[2]]
# cv2.imwrite(save_path, img)
def choose_one(img_folder, label_folder, i):
# img_list = os.listdir(img_folder)
# img_list.sort()
#
# label_list = os.listdir(label_folder)
# label_list.sort()
#
# img_path = img_folder + "/" + img_list[i]
# path1 = img_path.split(".")[0].split("/")[1]
# print(path1)
# txt_path = label_folder + "/" + label_list[i]
cut_one_image(img_path=img_folder, txt_path=label_folder)
if __name__ == '__main__':
choose_one(img_folder="train/image/000001.jpg", label_folder = "train/labels/000001.txt", i=0)