主要流程:
读取标签文件数据,打开图像,利用opencv-python库,在原图中画出标签的bbox检测框,并可以保存。
先说明一下我们的文件结构:
训练集:我们在案例中将训练集目录命名为images
然后训练集目录内全部都是jpg图像。
例如:
|-- images
| |-- 000000000009.jpg
| |-- 000000000025.jpg
| |-- 000000000030.jpg
| |-- ...
训练集标签:我们在案例中将训练集目录命名为labels
然后训练集标签目录内全部都是txt文件。
|-- labels
| |-- 000000000009.txt
| |-- 000000000025.txt
| |-- 000000000030.txt
| |-- ...
本问代码读取的标签格式是yolo格式的
txt标签内容格式例如:
0 0.3125 0.179104 0.0453125 0.0985075
简单介绍:
每行一共5个数据,数据与数据之间空格隔开。
第一个数据0
表示分类的类别序号
第二个数据0.3125
表示x_center/width,即检测框中点的x坐标除以图像宽度。
第三个数据0.179104
表示y_center/height,即检测框中点的y坐标除以图像高度。
第四个数据0.0453125
表示roi_width/width。即检测框的宽度除以图像宽度。
第五个数据 0.0985075
表示roi_width/width。即检测框的高度除以图像高度。
然后我们的代码如下:
具体路径根据实际情况而定
import os
import cv2
def main():
# 总的检测根目录
path_root_labels = './test_data/label'
# 总的检测根目录
path_root_imgs ='./test_data/img'
type_object = '.txt'
for ii in os.walk(path_root_imgs):
for j in ii[2]:
type = j.split(".")[1]
if type != 'jpg':
continue
path_img = os.path.join(path_root_imgs, j)
print(path_img)
label_name = j[:-4]+type_object
path_label = os.path.join(path_root_labels, label_name)
# print(path_label)
f = open(path_label, 'r+', encoding='utf-8')
if os.path.exists(path_label) == True:
img = cv2.imread(path_img)
w = img.shape[1]
h = img.shape[0]
new_lines = []
img_tmp = img.copy()
while True:
line = f.readline()
if line:
msg = line.split(" ")
# print(x_center,",",y_center,",",width,",",height)
x1 = int((float(msg[1]) - float(msg[3]) / 2) * w) # x_center - width/2
y1 = int((float(msg[2]) - float(msg[4]) / 2) * h) # y_center - height/2
x2 = int((float(msg[1]) + float(msg[3]) / 2) * w) # x_center + width/2
y2 = int((float(msg[2]) + float(msg[4]) / 2) * h) # y_center + height/2
print(x1,",",y1,",",x2,",",y2)
cv2.rectangle(img_tmp,(x1,y1),(x2,y2),(0,0,255),5)
else :
break
cv2.imshow("show", img_tmp)
c = cv2.waitKey(0)
if __name__ == '__main__':
main()