本文的目标是制作目标检测的数据集
使用的工具是 python + opencv
实现目标
1.批量图片重命名,手动框选图片中的目标,将目标框按照一定格式保存到txt中
图片名格式(批量)
00001.jpg 00002.jpg 00003.jpg
目标包围框储存格式
00001.jpg car 124 149 362 301 00002.jpg car 113 125 275 348 00003.jpg car 164 96 380 311 00001.jpg car 158 80 326 274 00002.jpg car 135 61 352 300 00003.jpg car 125 65 363 292
实现代码
# -*- coding: cp936 -*- import os import cv2 import numpy as np # 当鼠标按下时变为 True drawing = False ix,iy = -1,-1 ox,oy = -1,-1 # 创建回调函数 def draw_circle(event,x,y,flags,param): global ix,iy,ox,oy,drawing # 当按下左键是返回起始位置坐标 if event==cv2.EVENT_LBUTTONDOWN: drawing=True ix,iy = x,y # 当鼠标左键按下并移动是绘制图形。 event 可以查看移动, flag 查看是否按下 elif event==cv2.EVENT_MOUSEMOVE and flags==cv2.EVENT_FLAG_LBUTTON: if drawing==True: cv2.rectangle(image,(ix,iy),(x,y),(0,255,0),-1) ox,oy = x,y elif event==cv2.EVENT_LBUTTONUP: drawing==False number = 0 jpg = ".jpg" Image_Path = "./images" f_wrect = open('images.txt','a') for file in os.listdir(Image_Path): number = number + 1 #print(number) string_number = '%d'%number #print(string_number) i = len(string_number) #print(i) while (5 - i) > 0: string_number = '0' + string_number i = i + 1 newname = string_number + jpg old_NamePath = os.path.join(Image_Path,file) new_NamePath = os.path.join(Image_Path,newname) os.rename(old_NamePath,new_NamePath) image = cv2.imread(new_NamePath) cv2.namedWindow('image') cv2.setMouseCallback('image',draw_circle) while(1): cv2.imshow('image',image) k=cv2.waitKey(1)&0xFF if k==27: image_rect = newname + ' car '+ '%d'% ix +' '+ '%d'% iy+ ' ' + '%d'% ox + ' ' + '%d'% oy + ' ' f_wrect.write(image_rect) break cv2.destroyWindow('image')