1 Star 0 Fork 0

krokroal/counting

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
make_labels.py 2.60 KB
一键复制 编辑 原始数据 按行查看 历史
wzb1024 提交于 2022-04-29 15:43 . Initial commit
import cv2
import torch
import numpy as np
from utils.general import non_max_suppression, scale_coords, xyxy2xywh
from utils.augmentations import letterbox
from models.experimental import attempt_load
import os
weights = r'D:\yolov5-master\runs\train\exp17\weights\best.pt' #已训练好的模型路径
device = 'cuda' if torch.cuda.is_available() else 'cpu'
half = device != 'cpu'
imgsz = 640
conf_thres = 0.2
iou_thres = 0.2
model = attempt_load(weights, map_location=device) # load FP32 model
stride = int(model.stride.max()) #model stride
names = model.module.names if hasattr(model, 'module') else model.names #class name
if half:
model.half() # to FP16W
if device != 'cpu':
model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) #run once 初始化
def run():
entities=os.scandir("E:\Project\Script\pig\images")
for it in entities:
img0=cv2.imread(it.path)
img0 = cv2.cvtColor(img0, cv2.COLOR_BGRA2BGR)
img = letterbox(img0, imgsz, stride=stride)[0] #调整图片大小,填充
img = img.transpose((2, 0, 1))[::-1] #HWC to CHW, BGR to RBG
_,w,h=img.shape
img = np.ascontiguousarray(img)
img = torch.from_numpy(img).to(device)
img = img.half() if half else img.float()
img /= 255.0
if len(img.shape) == 3:
img = img[None] # expand for batch dim
pred = model(img, augment=False, visualize=False)[0]
pred = non_max_suppression(pred, conf_thres, iou_thres, agnostic=False)
aims = []
for i, det in enumerate(pred):
gn = torch.tensor(img0.shape)[[1, 0, 1, 0]] # normalization gain whwh
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img0.shape).round()
for *xyxy, conf, cls in reversed(det):
# bbox:(tag, x_center, y_center, x_width, y_width)
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
line = (cls, *xywh) # label format
aim = ('%g ' * len(line)).rstrip() % line
aim = aim.split(' ')
# aim=list(map(float,aim))
aims.append(aim)
f=open("E:\Project\Script\pig\labels\\"+it.name.split('.')[0]+'.txt','w')
for i in aims:
f.write(' '.join(i)+'\n')
f.close()
print(it.name)
run()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/krokroal/counting.git
[email protected]:krokroal/counting.git
krokroal
counting
counting
master

搜索帮助