diff --git a/.idea/MPKFNet.iml b/.idea/MPKFNet.iml index b557b9a..3b3bd7a 100755 --- a/.idea/MPKFNet.iml +++ b/.idea/MPKFNet.iml @@ -2,7 +2,7 @@ - + diff --git a/.idea/misc.xml b/.idea/misc.xml index acece97..528602c 100755 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100755 index 0000000..bdc0ec3 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,24 @@ +{ + // 使用 IntelliSense 了解相关属性。 + // 悬停以查看现有属性的描述。 + // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Python: Remote Attach", + "type": "python", + "request": "attach", + "connect": { + "host": "172.16.0.254", + "port": 22 + }, + "pathMappings": [ + { + "localRoot": "${workspaceFolder}", + "remoteRoot": "." + } + ], + "justMyCode": true + } + ] +} \ No newline at end of file diff --git a/20251105001/panorama.jpg b/20251105001/panorama.jpg new file mode 100644 index 0000000..9c5b5e6 Binary files /dev/null and b/20251105001/panorama.jpg differ diff --git a/20251105001/results/result_panorama.jpg b/20251105001/results/result_panorama.jpg new file mode 100644 index 0000000..f1208db Binary files /dev/null and b/20251105001/results/result_panorama.jpg differ diff --git a/Y5/utils/wandb_logging/__init__.py b/AIDetFineMul20240614.py similarity index 100% rename from Y5/utils/wandb_logging/__init__.py rename to AIDetFineMul20240614.py diff --git a/CalDatasetMeanVar.py b/CalDatasetMeanVar.py new file mode 100755 index 0000000..0296cb2 --- /dev/null +++ b/CalDatasetMeanVar.py @@ -0,0 +1,50 @@ +import os +from PIL import Image +import matplotlib.pyplot as plt +import numpy as np +#from scipy.misc import imread,imresize +import cv2,argparse +parser1 = argparse.ArgumentParser(description="CUI") +parser1.add_argument("root", default='/data1/Hatcher/model/project/data_MPKFNet/rawdata/竹林嘴-3月3日候鸟视频.mp4', type=str, + help='root.') +parser1.add_argument("imgsize", default='640', type=str, + help='imgsize') +args = parser1.parse_args() +filepath = args.root +imageSize = int(args.imgsize) +pathDir = os.listdir(filepath) + +R_channel = 0 +G_channel = 0 +B_channel = 0 +for idx in range(len(pathDir)): + filename = pathDir[idx] + print(filename) + img = cv2.imread(os.path.join(filepath, filename)) + img = cv2.resize(img,(imageSize,imageSize))/ 255.0 + R_channel = R_channel + np.sum(img[:, :, 0]) + G_channel = G_channel + np.sum(img[:, :, 1]) + B_channel = B_channel + np.sum(img[:, :, 2]) + +num = len(pathDir) * 512 * 512 # 这里(512,512)是每幅图片的大小,所有图片尺寸都一样 +R_mean = R_channel / num +G_mean = G_channel / num +B_mean = B_channel / num + +R_channel = 0 +G_channel = 0 +B_channel = 0 +for idx in range(len(pathDir)): + filename = pathDir[idx] + print(filename) + img = cv2.imread(os.path.join(filepath, filename)) + img = cv2.resize(img, (imageSize, imageSize)) / 255.0 + R_channel = R_channel + np.sum((img[:, :, 0] - R_mean) ** 2) + G_channel = G_channel + np.sum((img[:, :, 1] - G_mean) ** 2) + B_channel = B_channel + np.sum((img[:, :, 2] - B_mean) ** 2) + +R_var = np.sqrt(R_channel / num) +G_var = np.sqrt(G_channel / num) +B_var = np.sqrt(B_channel / num) +print("R_mean is %f, G_mean is %f, B_mean is %f" % (R_mean, G_mean, B_mean)) +print("R_var is %f, G_var is %f, B_var is %f" % (R_var, G_var, B_var)) \ No newline at end of file diff --git a/Dcl/util/__pycache__/__init__.cpython-36.pyc b/Dcl/util/__pycache__/__init__.cpython-36.pyc old mode 100644 new mode 100755 diff --git a/Dcl/util/__pycache__/test_tool.cpython-36.pyc b/Dcl/util/__pycache__/test_tool.cpython-36.pyc old mode 100644 new mode 100755 diff --git a/DclTest.py b/DclTest.py index e40efe8..810459d 100755 --- a/DclTest.py +++ b/DclTest.py @@ -44,7 +44,7 @@ from Dcl.models.LoadModel import MainModel from Dcl.DclConfig import LoadConfig, load_data_transformers from Dcl.util.test_tool import set_text, save_multi_img, cls_base_acc -os.environ['CUDA_VISIBLE_DEVICES'] = '6' +#os.environ['CUDA_VISIBLE_DEVICES'] = '6' devices = torch.device('cuda' if torch.cuda.is_available() else 'cpu') class DclInference: diff --git a/DetResizeForTrain.py b/DetResizeForTrain.py new file mode 100755 index 0000000..0696270 --- /dev/null +++ b/DetResizeForTrain.py @@ -0,0 +1,37 @@ +import os +import cv2 +import shutil +from tqdm import tqdm +anno_pathRoot = "/data/DataManagement/Project/CAS_ProjectBird/CDB_ProjectBird/Annotations_Original/" +image_pathRoot = anno_pathRoot.replace("/Annotations_Original/","/JPEGImages_Original/") +w = 1024 +h = 768 + +def DetResizeForTrain(anno_pathRoot,image_pathRoot,w,h): + annoResultPath = anno_pathRoot.replace("/Annotations_Original/","/Annotations/") + annoJPEGPath = anno_pathRoot.replace("/JPEGImages_Original/", "/JPEGImages/") + for anno in tqdm(os.listdir(anno_pathRoot)): + anno = GEN_Annotations(anno.replace(".xml", ".jpg")) + dom = xml.dom.minidom.parse(os.path.join(anno_pathRoot, xmls)) + size = dom.getElementsByTagName("size") + # print(size[0].getElementsByTagName('width')[0].childNodes[0].data) + width = size[0].getElementsByTagName('width')[0].childNodes[0].data + height = size[0].getElementsByTagName('height')[0].childNodes[0].data + depth = size[0].getElementsByTagName('depth')[0].childNodes[0].data + anno.set_size(int(w), int(h), int(depth)) + objects = dom.getElementsByTagName("object") + for object in objects: + bndbox = object.getElementsByTagName('bndbox')[0] + xmin = bndbox.getElementsByTagName('xmin')[0] + ymin = bndbox.getElementsByTagName('ymin')[0] + xmax = bndbox.getElementsByTagName('xmax')[0] + ymax = bndbox.getElementsByTagName('ymax')[0] + + xmin_data = int(xmin.childNodes[0].data)*(w/width) + ymin_data = int(ymin.childNodes[0].data)*(h/height) + xmax_data = int(xmax.childNodes[0].data)*(w/width) + ymax_data = int(ymax.childNodes[0].data)*(h/height) + label_name = object.getElementsByTagName('name')[0].childNodes[0].data + anno.add_pic_attr(label=label_name, xmin=xmin_data, xmax=xmax_data, ymin=ymin_data, ymax=ymax_data) + anno.savefile(os.path.join(annoResultPath, xmls)) + image = cv2.imread diff --git a/DetectFinePopulationSortVideo.py b/DetectFinePopulationSortVideo.py new file mode 100755 index 0000000..a697133 --- /dev/null +++ b/DetectFinePopulationSortVideo.py @@ -0,0 +1,273 @@ +# -*- coding:utf-8 -*- +import cv2,os,torch,argparse +import queue +import time +import threading +from System_I import Check_start_fordataselect,Density,Detection_Y5,Fine_grained,Fine_grained_T,shishi,save_sigle_image,RealDeal +from common import global_para as gp +r_db = None +import torch.multiprocessing as multiprocessing +import sort.sort as SORT +from imatovideo import images_to_video +from multiprocessing import Array + + + +class DetFineVid(): + def __init__(self, VideoPath,SavePath): + super(DetFineVid,self).__init__() + # name + self.VideoPath = VideoPath + self.VideoResultSavePathroot = "/data1/Hatcher/model/project/data_MPKFNet/result_vedio/" + self.VideoName = os.path.basename(self.VideoPath).split(".")[0] + self.VideoResultSavePath = os.path.join(self.VideoResultSavePathroot,"{}.avi".format(self.VideoName)) + self.SavePath = os.path.join(SavePath,self.VideoName) + if not os.path.exists(self.SavePath): + os.makedirs(self.SavePath) + + self.root = "/home/wanghc/output_jiankong" + self.DensityClass = Density(gp.devices, self.root) + self.DetectionClass = Detection_Y5(gp.devices, self.root) + self.Fine_grianedClass = Fine_grained_T(gp.devices) + self.FineRestartFlag = True + self.numrestart = 0 + + def conVideo(self): + images_to_video( self.SavePath,self.VideoResultSavePath) + def StartRec(self): + + + t1 = time.time() + cap = cv2.VideoCapture(self.VideoPath) + t2 = time.time() + print("capture is ",(t2-t1)*1000) + num_detection = 0 + num_cuntupian=0 + SortRestart = SORT.Sort(max_age=gp.max_age, + min_hits=gp.min_hits, + iou_threshold=gp.sortiou_threshold) + realtimedeal = RealDeal("check_start",self.DetectionClass,self.Fine_grianedClass,self.DensityClass) + if cap.isOpened(): + res, frame = cap.read() + if res: + shapex = frame.shape[1] + shapey = frame.shape[0] + gp.radioShowX = shapex / gp.radioShowX + gp.radioShowY = shapey / gp.radioShowY + gp.radioShowtext = gp.radioShowX + if frame.shape[1] == 3840: + gp.fontScale = 3 + elif frame.shape[1] == 2560: + gp.fontScale = 1 + else: + gp.fontScale = 1 + for i in range(20): + res, frame = cap.read() + print("skip{}".format(i)) + + num_image = 0 + while True: + if cap.isOpened(): + res, frame = cap.read() + if res: + closed = False + failCnt = 0 + num_image += 1 + data_today = 8 + print(num_detection) + # if num_detection <12974: + # a=0 + # num_detection+=1 + # continue + #cv2.imwrite("./test.jpg",frame) + if (int(data_today) > 1) & (int(data_today) < 20): + if (0xFF == ord('q')): + print("restart") + self.FineRestartFlag = True + self.numrestart = 0 + SortRestart = SORT.Sort(max_age=gp.max_age, + min_hits=gp.min_hits, + iou_threshold=gp.sortiou_threshold) + if self.FineRestartFlag : + realtimedeal.realtimerestart(frame,num_image=num_image,num_detection=num_detection,SortRestart = SortRestart) + self.numrestart += 1 + if self.numrestart >= 5: + self.numrestart = 0 + self.FineRestartFlag = False + FirstDetFineResult = realtimedeal.getrestartresult(gp.IndexMax) + print("µÚÒ»´Îʶ±ðÄ¿±êÊýÁ¿ ",len(FirstDetFineResult)) + gp.SortLabel_Index = FirstDetFineResult + # SortRealTime = SORT.Sort(max_age=gp.max_age, + # min_hits=gp.min_hits, + # iou_threshold=gp.sortiou_threshold) + + else: + tm1 = time.time() + #frame = cv2.imread("./test.jpg") + img_show,num_image = realtimedeal.realtime(frame,num_image=num_image,num_detection=num_detection,SortRestart = SortRestart) + tm2 = time.time() + if gp.DebugPrint_flag: + print("main1 time is ", (tm2 - tm1) * 1000) + # cv2.imshow("AI-ECO", img_show) + # #cv2.imwrite("../data_MPKFNet/RTSP3/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))),img_show) + # if cv2.waitKey(1) & 0xFF == ord('r'): + # break + save_path =os.path.join(self.SavePath,"{}.jpg".format(str(num_detection).zfill(6))) + cv2.imwrite(save_path,img_show) + tm3 = time.time() + if gp.DebugPrint_flag: + print("main2 time is ", (tm3 - tm2) * 1000) + else: + print("time is out") + if (num_detection >1000000) : + # save_image = save_sigle_image(frame) + # save_image.start() + # num_detection=0 + num_detection = 0 + num_detection+=1 + num_cuntupian+=1 + else: + break + + +def commanddeal(): + SavePath = "/data1/Hatcher/model/project/data_MPKFNet/result/" + print("starting ",gp.VideoPath) + DFS = DetFineVid(gp.VideoPath,SavePath) + DFS.StartRec() + DFS.conVideo() +def filedeal(rootPath): #deal all file in a folder + SavePath = "/data3/DEMO/images/" + i = 0 + for video_path in os.listdir(rootPath): + if i == 1: + print("111") + # print("starting deal {}".format(str(video_path))) + # VideoPath = os.path.join(rootPath,video_path) + # DFS = DetFineVid(VideoPath,SavePath) + # DFS.StartRec() + # DFS.conVideo() + P = multiprocessing.Process(target=func,args=(video_path,SavePath,rootPath)) + P.start() + P.join() + #globalInit() + i += 1 +def func(video_path,SavePath,rootPath): + print("starting deal {}".format(str(video_path))) + VideoPath = os.path.join(rootPath, video_path) + DFS = DetFineVid(VideoPath, SavePath) + DFS.StartRec() + DFS.conVideo() +def globalInit(): #deal all file in a folder + + parser1 = argparse.ArgumentParser(description="CUI") + parser1.add_argument("--video_num", default='/data1/Hatcher/model/project/data_MPKFNet/rawdata/PYH-DEMO.mp4', + type=str, + help='Video name.') + parser1.add_argument("--GPU", default='6', type=str, + help='GPU.') + parser1.add_argument("--thresh", default=0.4, type=float, + help='GPU.') + parser1.add_argument("--red", default=0, type=int, + help='red.') + parser1.add_argument("--add", default=0, type=str, + help='add.') + + args = parser1.parse_args() + # print(args) + gp.root = "/home/gyd/output1" + # os.environ['CUDA_VISIBLE_DEVICES'] = '0' + os.environ['CUDA_VISIBLE_DEVICES'] = args.GPU + gp.devices = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') + gp.camera_address = args.add + gp.VideoPath = args.video_num + gp.red_flag = args.red + gp.detect_thresh = args.thresh + + # fine_thresh2 = torch.tensor(fine_thresh2).cuda() + gp.birdIndex = 99999 + # birdIndex = torch.tensor(birdIndex).cuda() + gp.is_ex_bird = False # Ä¿±ê¼ì²â±ê־λ£¬Ã¿¸öÒ»Ãë¼ì²âÒ»´ÎÄ¿±ê¼ì²â£¬Èç¹ûÓÐÄñ£¬ÔòÖÃΪTrue£¬ÎªTrueµÄʱºò˵Ã÷£¬ ´¦Àí30sµÄÏ̻߳¹ÔÚ¼ÌÐø£¬Ö±µ½±ê־λ±äΪÁËFalseÔÙ¿ªÆôеÄÏß³Ì + gp.Density_thread_flag = False # ÃܶȹÀ¼ÆÏ̱߳ê־λ£¬ÎªTrue˵Ã÷¿ªÆôÁËÃܶȹÀ¼ÆỊ̈߳¬´¦ÀíÍê750֡Ϊֹ£¬±ê־λ±êΪFalse£¬ + gp.Detection_thread_flag = False # Ä¿±ê¼ì²âºÍϸÁ£¶Èʶ±ðÏ̱߳ê־λ£¬ÎªTrue˵Ã÷¿ªÆôÁËÃܶȹÀ¼ÆỊ̈߳¬´¦ÀíÍê750֡Ϊֹ£¬±ê־λ±êΪFalse£¬ + gp.Vedio_thread_flag = False # ´æ´¢ÊÓÆµÏ̱߳ê־룬´æ´¢30s + gp.SaveImage_thread_flag = False # ±£´æÔ­Í¼Ï̱߳ê־룬´æ´¢30ÕÅԭͼ + gp.ALL_thread_flag = False # ËùÓÐÏ̵߳ıê־룬µ¥¶À¿ªÉèÒ»¸öỊ̈߳¬¼à¿ØËùÓÐÏß³ÌÊÇ·ñ¶¼½áÊø£¬Èç¹û¶¼½áÊø£¬ÔòÖÃΪFalse£¬ºóÐøÌí¼ÓÏ̹߳ÜÀí£¬¿ÉÒÔ·ÅÔÚÕâÀïÃæ + + gp.ShowAllNumFlag = False + + gp.DebugPrint_flag = False # ´òÓ¡±ê־λ + + gp.num_count_old = 0 + gp.boxes_fine = None + gp.labels_fine = None + + gp.showThresh = 25 + gp.destory_image = False + gp.Camera_device = args.video_num # ÉãÏñÍ·±àºÅ£¬0001 + gp.image_time = None # µ±Ç°´¦ÀíµÄ30ÊÓÆµµÄ±àºÅ + gp.ImgDealQueue = [] # 750Ö¡ÊÓÆµ£¬»º´æ¿Õ¼ä + gp.img_show = None + + # event = threading.Event() + gp.eventDensity = threading.Event() + gp.eventDetection = threading.Event() + gp.eventSaveimage = threading.Event() + gp.max_age = 2 + gp.min_hits = 3 + gp.sortiou_threshold = 0.3 + gp.Finerestartboxes = [] + gp.IndexMax = 0 + gp.radioShowX = 2560.0 + gp.radioShowY = 1440.0 + gp.radioShowtext = gp.radioShowX + gp.SortLabel_Index = None # ±êÇ©ºÍË÷Òý¶ÔÓ¦¹ØÏµ[[4,1],[3,2]] + gp.SortLabel_Indexpre = [] # ±êÇ©ºÍË÷ÒýµÄ¶ÔÓ¦¹ØÏµ£¬ÓÃÔÚ×·×Ù¹ý³ÌÖÐгöÏÖµÄÄ¿±ê£¬[[label,Index,Count]] + # Detection2 = Detection(devices,root) + gp.FineCountThresh = 5 + + gp.img_show = None + + gp.Fine_thresh = 0.4 + + # DetWeight = "/data1/Hatcher/model/Detection/yolov5/runs/train/exp21/weights/best.pt" + # FineWeight = "/data/Hatcher/data/weigth/areaproject/resnet50-PYH-3-20.7/_42522_PYH-3/best.pth" + gp.DetWeight = "/data1/Hatcher/model/Detection/yolov5/runs/train/KunMingCuiHu-Fish2/weights/best.pt" + gp.FineWeight = "/data/Hatcher/data/weigth/areaproject/resnet50-DianChiFish-3-3-0.7/_4289_DianChiFish-4/best.pth" + # DetWeight = "/data1/Hatcher/model/Detection/yolov5/runs/train/BeijingCuiHu-Bird26/weights/best.pt" + # FineWeight = "/data/Hatcher/data/weigth/areaproject/resnet50-cui90_1model0.7/_42111_CUI-94-1/best.pth" + # BHG_chineseName = ["kong", '白鹤', '白头鹤','白枕鹤']#["kong","鲫鱼","麦穗鱼","鳑鲏"] + gp.BHG_chineseName = ["kong", "鲫鱼", "麦穗鱼", "鳑鲏"] + + # BHG_chineseName = ['Kong', '白额雁', '白骨顶', '苍鹭', '苍鹭', '白秋沙鸭', '白腰草鹬', '斑头雁', '斑嘴鸭', '苍鹭', '赤膀鸭', '赤颈鸭', '苍鹭', '大麻鳽', + # '豆雁', '反嘴鹬', '凤头鸊鷉', '凤头麦鸡', '凤头潜鸭', '黑鹳', '黑水鸡', '红嘴鸥', '鸿雁', '灰鹤', '灰雁', '绿翅鸭', '绿头鸭', '琵嘴鸭', + # '普通鸬鹚', '普通秋沙鸭', '翘鼻麻鸭', '鹊鸭', '扇尾沙锥', '小白额雁', '小天鹅', '针尾鸭', '苍鹭', '暗绿绣眼鸟', '八哥', '白腹鹞', '白鹡鸰', + # '白眼潜鸭', '草鹭', '池鹭', '戴胜', '黑翅长脚鹬', '黑鸢', '红隼', '花脸鸭', '环颈雉', '灰头绿啄木鸟', '灰头麦鸡', '矶鹬', '栗苇鳽', + # '罗纹鸭', '牛背鹭', '普通翠鸟', '雀鹰', '喜鹊', '苍鹭', '鸳鸯', '棕背伯劳', '红胸秋沙鸭', '普通燕鸥', '小白额燕鸥', '丘鹬', '凤头蜂鹰', + # '大天鹅', '大鸨', '小田鸡', '山斑鸠', '帆背潜鸭', '日本松雀鹰', '普通鵟', '松雀鹰', '毛脚鵟', '灰斑鸠', '白头鹞', '白尾鹞', '白眉鸭', + # '白鹈鹕', '红头潜鸭', '苍鹰', '蒙古银鸥', '西方秧鸡', '赤嘴潜鸭', '阔嘴鹬', '雕鸮', '鹌鹑', '鹗', '黄苇鳽', '黑颈鹤', '小䴙䴘', '赤麻鸭'] + # BHG_chineseName =["kong","绿头鸭","斑嘴鸭","灰雁","鸿雁","kong","小鷿鷈"] + + gp.FineClassNum = 4 + gp.color_show = (255, 255, 255) + gp.color_box = (255, 0, 0) + gp.NoneLabel = "鱼" # "鹤类" + gp.fine_thresh1 = 6000 + gp.fine_thresh2 = 10000 + gp.fontScale = 1 + + + + torch.zero_(gp.Species) + + + +if __name__ == '__main__': + multiprocessing.set_start_method("spawn") + rootPath = "/data3/DEMO/video/PYH/" + filedeal(rootPath) + #commanddeal() + + + + diff --git a/DetectImageNetFineSplit.py b/DetectImageNetFineSplit.py new file mode 100755 index 0000000..81432d5 --- /dev/null +++ b/DetectImageNetFineSplit.py @@ -0,0 +1,176 @@ +# -- coding: utf-8 -- +# @Author : Calvin +# @Email : 934055521@qq.com +# @File : xld.py +# @use : +# @Software: PyCharm +# @Time : 27/5/2022 3:32 PM +""" +python3 FinegrainedIdentificationDatasetGenerate.py +-rp /data/DataManagement/Project/004_kunmingcuihu/0003_20220507_800/CAS_KMCuihuBird/CMB_KMCuihuBird +-blp /data/DataManagement/Project/004_kunmingcuihu/0003_20220507_800/CAS_KMCuihuBird/CMB_KMCuihuBird/birdList/KMCuihuBird.xlsx +""" +import os +import shutil +import argparse +import random +import pandas as pd +import numpy as np +import cv2 +from tqdm import tqdm +BHG_chineseName = ['bird', 'Anser_albifrons', 'Fulica_atra', 'Egretta_garzetta', 'Platalea_leucorodia', 'Mergellus_albellus', 'Tringa_ochropus', 'Anser_indicus', 'Anas_zonorhyncha', 'Ardea_cinerea', 'Mareca_strepera', 'Mareca_penelope', 'Ardea_alba', 'Botaurus_stellaris', 'Anser_fabalis', 'Recurvirostra_avosetta', 'Podiceps_cristatus', 'Vanellus_vanellus', 'Aythya_fuligula', 'Ciconia_nigra', 'Gallinula_chloropus', 'Chroicocephalus_ridibundus', 'Anser_cygnoides', 'Grus_grus', 'Anser_anser', 'Anas_crecca', 'Anas_platyrhynchos', 'Spatula_clypeata', 'Phalacrocorax_carbo', 'Mergus_merganser', 'Tadorna_tadorna', 'Bucephala_clangula', 'Gallinago_gallinago', 'Anser_erythropus', 'Cygnus_columbianus', 'Anas_acuta', 'Ardea_intermedia', 'Zosterops_simplex', 'Acridotheres_cristatellus', 'Circus_spilonotus', 'Motacilla_alba', 'Aythya_nyroca', 'Ardea_purpurea', 'Ardeola_bacchus', 'Upupa_epops', 'Himantopus_himantopus', 'Milvus_migrans', 'Falco_tinnunculus', 'Sibirionetta_formosa', 'Phasianus_colchicus', 'Picus_canus', 'Vanellus_cinereus', 'Actitis_hypoleucos', 'Ixobrychus_cinnamomeus', 'Mareca_falcata', 'Bubulcus_coromandus', 'Alcedo_atthis', 'Accipiter_nisus', 'Pica_serica', 'Nycticorax_nycticorax', 'Aix_galericulata', 'Lanius_schach', 'Mergus_serrator', 'Sterna_hirundo', 'Sternula_antillarum', 'Scolopax_rusticola', 'Pernis_ptilorhynchus', 'Cygnus_cygnus', 'Otis_tarda', 'Zapornia_pusilla', 'Streptopelia_orientalis', 'Aythya_valisineria', 'Accipiter_gularis', 'Buteo_japonicus', 'Accipiter_virgatus', 'Buteo_lagopus', 'Streptopelia_decaocto', 'Circus_aeruginosus', 'Circus_cyaneus', 'Spatula_querquedula', 'Pelecanus_onocrotalus', 'Aythya_ferina', 'Accipiter_gentilis', 'Larus_cachinnans', 'Rallus_aquaticus', 'Netta_rufina', 'Calidris_falcinellus', 'Bubo_bubo', 'Coturnix_japonica', 'Pandion_haliaetus', 'Ixobrychus_sinensis', 'Grus_nigricollis', 'Tachybaptus_ruficollis', 'Tadorna_ferruginea', 'Leucogeranus_leucogeranus', 'Grus_monacha', 'Antigone_vipio', 'Cyanopica_cyanus', 'Passer_montanus', 'Hirundo_rustica'] + + +##################################### +Number_last = 0 +LabelSpecies = [] +DataNOlineFeed = [] +WrongImages = [] +DataSpeciesClassier = dict() +##################################### + + +def parse(): + arg = argparse.ArgumentParser() + arg.add_argument('--root_path', '-rp', default='/data/DataManagement/Project/CAS_ProjectBird/CMB_ProjectBird0615/', type=str) + arg.add_argument('--division_ratio', '-dr', default='0.7', type=float) + arg.add_argument('--bird_list_path', '-blp', default='/data/DataManagement/Project/CAS_ProjectBird/CMB_ProjectBird0615/birdList/ProjectBirdList.xlsx') + args = arg.parse_args() + return args + + +if __name__ == '__main__': + args = parse() + dataset_txt_path = os.path.join(args.root_path, 'DatasetTxt') + species_txt_path = f'{args.root_path}/DatasetTxt/Species.txt' + dataset_spectrum_path = f'{args.root_path}/OrginalData' + dataset_allspectrum_path = f'{args.root_path}/FinalData/data' + dataset_allspectrum_path_train = f'{args.root_path}/FinalData/train' + dataset_allspectrum_path_test = f'{args.root_path}/FinalData/test' + dataset_allspectrum_txt_path = f'{args.root_path}/FinalData/anno/all.txt' + if not os.path.exists(dataset_txt_path): + os.makedirs(dataset_txt_path) + # for data in tqdm(os.listdir(dataset_spectrum_path), ncols=80, ascii=True, desc="OrginalData images path"): + # # for data in os.listdir(dataset_spectrum_path): + # for image in os.listdir(os.path.join(dataset_spectrum_path, data)): + # try: + # im = cv2.imread(os.path.join(dataset_spectrum_path, data, image)) + # except: + # WrongImages.append(os.path.join(dataset_spectrum_path, data, image)) + # os.remove(os.path.join(dataset_spectrum_path, data, image)) + # tqdm.write('Wrong images are {:}'.format(WrongImages)) + bird_list = pd.read_excel(args.bird_list_path, usecols=['拉丁名']) + bird_list = np.array(bird_list.stack()).tolist() + for num, data in tqdm(enumerate(bird_list), ncols=80, ascii=True, desc="writing species.txt"): + # for num, data in enumerate(bird_list): + with open(species_txt_path, 'a') as f: + filename = data + file_final_name = data + ' ' + str(num) + f.write(file_final_name) + f.write('\n') + for speices in tqdm(os.listdir(dataset_spectrum_path), ncols=80, ascii=True, desc="writing species.txt"): + # for speices in os.listdir(dataset_spectrum_path): + for data in os.listdir(os.path.join(dataset_spectrum_path, speices)): + if data.split('___')[0] != speices: + os.rename(os.path.join(dataset_spectrum_path, speices, data), os.path.join(dataset_spectrum_path, speices, '{:}___{:}'.format(speices, data))) + tqdm.write('The pictures naming is done!') + + with open(species_txt_path, 'r') as file: + Data = file.readlines() + for line in Data: + line = line.strip('\n') + species = line.split(' ')[0] + Number = line.split(' ')[1] + #Judge Number + if Number != Number_last: + DataSpeciesClassier[species] = Number + Number_last = Number + + tqdm.write(str(DataSpeciesClassier)) + tqdm.write('The species have been obtained') + + # transfer single files to all files + if not os.path.exists(dataset_allspectrum_path): + os.makedirs(dataset_allspectrum_path) + if not os.path.exists(dataset_allspectrum_path_train): + os.makedirs(dataset_allspectrum_path_train) + if not os.path.exists(dataset_allspectrum_path_test): + os.makedirs(dataset_allspectrum_path_test) + for data in tqdm(os.listdir(dataset_spectrum_path), ncols=80, ascii=True, desc="transfer single files"): + # for data in os.listdir(dataset_spectrum_path): + for file in os.listdir(os.path.join(dataset_spectrum_path, data)): + shutil.copy(os.path.join(dataset_spectrum_path, data, file), dataset_allspectrum_path) + tqdm.write('Transfer single files to all files is done') + + # generate the all.txt + if not os.path.exists('/'.join(dataset_allspectrum_txt_path.split('/')[:-1])): + os.makedirs('/'.join(dataset_allspectrum_txt_path.split('/')[:-1])) + for data in tqdm(os.listdir(dataset_allspectrum_path), ncols=80, ascii=True, desc="transfer single files"): + # for data in os.listdir(dataset_allspectrum_path): + with open(dataset_allspectrum_txt_path, 'a') as f: + file_new_name = data.split('___')[0] + # file_new_name = data + # file_new_name = '_'.join(file_new_name.split('_')[:-1]) + num = DataSpeciesClassier[file_new_name] + file_final_name = data + ' ' + num + f.write(file_final_name) + f.write('\n') + tqdm.write('Generate the all.txt is done') + + # Spilit dataset + DataPath = dataset_allspectrum_txt_path + # delete file_txt + if os.path.exists(DataPath.replace(os.path.basename(DataPath), 'train.txt')) : + os.remove(DataPath.replace(os.path.basename(DataPath), 'train.txt')) + if os.path.exists(DataPath.replace(os.path.basename(DataPath), 'test.txt')): + os.remove(DataPath.replace(os.path.basename(DataPath), 'test.txt')) + + with open(DataPath, 'r')as f: + Data = f.readlines() + LabelSpecies = [] + for RowData in Data: + RowData = RowData.strip() + # find picture-label + RowLabels = RowData.split(' ')[1] + DataNOlineFeed.append(RowData.split(' ')) + if RowLabels not in LabelSpecies: + LabelSpecies.append(RowLabels) + print(LabelSpecies) + tqdm.write("classes num of Dataset is : {:}".format(len(LabelSpecies))) + for Labels in tqdm(LabelSpecies, ncols=80, ascii=True, desc="transfer single files"): + # for Labels in LabelSpecies: + Num = 0 + TrainData = [] + TestData = [] + TotalData = [] + for SpeciesData in DataNOlineFeed: + if Labels == SpeciesData[1]: + Num += 1 + TotalData.append(SpeciesData) + + TrainNum = int(Num * args.division_ratio) + TestNum = Num - TrainNum + random.shuffle(TotalData) + with open(DataPath.replace(os.path.basename(DataPath), 'train.txt'), 'a') as f: + for i in range(TrainNum): + f.write(' '.join(TotalData[i]) + '\n') + label_classname = "{}.{}".format(str(Labels).zfill(4),BHG_chineseName[int(Labels)]) + soursepathTrain = os.path.join(dataset_spectrum_path,label_classname) + destpathTrain = os.path.join(dataset_allspectrum_path_train,label_classname) + if not os.path.exists(destpathTrain): + os.makedirs(destpathTrain) + image_name = TotalData[i][0] + shutil.copy(os.path.join(soursepathTrain,str(image_name)),os.path.join(destpathTrain,str(image_name))) + + with open(DataPath.replace(os.path.basename(DataPath), 'test.txt'), 'a') as f: + for i in range(TrainNum, Num): + f.write(' '.join(TotalData[i]) + '\n') + label_classname = "{}.{}".format(str(Labels).zfill(4), BHG_chineseName[int(Labels)]) + soursepathTest = os.path.join(dataset_spectrum_path, label_classname) + destpathTest = os.path.join(dataset_allspectrum_path_test, label_classname) + if not os.path.exists(destpathTest): + os.makedirs(destpathTest) + image_name = TotalData[i][0] + shutil.copy(os.path.join(soursepathTest, str(image_name)), os.path.join(destpathTest, str(image_name))) + + diff --git a/DetectionAILAbel.py b/DetectionAILAbel.py old mode 100644 new mode 100755 index 5db1bb2..1de07dc --- a/DetectionAILAbel.py +++ b/DetectionAILAbel.py @@ -1,30 +1,40 @@ import os,argparse,torch -from System_I import Detection_Y5 +from System_I import Detection_Y5,Fine_grained_T from tqdm import tqdm - +#os.environ['CUDA_VISIBLE_DEVICES'] = "1" if __name__ == '__main__': parser1 = argparse.ArgumentParser(description="AILabel") - parser1.add_argument("--RawPath", default='/data/DataManagement/Project/001_cuihu/0012_20220517_RTSP/imagesAILabel', type=str, + parser1.add_argument("--RawPath", default='/data/DataManagement/Project/006_huanghekou/0006_20220621/Raw_images/imagesAILabel', type=str, help='RawPath.') - parser1.add_argument("--GPU", default="1", type=str, + parser1.add_argument("--GPU", default="4", type=str, help='GPU.') parser1.add_argument("--thresh", default=0.4, type=float, help='thresh.') - parser1.add_argument("--Weight", default="/data/Hatcher/data/Detection_weigth/BJCHKMCH-Bird-1-4/weights/best.pt", type=str, - help='Weight.') args = parser1.parse_args() - os.environ['CUDA_VISIBLE_DEVICES'] = args.GPU - devices = torch.device('cuda:{}'.format(str(int(args.GPU))) if torch.cuda.is_available() else 'cpu') + os.environ['CUDA_VISIBLE_DEVICES'] = args.GPU#"1" + try: + if "imagesAILabel" not in args.RawPath: + exit() + else: + os.system("sudo chmod 777 -R {}".format(str(args.RawPath).replace("imagesAILabel",""))) + except: + exit() + #devices = torch.device('cuda:{}'.format(str(int(args.GPU))) if torch.cuda.is_available() else 'cpu') + devices = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') if not os.path.exists(args.RawPath.replace("imagesAILabel","NoResult")): os.makedirs(args.RawPath.replace("imagesAILabel","NoResult")) - if not os.path.exists(args.RawPath.replace("imagesAILabel","YesResult")): - os.makedirs(args.RawPath.replace("imagesAILabel","YesResult")) - if not os.path.exists(args.RawPath.replace("imagesAILabel","LabelXML")): - os.makedirs(args.RawPath.replace("imagesAILabel","LabelXML")) - Detection = Detection_Y5(device=devices,root=" ", detect_thresh=args.thresh,DetWeight=args.Weight) + if not os.path.exists(args.RawPath.replace("imagesAILabel","JPEGImages")): + os.makedirs(args.RawPath.replace("imagesAILabel","JPEGImages")) + if not os.path.exists(args.RawPath.replace("imagesAILabel","Annotations")): + os.makedirs(args.RawPath.replace("imagesAILabel","Annotations")) + if not os.path.exists(args.RawPath.replace("imagesAILabel", "BrokenImage")): + os.makedirs(args.RawPath.replace("imagesAILabel", "BrokenImage")) + + Detection = Detection_Y5(device=devices,root=" ", detect_thresh=args.thresh) + FineGrained = Fine_grained_T(device=devices) imagepaths = os.listdir(args.RawPath) for imagepath in tqdm(imagepaths): imagepath = os.path.join(args.RawPath,imagepath) - Detection.AIlabel(imagepath) \ No newline at end of file + Detection.AIlabelFine(imagepath,FineGrained) \ No newline at end of file diff --git a/DetectionFineAILAbel.py b/DetectionFineAILAbel.py new file mode 100755 index 0000000..de9d0d5 --- /dev/null +++ b/DetectionFineAILAbel.py @@ -0,0 +1,44 @@ +import os,argparse,torch +from System_I import Detection_Y5,Fine_grained_T +from tqdm import tqdm + +#os.environ['CUDA_VISIBLE_DEVICES'] = "1" + +if __name__ == '__main__': + parser1 = argparse.ArgumentParser(description="AILabel") + parser1.add_argument("--RawPath", default='/data/DataManagement/Project/temp/OrginalData', type=str, + help='RawPath.') + parser1.add_argument("--GPU", default="2", type=str, + help='GPU.') + parser1.add_argument("--thresh", default=0.4, type=float, + help='thresh.') + args = parser1.parse_args() + os.environ['CUDA_VISIBLE_DEVICES'] = args.GPU#"1" + try: + if "imagesAILabel" not in args.RawPath: + exit() + else: + os.system("sudo chmod 777 -R {}".format(str(args.RawPath).replace("imagesAILabel",""))) + except: + exit() + + #devices = torch.device('cuda:{}'.format(str(int(args.GPU))) if torch.cuda.is_available() else 'cpu') + devices = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') + Detection = Detection_Y5(device=devices, root=" ", detect_thresh=args.thresh) + FineGrained = Fine_grained_T(device=devices) + for RawPaths in os.listdir(args.RawPath): + RawPath = os.path.join(args.RawPath,RawPaths,"imagesAILabel") + if not os.path.exists(RawPath.replace("imagesAILabel","NoResult")): + os.makedirs(RawPath.replace("imagesAILabel","NoResult")) + if not os.path.exists(RawPath.replace("imagesAILabel","JPEGImages")): + os.makedirs(RawPath.replace("imagesAILabel","JPEGImages")) + if not os.path.exists(RawPath.replace("imagesAILabel","Annotations")): + os.makedirs(RawPath.replace("imagesAILabel","Annotations")) + if not os.path.exists(RawPath.replace("imagesAILabel", "BrokenImage")): + os.makedirs(RawPath.replace("imagesAILabel", "BrokenImage")) + + + imagepaths = os.listdir(RawPath) + for imagepath in tqdm(imagepaths): + imagepath = os.path.join(args.RawPath,imagepath) + Detection.AIlabelFine(imagepath,FineGrained) \ No newline at end of file diff --git a/DetectionFineAILAbel_mmcls.py b/DetectionFineAILAbel_mmcls.py new file mode 100755 index 0000000..81559c3 --- /dev/null +++ b/DetectionFineAILAbel_mmcls.py @@ -0,0 +1,66 @@ +import os,argparse,torch +from System_I import Detection_Y5,Fine_grained_T,Fine_grained_mmclsonnx +from tqdm import tqdm + +#os.environ['CUDA_VISIBLE_DEVICES'] = "1" +"""### +输入:/根目录/imagesAI + -------文件夹1 + ------NoResult 存放无结果图片 + ------BrokenImage 存放损坏图片 + ------imagesAILabel 存放待处理图片 + ------Annotations 存放识别结果xml标签文件 + ------JPEGImages 备份原图原图 + ------result 存放可视化结果图片 + -------文件夹2 + ------NoResult 存放无结果图片 + ------BrokenImage 存放损坏图片 + ------imagesAILabel 存放待处理图片 + ------Annotations 存放识别结果xml标签文件 + ------JPEGImages 备份原图原图 + ------result 存放可视化结果图片 + +###""" + + + +if __name__ == '__main__': + parser1 = argparse.ArgumentParser(description="AILabel") + parser1.add_argument("--RawPath", default='/data5/student/Hatcher/test/imagesAI', type=str, + help='RawPath.') + parser1.add_argument("--GPU", default="2", type=str, + help='GPU.') #本参数在该工程中不起作用,请修改common.py文件种的全局参数 + parser1.add_argument("--thresh", default=0.4, type=float, + help='thresh.') + args = parser1.parse_args() + os.environ['CUDA_VISIBLE_DEVICES'] = args.GPU#"1" + try: + if "imagesAI" not in args.RawPath: + exit() + else: + os.system("sudo chmod 777 -R {}".format(str(args.RawPath).replace("imagesAI",""))) + except: + exit() + + #devices = torch.device('cuda:{}'.format(str(int(args.GPU))) if torch.cuda.is_available() else 'cpu') + devices = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') + Detection = Detection_Y5(device=devices, root=" ", detect_thresh=args.thresh) + FineGrained = Fine_grained_mmclsonnx(device=devices) + for RawPaths in os.listdir(args.RawPath): + RawPath = os.path.join(args.RawPath,RawPaths,"imagesAILabel") + if not os.path.exists(RawPath.replace("imagesAILabel","NoResult")): + os.makedirs(RawPath.replace("imagesAILabel","NoResult")) + if not os.path.exists(RawPath.replace("imagesAILabel","JPEGImages")): + os.makedirs(RawPath.replace("imagesAILabel","JPEGImages")) + if not os.path.exists(RawPath.replace("imagesAILabel","Annotations")): + os.makedirs(RawPath.replace("imagesAILabel","Annotations")) + if not os.path.exists(RawPath.replace("imagesAILabel", "BrokenImage")): + os.makedirs(RawPath.replace("imagesAILabel", "BrokenImage")) + if not os.path.exists(RawPath.replace("imagesAILabel", "result")): + os.makedirs(RawPath.replace("imagesAILabel", "result")) + + + imagepaths = os.listdir(RawPath) + for imagepath in tqdm(imagepaths): + imagepath = os.path.join(RawPath,imagepath) + Detection.AIlabelFine(imagepath,FineGrained) \ No newline at end of file diff --git a/DetectionFineAILAbel_zwq.py b/DetectionFineAILAbel_zwq.py new file mode 100755 index 0000000..29304d8 --- /dev/null +++ b/DetectionFineAILAbel_zwq.py @@ -0,0 +1,61 @@ +import os +import argparse +import torch +from System_zwq import Detection_Y5, Fine_grained_T +from tqdm import tqdm + +#os.environ['CUDA_VISIBLE_DEVICES'] = "1" + +def oneFolder(): + RawPath = os.path.join(args.RawPath, "imagesAILabel") + os.system("sudo chmod 777 -R {}".format(str(args.RawPath))) + if not os.path.exists(RawPath.replace("imagesAILabel", "NoResult")): + os.makedirs(RawPath.replace("imagesAILabel", "NoResult")) + if not os.path.exists(RawPath.replace("imagesAILabel", "JPEGImages")): + os.makedirs(RawPath.replace("imagesAILabel", "JPEGImages")) + if not os.path.exists(RawPath.replace("imagesAILabel", "Annotations")): + os.makedirs(RawPath.replace("imagesAILabel", "Annotations")) + if not os.path.exists(RawPath.replace("imagesAILabel", "BrokenImage")): + os.makedirs(RawPath.replace("imagesAILabel", "BrokenImage")) + + imagepaths = os.listdir(RawPath) + for imagepath in tqdm(imagepaths, ncols=120, ascii=True, desc=RawPath + " images"): + imagepath = os.path.join(RawPath, imagepath) + Detection.AIlabelFine(imagepath, FineGrained) + + +def manyFolder(): + for RawPaths in tqdm(os.listdir(args.RawPath), ncols=120, ascii=True, desc="bird folders"): + # for RawPaths in os.listdir(args.RawPath): + RawPath = os.path.join(args.RawPath, RawPaths, "imagesAILabel") + # os.system("sudo chmod 777 -R {}".format(str(os.path.join(args.RawPath, RawPaths)))) + if not os.path.exists(RawPath.replace("imagesAILabel", "NoResult")): + os.makedirs(RawPath.replace("imagesAILabel", "NoResult")) + if not os.path.exists(RawPath.replace("imagesAILabel", "JPEGImages")): + os.makedirs(RawPath.replace("imagesAILabel", "JPEGImages")) + if not os.path.exists(RawPath.replace("imagesAILabel", "Annotations")): + os.makedirs(RawPath.replace("imagesAILabel", "Annotations")) + if not os.path.exists(RawPath.replace("imagesAILabel", "BrokenImage")): + os.makedirs(RawPath.replace("imagesAILabel", "BrokenImage")) + + imagepaths = os.listdir(RawPath) + for imagepath in tqdm(imagepaths, ncols=120, ascii=True, desc=RawPaths + " images"): + # for imagepath in tqdm(imagepaths): + imagepath = os.path.join(RawPath, imagepath) + Detection.AIlabelFine(imagepath, FineGrained) + + +if __name__ == '__main__': + parser1 = argparse.ArgumentParser(description="AILabel") + parser1.add_argument("RawPath", default='/data5/PartDataset/003 PYH/0014 20230411/', type=str, help='RawPath.') + parser1.add_argument("--GPU", default="7", type=str, help='GPU.') + parser1.add_argument("--thresh", default=0.4, type=float, help='thresh.') + args = parser1.parse_args() + # os.environ['CUDA_VISIBLE_DEVICES'] = "7" #args.GPU # "1" + + devices = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') + Detection = Detection_Y5(device=devices, root=" ", detect_thresh=args.thresh) + FineGrained = Fine_grained_T(device=devices) + oneFolder() + # manyFolder() + \ No newline at end of file diff --git a/DetectionVideo_Video.py b/DetectionVideo_Video.py index ac99425..b44a472 100755 --- a/DetectionVideo_Video.py +++ b/DetectionVideo_Video.py @@ -27,7 +27,7 @@ from vediotoima import vedio_img from imatovideo import images_to_video,images_to_video_big from moviepy.editor import * import os -os.environ['CUDA_VISIBLE_DEVICES'] = '3' +#os.environ['CUDA_VISIBLE_DEVICES'] = '3' def parse_args(): diff --git a/FineNewNameWithindex.py b/FineNewNameWithindex.py new file mode 100755 index 0000000..13baa9f --- /dev/null +++ b/FineNewNameWithindex.py @@ -0,0 +1,13 @@ +""" +FInename---->0001.Finename + +""" +import os +from tqdm import tqdm +BHG_chineseName = ['bird', 'Anser_albifrons', 'Fulica_atra', 'Egretta_garzetta', 'Platalea_leucorodia', 'Mergellus_albellus', 'Tringa_ochropus', 'Anser_indicus', 'Anas_zonorhyncha', 'Ardea_cinerea', 'Mareca_strepera', 'Mareca_penelope', 'Ardea_alba', 'Botaurus_stellaris', 'Anser_fabalis', 'Recurvirostra_avosetta', 'Podiceps_cristatus', 'Vanellus_vanellus', 'Aythya_fuligula', 'Ciconia_nigra', 'Gallinula_chloropus', 'Chroicocephalus_ridibundus', 'Anser_cygnoides', 'Grus_grus', 'Anser_anser', 'Anas_crecca', 'Anas_platyrhynchos', 'Spatula_clypeata', 'Phalacrocorax_carbo', 'Mergus_merganser', 'Tadorna_tadorna', 'Bucephala_clangula', 'Gallinago_gallinago', 'Anser_erythropus', 'Cygnus_columbianus', 'Anas_acuta', 'Ardea_intermedia', 'Zosterops_simplex', 'Acridotheres_cristatellus', 'Circus_spilonotus', 'Motacilla_alba', 'Aythya_nyroca', 'Ardea_purpurea', 'Ardeola_bacchus', 'Upupa_epops', 'Himantopus_himantopus', 'Milvus_migrans', 'Falco_tinnunculus', 'Sibirionetta_formosa', 'Phasianus_colchicus', 'Picus_canus', 'Vanellus_cinereus', 'Actitis_hypoleucos', 'Ixobrychus_cinnamomeus', 'Mareca_falcata', 'Bubulcus_coromandus', 'Alcedo_atthis', 'Accipiter_nisus', 'Pica_serica', 'Nycticorax_nycticorax', 'Aix_galericulata', 'Lanius_schach', 'Mergus_serrator', 'Sterna_hirundo', 'Sternula_antillarum', 'Scolopax_rusticola', 'Pernis_ptilorhynchus', 'Cygnus_cygnus', 'Otis_tarda', 'Zapornia_pusilla', 'Streptopelia_orientalis', 'Aythya_valisineria', 'Accipiter_gularis', 'Buteo_japonicus', 'Accipiter_virgatus', 'Buteo_lagopus', 'Streptopelia_decaocto', 'Circus_aeruginosus', 'Circus_cyaneus', 'Spatula_querquedula', 'Pelecanus_onocrotalus', 'Aythya_ferina', 'Accipiter_gentilis', 'Larus_cachinnans', 'Rallus_aquaticus', 'Netta_rufina', 'Calidris_falcinellus', 'Bubo_bubo', 'Coturnix_japonica', 'Pandion_haliaetus', 'Ixobrychus_sinensis', 'Grus_nigricollis', 'Tachybaptus_ruficollis', 'Tadorna_ferruginea', 'Leucogeranus_leucogeranus', 'Grus_monacha', 'Antigone_vipio', 'Cyanopica_cyanus', 'Passer_montanus', 'Hirundo_rustica'] +rootPath = "/data/DataManagement/Project/CAS_ProjectBird/CMB_ProjectBird0615/OrginalData" +os.system("sudo chmod 777 -R {}".format(rootPath)) +for path in tqdm(os.listdir(rootPath),ncols=80, ascii=True, desc="change name"): + source = os.path.join(rootPath,path) + dest = os.path.join(rootPath,"{}.{}".format(str(BHG_chineseName.index(path)).zfill(4),str(path))) + os.rename(source,dest) \ No newline at end of file diff --git a/GYD_RedCamera.py b/GYD_RedCamera.py index d91a91c..a21ba3b 100755 --- a/GYD_RedCamera.py +++ b/GYD_RedCamera.py @@ -36,7 +36,7 @@ def GYD_RedCameraDeal (root,DetectionCalss,Fine_grainedClass): if __name__ == '__main__': - os.environ['CUDA_VISIBLE_DEVICES'] = '4' + #os.environ['CUDA_VISIBLE_DEVICES'] = '4' devices = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') root = "/data1/Hatcher/ftp" Detection1 = Detection_S(devices, root) diff --git a/NewDetAiLabelFine.py b/NewDetAiLabelFine.py new file mode 100755 index 0000000..4793a29 --- /dev/null +++ b/NewDetAiLabelFine.py @@ -0,0 +1,1763 @@ +""" +测试代码: +1.-dw 输入目标检测权重,为pt文件,必要选项 +2.-cw 输入细粒度识别权重,为onnx文件,必要选项 +3.-c 输入细粒度识别名录,为txt文件,中文名字,每个中文用引号表示,中间用“,”隔开 +4.-m 系统执行模式,分两种,一种为推理图片,直接生成结果“inf”,一种为AI label,生成xml文件,“ai” +5.-s 源文件路径,可以是文件夹也可以是图片文件,如果是AI label,则在同级目录下面生成一个xml文件。,可以一直输入单张图片地址进行推理“always”,则源文件路径参数失效,需要输入1即可,也可以是超大分辨率的处理,返回的参数是7,要求文件夹目录必须有long字眼 +6.-o 存储根路径 + CUDA_VISIBLE_DEVICES=7 ./NewDetAiLabelFine -dw /data5/Train_Models/Detection_weigth/3090/202405/20240501-17413-pixel50-GHY/weights/best.pt -cw /data5/Train_Models/mmcls_onnx/CMB_GHY_Animal_52_1/convnext-base_4xb32_cmb200/end2end.onnx -c /data5/CAS_Project/CAS_ProjectAnimal/CMB_ProjectAnimal/CMB_GHY_Animal_52/animalListCNlist.txt -m "ai" -s /data5/Temp_ProjectData/mdh/GHY/20240604/NET_camera_images_01/ -o /data5/Hatcher/data/detection/testresult5 +0: 路径不存在 +1: 普通文件夹(不包含子文件夹) +2: 图像文件 +3: 视频文件 +4: 包含子文件夹的文件夹 +6: TXT文本文件 +7: 名称包含"long"的文件夹 +"always": 特殊标识符 +"文件": 其他类型文件 +"未知类型": 无法识别的类型 + +""" +import imp +from unicodedata import name +import torch,os +import cv2,time +import warnings +from PIL import Image +import onnxruntime as ort +import numpy as np +import torchvision +import argparse,mimetypes +from tqdm import tqdm +from scipy.io import loadmat +import cv2 +import json +from copy import deepcopy +from torch import Tensor +from configs.configs import model_head +from tqdm import tqdm +import os, sys, shutil +import torch +import platform,subprocess +import math,urllib +import random,requests +from pathlib import Path +from torch import nn +from PIL import Image, ImageDraw, ImageFont +from vizer.draw import draw_boxes +try: + import thop # for FLOPs computation +except ImportError: + thop = None +import numpy as np +import pkg_resources as pkg +from fine.fineConfig import LoadConfig, load_data_transformers +from torch.autograd import Variable +from creat_xml_fordetection import make_xml +import threading +from common import global_para as gp +import time, statistics +from typing import Tuple +import torch.nn.functional as F +root_path = os.getcwd() +sys.path.insert(0,root_path+"/Y5") +import matplotlib.pyplot as plt +import Y5.models +DebugPrint_flag = True +def parse_args(): + parser = argparse.ArgumentParser(description='Hatcher detection inference ') + parser.add_argument('-dw', '--detectionweights', type=str,default="/data5/PartDataset/007_BJNHZ/0018_20240608/20231211/best.pt", help='Input weights (.pt) file path (required)') + parser.add_argument('-cw', '--fineweights', type=str,default="/data5/PartDataset/007_BJNHZ/0018_20240608/20231211/convnext_base_in22k-CMB_BJNHZ_20230202_31_84590-RP-RC-RP.onnx", help='Input weights (.onnx) file path (required)') + parser.add_argument('-c', '--classes',type=str,default="/data5/PartDataset/007_BJNHZ/0018_20240608/20231211/CMB_BJNHZ_20230911_31.txt" , help='Input fine class label') + parser.add_argument('-m','--mode', default="ai",choices=['inf', 'ai'], help='inference mode') + parser.add_argument('-s', '--source', type=str,default="/data5/Hatcher/data/detection/test1/", help='Input test images file path (required)') + parser.add_argument( + '-o', '--out', type=str, default="/data5/Hatcher/data/detection/testresult", help='save path') + args = parser.parse_args() + if not os.path.isfile(args.detectionweights): + raise SystemExit('Invalid weights file') + return args.detectionweights, args.fineweights,args.classes,args.mode, args.source,args.out + +###### +def cv2AddChineseText(draw, text ,position, textColor=(0, 255, 0), textSize=30): + tp2 = time.time() + fontStyle = ImageFont.truetype( + "./Font/msyh.ttc", textSize, encoding="utf-8") + tp3 = time.time() + if gp.DebugPrint_flag: + print("tp2 is ", (tp3 - tp2) * 1000) + + draw.text(position, text, textColor, font=fontStyle) + + tp4 = time.time() + if gp.DebugPrint_flag: + print("tp3 is ", (tp4 - tp3) * 1000) + return draw#cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) +def plot_one_box(x, draw, height,width,color=None, label=None, Index = None, line_thickness=3): + # Plots one bounding box on image img + tl = line_thickness or round(0.002 * (height + width) / 2) + 1 # line/font thickness + color = color or tuple(random.randint(0, 255) for _ in range(3)) + c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) + draw.rectangle((c1, c2), fill=None, outline=color, width=tl) + if label: + tf = max(tl - 1, 1) # font thickness + t_size = cv2.getTextSize(label, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=gp.fontScale , thickness=tl)[0] + print(label,t_size[0],t_size[1]) + c1 = c1[0],c1[1]-t_size[1] + c2 = c1[0] + t_size[0], c1[1]+t_size[1] + draw.rectangle((c1, c2), fill=color, outline=color, width=tl) + draw = cv2AddChineseText(draw, label,(c1[0], c1[1]), textColor = (225, 255, 255), textSize=tf*17) + #img = cv2AddChineseText(img, "ÊýÁ¿: {}".format(str("011")), (2000,100), textColor=(0, 255, 0), textSize=80) + return draw +def clip_coords(boxes, shape): + # Clip bounding xyxy bounding boxes to image shape (height, width) + if isinstance(boxes, torch.Tensor): # faster individually + boxes[:, 0].clamp_(0, shape[1]) # x1 + boxes[:, 1].clamp_(0, shape[0]) # y1 + boxes[:, 2].clamp_(0, shape[1]) # x2 + boxes[:, 3].clamp_(0, shape[0]) # y2 + else: # np.array (faster grouped) + boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2 + boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2 +def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None): + # Rescale coords (xyxy) from img1_shape to img0_shape + if ratio_pad is None: # calculate from img0_shape + gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new + pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding + else: + gain = ratio_pad[0][0] + pad = ratio_pad[1] + + coords[:, [0, 2]] -= pad[0] # x padding + coords[:, [1, 3]] -= pad[1] # y padding + coords[:, :4] /= gain + clip_coords(coords, img0_shape) + return coords +def box_area(box): + # box = xyxy(4,n) + return (box[2] - box[0]) * (box[3] - box[1]) +def _upcast(t: Tensor) -> Tensor: + # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type + if t.is_floating_point(): + return t if t.dtype in (torch.float32, torch.float64) else t.float() + else: + return t if t.dtype in (torch.int32, torch.int64) else t.int() +def _box_inter_union(boxes1: Tensor, boxes2: Tensor) -> Tuple[Tensor, Tensor]: + area1 = box_area(boxes1) + area2 = box_area(boxes2) + + lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] + rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] + + wh = _upcast(rb - lt).clamp(min=0) # [N,M,2] + inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] + + union = area1[:, None] + area2 - inter + + return inter, union +def xywh2xyxy(x): + # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x + y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y + y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x + y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y + return y +def box_iou(boxes1: Tensor, boxes2: Tensor) -> Tensor: + + inter, union = _box_inter_union(boxes1, boxes2) + iou = inter / union + return iou +def non_max_suppression(prediction, + conf_thres=0.25, + iou_thres=0.45, + classes=None, + agnostic=False, + multi_label=False, + labels=(), + max_det=300): + """Non-Maximum Suppression (NMS) on inference results to reject overlapping bounding boxes + + Returns: + list of detections, on (n,6) tensor per image [xyxy, conf, cls] + """ + + bs = prediction.shape[0] # batch size + nc = prediction.shape[2] - 5 # number of classes + xc = prediction[..., 4] > conf_thres # candidates + + # Checks + assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0' + assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0' + + # Settings + # min_wh = 2 # (pixels) minimum box width and height + max_wh = 7680 # (pixels) maximum box width and height + max_nms = 30000 # maximum number of boxes into torchvision.ops.nms() + time_limit = 0.3 + 0.03 * bs # seconds to quit after + redundant = True # require redundant detections + multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img) + merge = False # use merge-NMS + + t = time.time() + output = [torch.zeros((0, 6), device=prediction.device)] * bs + for xi, x in enumerate(prediction): # image index, image inference + # Apply constraints + # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height + x = x[xc[xi]] # confidence + + # Cat apriori labels if autolabelling + if labels and len(labels[xi]): + lb = labels[xi] + v = torch.zeros((len(lb), nc + 5), device=x.device) + v[:, :4] = lb[:, 1:5] # box + v[:, 4] = 1.0 # conf + v[range(len(lb)), lb[:, 0].long() + 5] = 1.0 # cls + x = torch.cat((x, v), 0) + + # If none remain process next image + if not x.shape[0]: + continue + + # Compute conf + x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf + + # Box (center x, center y, width, height) to (x1, y1, x2, y2) + box = xywh2xyxy(x[:, :4]) + + # Detections matrix nx6 (xyxy, conf, cls) + if multi_label: + i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T + x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1) + else: # best class only + conf, j = x[:, 5:].max(1, keepdim=True) + x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres] + + # Filter by class + if classes is not None: + x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] + + # Apply finite constraint + # if not torch.isfinite(x).all(): + # x = x[torch.isfinite(x).all(1)] + + # Check shape + n = x.shape[0] # number of boxes + if not n: # no boxes + continue + elif n > max_nms: # excess boxes + x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence + + # Batched NMS + c = x[:, 5:6] * (0 if agnostic else max_wh) # classes + boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores + i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS + if i.shape[0] > max_det: # limit detections + i = i[:max_det] + if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean) + # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4) + iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix + weights = iou * scores[None] # box weights + x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes + if redundant: + i = i[iou.sum(1) > 1] # require redundancy + + output[xi] = x[i] + if (time.time() - t) > time_limit: + + break # time limit exceeded + + return output +def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32): + # Resize and pad image while meeting stride-multiple constraints + shape = im.shape[:2] # current shape [height, width] + if isinstance(new_shape, int): + new_shape = (new_shape, new_shape) + + # Scale ratio (new / old) + r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) + if not scaleup: # only scale down, do not scale up (for better val mAP) + r = min(r, 1.0) + + # Compute padding + ratio = r, r # width, height ratios + new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) + dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding + # if auto: # minimum rectangle + # dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding + # elif scaleFill: # stretch + # dw, dh = 0.0, 0.0 + # new_unpad = (new_shape[1], new_shape[0]) + # ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios + + dw /= 2 # divide padding into 2 sides + dh /= 2 + + if shape[::-1] != new_unpad: # resize + im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR) + top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) + left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) + im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border + return im, ratio, (dw, dh) +def check_anchor_order(m): + # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary + a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer + da = a[-1] - a[0] # delta a + ds = m.stride[-1] - m.stride[0] # delta s + if da and (da.sign() != ds.sign()): # same order + m.anchors[:] = m.anchors.flip(0) +def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False): + # Check version vs. required version + current, minimum = (pkg.parse_version(x) for x in (current, minimum)) + result = (current == minimum) if pinned else (current >= minimum) # bool + s = f'{name}{minimum} required by YOLOv5, but {name}{current} is currently installed' # string + if hard: + assert result, s # assert min requirements met + if verbose and not result: + pass + return result +class Detect(nn.Module): + stride = None # strides computed during build + onnx_dynamic = False # ONNX export parameter + export = False # export mode + + def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer + super().__init__() + self.nc = nc # number of classes + self.no = nc + 5 # number of outputs per anchor + self.nl = len(anchors) # number of detection layers + self.na = len(anchors[0]) // 2 # number of anchors + self.grid = [torch.zeros(1)] * self.nl # init grid + self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid + self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2) + self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv + self.inplace = inplace # use in-place ops (e.g. slice assignment) + + def forward(self, x): + z = [] # inference output + for i in range(self.nl): + x[i] = self.m[i](x[i]) # conv + bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) + x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() + + if not self.training: # inference + if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]: + self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i) + + y = x[i].sigmoid() + if self.inplace: + y[..., 0:2] = (y[..., 0:2] * 2 + self.grid[i]) * self.stride[i] # xy + y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh + else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953 + xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0 + xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy + wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh + y = torch.cat((xy, wh, conf), 4) + z.append(y.view(bs, -1, self.no)) + + return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x) + + def _make_grid(self, nx=20, ny=20, i=0): + d = self.anchors[i].device + t = self.anchors[i].dtype + shape = 1, self.na, ny, nx, 2 # grid shape + y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t) + if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility + yv, xv = torch.meshgrid(y, x, indexing='ij') + else: + yv, xv = torch.meshgrid(y, x) + grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5 + anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape) + return grid, anchor_grid + +def initialize_weights(model): + for m in model.modules(): + t = type(m) + if t is nn.Conv2d: + pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + elif t is nn.BatchNorm2d: + m.eps = 1e-3 + m.momentum = 0.03 + elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]: + m.inplace = True +def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) + # Scales img(bs,3,y,x) by ratio constrained to gs-multiple + if ratio == 1.0: + return img + h, w = img.shape[2:] + s = (int(h * ratio), int(w * ratio)) # new size + img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize + if not same_shape: # pad/crop img + h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w)) + return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean +def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')): + """ + x: Features to be visualized + module_type: Module type + stage: Module stage within model + n: Maximum number of feature maps to plot + save_dir: Directory to save results + """ + if 'Detect' not in module_type: + batch, channels, height, width = x.shape # batch, channels, height, width + if height > 1 and width > 1: + f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename + + blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels + n = min(n, channels) # number of plots + fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols + ax = ax.ravel() + plt.subplots_adjust(wspace=0.05, hspace=0.05) + for i in range(n): + ax[i].imshow(blocks[i].squeeze()) # cmap='gray' + ax[i].axis('off') + + + plt.savefig(f, dpi=300, bbox_inches='tight') + plt.close() + np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy()) # npy save +def time_sync(): + # PyTorch-accurate time + if torch.cuda.is_available(): + torch.cuda.synchronize() + return time.time() +def autopad(k, p=None): # kernel, padding + # Pad to 'same' + if p is None: + p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad + return p +class Conv(nn.Module): + # Standard convolution + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False) + self.bn = nn.BatchNorm2d(c2) + self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity()) + + def forward(self, x): + return self.act(self.bn(self.conv(x))) + + def forward_fuse(self, x): + return self.act(self.conv(x)) + + +class DWConv(Conv): + # Depth-wise convolution class + def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act) + + +class DWConvTranspose2d(nn.ConvTranspose2d): + # Depth-wise transpose convolution class + def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, kernel, stride, padding, padding_out + super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2)) + + +class TransformerLayer(nn.Module): + # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance) + def __init__(self, c, num_heads): + super().__init__() + self.q = nn.Linear(c, c, bias=False) + self.k = nn.Linear(c, c, bias=False) + self.v = nn.Linear(c, c, bias=False) + self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads) + self.fc1 = nn.Linear(c, c, bias=False) + self.fc2 = nn.Linear(c, c, bias=False) + + def forward(self, x): + x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x + x = self.fc2(self.fc1(x)) + x + return x + + +class TransformerBlock(nn.Module): + # Vision Transformer https://arxiv.org/abs/2010.11929 + def __init__(self, c1, c2, num_heads, num_layers): + super().__init__() + self.conv = None + if c1 != c2: + self.conv = Conv(c1, c2) + self.linear = nn.Linear(c2, c2) # learnable position embedding + self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers))) + self.c2 = c2 + + def forward(self, x): + if self.conv is not None: + x = self.conv(x) + b, _, w, h = x.shape + p = x.flatten(2).permute(2, 0, 1) + return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h) + + +class Bottleneck(nn.Module): + # Standard bottleneck + def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_, c2, 3, 1, g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x): + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) + + +class BottleneckCSP(nn.Module): + # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) + self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) + self.cv4 = Conv(2 * c_, c2, 1, 1) + self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) + self.act = nn.SiLU() + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) + + def forward(self, x): + y1 = self.cv3(self.m(self.cv1(x))) + y2 = self.cv2(x) + return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1)))) + + +class CrossConv(nn.Module): + # Cross Convolution Downsample + def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): + # ch_in, ch_out, kernel, stride, groups, expansion, shortcut + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, (1, k), (1, s)) + self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x): + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) + + +class C3(nn.Module): + # CSP Bottleneck with 3 convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c1, c_, 1, 1) + self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2) + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) + + def forward(self, x): + return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)) + + +class C3x(C3): + # C3 module with cross-convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n))) + + +class C3TR(C3): + # C3 module with TransformerBlock() + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = TransformerBlock(c_, c_, 4, n) + + +class C3SPP(C3): + # C3 module with SPP() + def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = SPP(c_, c_, k) + + +class C3Ghost(C3): + # C3 module with GhostBottleneck() + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) # hidden channels + self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n))) + + +class SPP(nn.Module): + # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729 + def __init__(self, c1, c2, k=(5, 9, 13)): + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) + self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) + + def forward(self, x): + x = self.cv1(x) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning + return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) + +FONT = 'Arial.ttf' +class SPPF(nn.Module): + # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher + def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13)) + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_ * 4, c2, 1, 1) + self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) + + def forward(self, x): + x = self.cv1(x) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning + y1 = self.m(x) + y2 = self.m(y1) + return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1)) + + +class Focus(nn.Module): + # Focus wh information into c-space + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.conv = Conv(c1 * 4, c2, k, s, p, g, act) + # self.contract = Contract(gain=2) + + def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) + return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1)) + # return self.conv(self.contract(x)) + + +class GhostConv(nn.Module): + # Ghost Convolution https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups + super().__init__() + c_ = c2 // 2 # hidden channels + self.cv1 = Conv(c1, c_, k, s, None, g, act) + self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) + + def forward(self, x): + y = self.cv1(x) + return torch.cat((y, self.cv2(y)), 1) + +class MixConv2d(nn.Module): + # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595 + def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy + super().__init__() + n = len(k) # number of convolutions + if equal_ch: # equal c_ per group + i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices + c_ = [(i == g).sum() for g in range(n)] # intermediate channels + else: # equal weight.numel() per group + b = [c2] + [0] * n + a = np.eye(n + 1, n, k=-1) + a -= np.roll(a, 1, axis=1) + a *= np.array(k) ** 2 + a[0] = 1 + c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b + + self.m = nn.ModuleList([ + nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)]) + self.bn = nn.BatchNorm2d(c2) + self.act = nn.SiLU() + + def forward(self, x): + return self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) +class GhostBottleneck(nn.Module): + # Ghost Bottleneck https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride + super().__init__() + c_ = c2 // 2 + self.conv = nn.Sequential( + GhostConv(c1, c_, 1, 1), # pw + DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw + GhostConv(c_, c2, 1, 1, act=False)) # pw-linear + self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, + act=False)) if s == 2 else nn.Identity() + + def forward(self, x): + return self.conv(x) + self.shortcut(x) + + +class Contract(nn.Module): + # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40) + def __init__(self, gain=2): + super().__init__() + self.gain = gain + + def forward(self, x): + b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain' + s = self.gain + x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2) + x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40) + return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40) + + +class Expand(nn.Module): + # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160) + def __init__(self, gain=2): + super().__init__() + self.gain = gain + + def forward(self, x): + b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain' + s = self.gain + x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80) + x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2) + return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160) + + +class Concat(nn.Module): + # Concatenate a list of tensors along dimension + def __init__(self, dimension=1): + super().__init__() + self.d = dimension + + def forward(self, x): + return torch.cat(x, self.d) + + + + + + + +def xyxy2xywh(x): + # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center + y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center + y[:, 2] = x[:, 2] - x[:, 0] # width + y[:, 3] = x[:, 3] - x[:, 1] # height + return y +def is_ascii(s=''): + # Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7) + s = str(s) # convert list, tuple, None, etc. to str + return len(s.encode().decode('ascii', 'ignore')) == len(s) +def is_writeable(dir, test=False): + # Return True if directory has write permissions, test opening a file with write permissions if test=True + if not test: + return os.access(dir, os.R_OK) # possible issues on Windows + file = Path(dir) / 'tmp.txt' + try: + with open(file, 'w'): # open file with write permissions + pass + file.unlink() # remove file + return True + except OSError: + return False +def user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'): + # Return path of user configuration directory. Prefer environment variable if exists. Make dir if required. + env = os.getenv(env_var) + if env: + path = Path(env) # use environment variable + else: + cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'} # 3 OS dirs + path = Path.home() / cfg.get(platform.system(), '') # OS-specific config dir + path = (path if is_writeable(path) else Path('/tmp')) / dir # GCP and AWS lambda fix, only /tmp is writeable + path.mkdir(exist_ok=True) # make if required + return path +CONFIG_DIR = user_config_dir() +def check_font(font=FONT, progress=False): + # Download font to CONFIG_DIR if necessary + font = Path(font) + file = CONFIG_DIR / font.name + if not font.exists() and not file.exists(): + url = "https://ultralytics.com/assets/" + font.name + + torch.hub.download_url_to_file(url, str(file), progress=progress) + +def check_pil_font(font=FONT, size=10): + # Return a PIL TrueType Font, downloading to CONFIG_DIR if necessary + font = Path(font) + font = font if font.exists() else (CONFIG_DIR / font.name) + try: + return ImageFont.truetype(str(font) if font.exists() else font.name, size) + except Exception: # download if missing + try: + check_font(font) + return ImageFont.truetype(str(font), size) + except TypeError: + pass # known issue https://github.com/ultralytics/yolov5/issues/5374 + + +class Annotator: + # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations + def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'): + assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.' + non_ascii = not is_ascii(example) # non-latin labels, i.e. asian, arabic, cyrillic + self.pil = pil or non_ascii + if self.pil: # use PIL + self.im = im if isinstance(im, Image.Image) else Image.fromarray(im) + self.draw = ImageDraw.Draw(self.im) + self.font = check_pil_font(font='Arial.Unicode.ttf' if non_ascii else font, + size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12)) + else: # use cv2 + self.im = im + self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width + + def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)): + # Add one xyxy box to image with label + if self.pil or not is_ascii(label): + self.draw.rectangle(box, width=self.lw, outline=color) # box + if label: + w, h = self.font.getsize(label) # text width, height + outside = box[1] - h >= 0 # label fits outside box + self.draw.rectangle( + (box[0], box[1] - h if outside else box[1], box[0] + w + 1, + box[1] + 1 if outside else box[1] + h + 1), + fill=color, + ) + # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0 + self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font) + else: # cv2 + p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3])) + cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA) + if label: + tf = max(self.lw - 1, 1) # font thickness + w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0] # text width, height + outside = p1[1] - h >= 3 + p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3 + cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled + cv2.putText(self.im, + label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2), + 0, + self.lw / 3, + txt_color, + thickness=tf, + lineType=cv2.LINE_AA) + + def rectangle(self, xy, fill=None, outline=None, width=1): + # Add rectangle to image (PIL-only) + self.draw.rectangle(xy, fill, outline, width) + + def text(self, xy, text, txt_color=(255, 255, 255)): + # Add text to image (PIL-only) + w, h = self.font.getsize(text) # text width, height + self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font) + + def result(self): + # Return annotated image as array + return np.asarray(self.im) + +class Detections: + # YOLOv5 detections class for inference results + def __init__(self, imgs, pred, files, times=(0, 0, 0, 0), names=None, shape=None): + super().__init__() + d = pred[0].device # device + gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in imgs] # normalizations + self.imgs = imgs # list of images as numpy arrays + self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls) + self.names = names # class names + self.files = files # image filenames + self.times = times # profiling times + self.xyxy = pred # xyxy pixels + self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels + self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized + self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized + self.n = len(self.pred) # number of images (batch size) + self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms) + self.s = shape # inference BCHW shape + + + + def tolist(self): + # return a list of Detections objects, i.e. 'for result in results.tolist():' + r = range(self.n) # iterable + x = [Detections([self.imgs[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r] + # for d in x: + # for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']: + # setattr(d, k, getattr(d, k)[0]) # pop out of list + return x + + def __len__(self): + return self.n # override len(results) + + def __str__(self): + self.print() # override print(results) + return '' +def fuse_conv_and_bn(conv, bn): + # Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ + fusedconv = nn.Conv2d(conv.in_channels, + conv.out_channels, + kernel_size=conv.kernel_size, + stride=conv.stride, + padding=conv.padding, + groups=conv.groups, + bias=True).requires_grad_(False).to(conv.weight.device) + + # Prepare filters + w_conv = conv.weight.clone().view(conv.out_channels, -1) + w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) + fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape)) + + # Prepare spatial bias + b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias + b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) + fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) + + return fusedconv + +class Classify(nn.Module): + # Classification head, i.e. x(b,c1,20,20) to x(b,c2) + def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1) + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1) + self.flat = nn.Flatten() + + def forward(self, x): + z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list + return self.flat(self.conv(z)) # flatten to x(b,c2) +class Model(nn.Module): + # YOLOv5 model + def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes + super().__init__() + if isinstance(cfg, dict): + self.yaml = cfg # model dict + else: # is *.yaml + import yaml # for torch hub + self.yaml_file = Path(cfg).name + with open(cfg, encoding='ascii', errors='ignore') as f: + self.yaml = yaml.safe_load(f) # model dict + + # Define model + ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels + if nc and nc != self.yaml['nc']: + + self.yaml['nc'] = nc # override yaml value + if anchors: + + self.yaml['anchors'] = round(anchors) # override yaml value + self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist + self.names = [str(i) for i in range(self.yaml['nc'])] # default names + self.inplace = self.yaml.get('inplace', True) + + # Build strides, anchors + m = self.model[-1] # Detect() + if isinstance(m, Detect): + s = 256 # 2x min stride + m.inplace = self.inplace + m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward + check_anchor_order(m) # must be in pixel-space (not grid-space) + m.anchors /= m.stride.view(-1, 1, 1) + self.stride = m.stride + self._initialize_biases() # only run once + + # Init weights, biases + initialize_weights(self) + self.info() + + + def forward(self, x, augment=False, profile=False, visualize=False): + if augment: + return self._forward_augment(x) # augmented inference, None + return self._forward_once(x, profile, visualize) # single-scale inference, train + + def _forward_augment(self, x): + img_size = x.shape[-2:] # height, width + s = [1, 0.83, 0.67] # scales + f = [None, 3, None] # flips (2-ud, 3-lr) + y = [] # outputs + for si, fi in zip(s, f): + xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) + yi = self._forward_once(xi)[0] # forward + # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save + yi = self._descale_pred(yi, fi, si, img_size) + y.append(yi) + y = self._clip_augmented(y) # clip augmented tails + return torch.cat(y, 1), None # augmented inference, train + + def _forward_once(self, x, profile=False, visualize=False): + y, dt = [], [] # outputs + for m in self.model: + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + if profile: + self._profile_one_layer(m, x, dt) + x = m(x) # run + y.append(x if m.i in self.save else None) # save output + if visualize: + feature_visualization(x, m.type, m.i, save_dir=visualize) + return x + + def _descale_pred(self, p, flips, scale, img_size): + # de-scale predictions following augmented inference (inverse operation) + if self.inplace: + p[..., :4] /= scale # de-scale + if flips == 2: + p[..., 1] = img_size[0] - p[..., 1] # de-flip ud + elif flips == 3: + p[..., 0] = img_size[1] - p[..., 0] # de-flip lr + else: + x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale + if flips == 2: + y = img_size[0] - y # de-flip ud + elif flips == 3: + x = img_size[1] - x # de-flip lr + p = torch.cat((x, y, wh, p[..., 4:]), -1) + return p + + def _clip_augmented(self, y): + # Clip YOLOv5 augmented inference tails + nl = self.model[-1].nl # number of detection layers (P3-P5) + g = sum(4 ** x for x in range(nl)) # grid points + e = 1 # exclude layer count + i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices + y[0] = y[0][:, :-i] # large + i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices + y[-1] = y[-1][:, i:] # small + return y + + def _profile_one_layer(self, m, x, dt): + c = isinstance(m, Detect) # is final layer, copy input as inplace fix + o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs + t = time_sync() + for _ in range(10): + m(x.copy() if c else x) + dt.append((time_sync() - t) * 100) + if m == self.model[0]: + pass + pass + if c: + pass + + def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency + # https://arxiv.org/abs/1708.02002 section 3.3 + # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. + m = self.model[-1] # Detect() module + for mi, s in zip(m.m, m.stride): # from + b = mi.bias.view(m.na, -1).detach() # conv.bias(255) to (3,85) + b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) + b[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls + mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) + + def _print_biases(self): + m = self.model[-1] # Detect() module + for mi in m.m: # from + b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) + + + # def _print_weights(self): + # for m in self.model.modules(): + # if type(m) is Bottleneck: + # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights + + def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers + + for m in self.model.modules(): + if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'): + m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv + delattr(m, 'bn') # remove batchnorm + m.forward = m.forward_fuse # update forward + self.info() + return self + + def info(self, verbose=False, img_size=640): # print model information + pass + #model_info(self, verbose, img_size) + + def _apply(self, fn): + # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers + self = super()._apply(fn) + m = self.model[-1] # Detect() + if isinstance(m, Detect): + m.stride = fn(m.stride) + m.grid = list(map(fn, m.grid)) + if isinstance(m.anchor_grid, list): + m.anchor_grid = list(map(fn, m.anchor_grid)) + return self +def make_divisible(x, divisor): + # Returns nearest x divisible by divisor + if isinstance(divisor, torch.Tensor): + divisor = int(divisor.max()) # to int + return math.ceil(x / divisor) * divisor + +def parse_model(d, ch): # model_dict, input_channels(3) + #LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") + anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] + na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors + no = na * (nc + 5) # number of outputs = anchors * (classes + 5) + + layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out + for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args + m = eval(m) if isinstance(m, str) else m # eval strings + for j, a in enumerate(args): + try: + args[j] = eval(a) if isinstance(a, str) else a # eval strings + except NameError: + pass + + n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain + if m in (Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, + BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x): + c1, c2 = ch[f], args[0] + if c2 != no: # if not output + c2 = make_divisible(c2 * gw, 8) + + args = [c1, c2, *args[1:]] + if m in [BottleneckCSP, C3, C3TR, C3Ghost, C3x]: + args.insert(2, n) # number of repeats + n = 1 + elif m is nn.BatchNorm2d: + args = [ch[f]] + elif m is Concat: + c2 = sum(ch[x] for x in f) + elif m is Detect: + args.append([ch[x] for x in f]) + if isinstance(args[1], int): # number of anchors + args[1] = [list(range(args[1] * 2))] * len(f) + elif m is Contract: + c2 = ch[f] * args[0] ** 2 + elif m is Expand: + c2 = ch[f] // args[0] ** 2 + else: + c2 = ch[f] + + m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module + t = str(m)[8:-2].replace('__main__.', '') # module type + np = sum(x.numel() for x in m_.parameters()) # number params + m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params + #LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print + save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist + layers.append(m_) + if i == 0: + ch = [] + ch.append(c2) + return nn.Sequential(*layers), sorted(save) +class Ensemble(nn.ModuleList): + # Ensemble of models + def __init__(self): + super().__init__() + + def forward(self, x, augment=False, profile=False, visualize=False): + y = [module(x, augment, profile, visualize)[0] for module in self] + # y = torch.stack(y).max(0)[0] # max ensemble + # y = torch.stack(y).mean(0) # mean ensemble + y = torch.cat(y, 1) # nms ensemble + return y, None # inference, train output +def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''): + # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes + + + file = Path(file) + assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}" + try: # url1 + #LOGGER.info(f'Downloading {url} to {file}...') + torch.hub.download_url_to_file(url, str(file), progress=True) + assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check + except Exception as e: # url2 + file.unlink(missing_ok=True) # remove partial downloads + #LOGGER.info(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...') + os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail + finally: + if not file.exists() or file.stat().st_size < min_bytes: # check + file.unlink(missing_ok=True) # remove partial downloads + #LOGGER.info(f"ERROR: {assert_msg}\n{error_msg}") + pass + #LOGGER.info('') +def attempt_download(file, repo='ultralytics/yolov5', release='v6.1'): + # Attempt file download from GitHub release assets if not found locally. release = 'latest', 'v6.1', etc. + + def github_assets(repository, version='latest'): + # Return GitHub repo tag (i.e. 'v6.1') and assets (i.e. ['yolov5s.pt', 'yolov5m.pt', ...]) + if version != 'latest': + version = f'tags/{version}' # i.e. tags/v6.1 + response = requests.get(f'https://api.github.com/repos/{repository}/releases/{version}').json() # github api + return response['tag_name'], [x['name'] for x in response['assets']] # tag, assets + + file = Path(str(file).strip().replace("'", '')) + if not file.exists(): + # URL specified + name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc. + if str(file).startswith(('http:/', 'https:/')): # download + url = str(file).replace(':/', '://') # Pathlib turns :// -> :/ + file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth... + if Path(file).is_file(): + pass + #LOGGER.info(f'Found {url} locally at {file}') # file already exists + else: + safe_download(file=file, url=url, min_bytes=1E5) + return file + + # GitHub assets + assets = [ + 'yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov5n6.pt', 'yolov5s6.pt', + 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] + try: + tag, assets = github_assets(repo, release) + except Exception: + try: + tag, assets = github_assets(repo) # latest release + except Exception: + try: + tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] + except Exception: + tag = release + + file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required) + if name in assets: + url3 = 'https://drive.google.com/drive/folders/1EFQTEUeXWSFww0luse2jB9M1QNZQGwNl' # backup gdrive mirror + safe_download( + file, + url=f'https://github.com/{repo}/releases/download/{tag}/{name}', + url2=f'https://storage.googleapis.com/{repo}/{tag}/{name}', # backup url (optional) + min_bytes=1E5, + error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/{tag} or {url3}') + + return str(file) +def attempt_load(weights, device=None, inplace=True, fuse=True): + # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a + + + model = Ensemble() + for w in weights if isinstance(weights, list) else [weights]: + ckpt = torch.load(attempt_download(w), map_location='cpu') # load + ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model + model.append(ckpt.fuse().eval() if fuse else ckpt.eval()) # fused or un-fused model in eval mode + + # Compatibility updates + for m in model.modules(): + t = type(m) + if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model): + m.inplace = inplace # torch 1.7.0 compatibility + if t is Detect and not isinstance(m.anchor_grid, list): + delattr(m, 'anchor_grid') + setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl) + elif t is Conv: + m._non_persistent_buffers_set = set() # torch 1.6.0 compatibility + elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'): + m.recompute_scale_factor = None # torch 1.11.0 compatibility + + if len(model) == 1: + return model[-1] # return model + print(f'Ensemble created with {weights}\n') + for k in 'names', 'nc', 'yaml': + setattr(model, k, getattr(model[0], k)) + model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride + assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}' + return model # return ensemble + + +###### + + +def identify_path_type(path): + # 检查路径是否存在 + print("原始路径为:{}".format(path)) + + if path =="always": + return "always" + + if not os.path.exists(path): + return 0 + if 'long' in path.lower(): + return 7 + # 检查是否为文件夹 + if os.path.isdir(path): + items = os.listdir(path) + for item in items: + if os.path.isdir(os.path.join(path, item)): + return 4 # Found a subfolder + return 1 + if os.path.splitext(path)[1].lower() == '.txt': + return 6 + + # 检查是否为文件 + if os.path.isfile(path): + # 获取文件的 MIME 类型 + mime_type, _ = mimetypes.guess_type(path) + if mime_type: + # 根据 MIME 类型判断是否为图像或视频 + if mime_type.startswith('image'): + return 2 + elif mime_type.startswith('video'): + return 3 + return "文件" + + return "未知类型" + +class Fine_grained_T: + def __init__(self, onnx_model): + """ + Initialization. + + Args: + onnx_model (str): Path to the ONNX model. + """ + if 'CUDAExecutionProvider' in ort.get_available_providers(): + print("CUDA is available. ONNXRuntime will use GPU.") + self.session = ort.InferenceSession( + onnx_model, + providers=["CUDAExecutionProvider", "CPUExecutionProvider"] + if ort.get_device() == "GPU" + else ["CPUExecutionProvider"], + ) + else: + print("CUDA is not available. ONNXRuntime will use CPU.") + print(ort.get_device()) + print("Fine is ready") + + + + def inference(self, img, imagelist, labellist, scorelist, fine_thresh1,infsize): + with torch.no_grad(): + for i, box in enumerate(imagelist): + if box[0] < 0: + box[0] = 0 + if box[1] < 0: + box[1] = 0 + if box[2] < 0: + box[2] = 0 + if box[3] < 0: + box[3] = 0 + X_left = int(box[1])-10 + if X_left < 0: + X_left = 0 + X_right = int(box[3])+10 + if X_right>2159: + X_right = 2159 + + y_up = int(box[0])-10 + if y_up <0 : + y_up = 0 + + y_down = int(box[2])+10 + if y_down>3839: + y_down =3839 + image = img.copy()[X_left:X_right, y_up:y_down, :] + image = Image.fromarray(image) + #image.save("/data5/Hatcher/data/count/testresult/11111.jpg") + #if gp.DebugPrint_flag: + #print(box) + #print(Img) + #if (int(box[3])-int(box[1])>gp.fine_thresh) and (int(box[2])-int(box[0])>gp.fine_thresh): + if ((int(box[3]) - int(box[1])) * (int(box[2]) - int(box[0]))) > fine_thresh1 : +# 定义归一化参数 + img_norm_cfg = dict( + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + to_rgb=True + ) + + image = image.resize((infsize, infsize)) + image = np.array(image).astype('float32') + if img_norm_cfg['to_rgb']: + image = image[..., ::-1] # BGR转RGB + image = np.transpose(image, (2, 0, 1)) # HWC转CHW + mean = np.array(img_norm_cfg['mean']).reshape(-1, 1, 1) + std = np.array(img_norm_cfg['std']).reshape(-1, 1, 1) + image = (image - mean) / std + image = np.expand_dims(image, axis=0) + image = image.astype('float32') + # 模型推理 + inputs = {self.session.get_inputs()[0].name: image} + outputs = self.session.run(None, inputs) + fineclass = np.argmax(outputs[0]) + labellist[i] = fineclass + + else: + pass + + return imagelist, labellist, scorelist + def inferenceone(self, imagepath): + image = Image.open(imagepath) + image = image.resize((224, 224)) # 假设模型需要 224x224 的输入 + image = np.array(image).astype('float32') + image = (np.transpose(image, (2, 0, 1))) # 改变通道顺序 + image = np.expand_dims(image, axis=0) + inputs = {self.session.get_inputs()[0].name: image} + outputs = self.session.run(None, inputs) + fineclass = np.argmax(outputs[0]) + #print(fineclass) + return(fineclass) + #print(fineclass) +class Detection: + def __init__(self,device,DetWeight,ChineseName): + self.device = device + self.img_size = 2176 + self.conf_thres = 0.3#0.6 + self.iou_thres = 0.4 + self.stride = 1 + self.weights = DetWeight + self.fine_thresh = 0.6 + self.fineinfsize = 224 + model = attempt_load(self.weights, device=self.device) + model.to(self.device).eval() + + model.half() + self.model = model + self.names = model.module.names if hasattr( + model, 'module') else model.names + self.ChineseName = ChineseName + print("Detection is in ",self.device) + print("Detection is ready") + # while(1): + # pass + + def preprocess(self, img): + + img0 = img.copy() + #img = cv2.resize(img, (2000, 1000)) + img = letterbox(img, new_shape=self.img_size, stride=self.stride)[0] + img = img[:, :, ::-1].transpose(2, 0, 1) + img = np.ascontiguousarray(img) + img = torch.from_numpy(img).to(self.device) + img = img.half() # ¡ã????¨¨ + img /= 255.0 # ¨ª???1¨¦¨°??¡¥ + if img.ndimension() == 3: + img = img.unsqueeze(0) + + return img0, img + def process_long_image(self, img_path, fine_grained, save_root): + image = cv2.imread(img_path) + if image is None: + print(f"Failed to load image: {img_path}") + return + + original_height, original_width = image.shape[:2] + + # 计算resize后的尺寸 + target_width = 3840 + num_splits = max(1, round(original_width / target_width)) + new_width = target_width * num_splits + scale_factor = new_width / original_width + new_height = int(original_height * scale_factor) + + # resize图像 + resized_image = cv2.resize(image, (new_width, new_height)) + + all_boxes = [] + all_labels = [] + all_scores = [] + + for i in range(num_splits): + start_x = i * target_width + end_x = (i + 1) * target_width + sub_image = resized_image[:, start_x:end_x] + + # 检测处理 + img_detect = cv2.resize(sub_image, (3840, 2160)) + detect_height, detect_width = img_detect.shape[:2] + image_scale, image = self.preprocess(img_detect) + + with torch.no_grad(): + pred = self.model(image, augment=False)[0] + pred = pred.float() + pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) + + for det in pred: + if det is not None and len(det): + # 先将坐标从模型输出转换到3840x2160 + det[:, :4] = scale_coords( + image.shape[2:], det[:, :4], img_detect.shape).round() + + # 计算从3840x2160到子图实际大小的缩放比例 + width_scale = sub_image.shape[1] / detect_width + height_scale = sub_image.shape[0] / detect_height + + # 转换坐标到子图实际大小 + boxes = det[:, :4].cpu().numpy() + boxes[:, [0, 2]] *= width_scale + boxes[:, [1, 3]] *= height_scale + + # 添加偏移量 + boxes[:, [0, 2]] += start_x + + scores = det[:, 4].cpu().numpy() + labels = det[:, -1].cpu().numpy() + + if len(labels) > 0: + boxes_fine, labels_fine, scores_fine = fine_grained.inference( + resized_image, boxes, labels, scores, + self.fine_thresh, self.fineinfsize) + + all_boxes.extend(boxes_fine) + all_labels.extend(labels_fine) + all_scores.extend(scores_fine) + + # 创建可视化结果 + result_image = resized_image.copy() + + # 添加调试信息 + + for i, box in enumerate(all_boxes): + print(f"Box {i}: {box}") + + for box, label, score in zip(all_boxes, all_labels, all_scores): + box = [int(b) for b in box] + color = (0, 255, 0) + # 确保坐标不超出图像边界 + x1 = max(0, min(box[0], result_image.shape[1]-1)) + y1 = max(0, min(box[1], result_image.shape[0]-1)) + x2 = max(0, min(box[2], result_image.shape[1]-1)) + y2 = max(0, min(box[3], result_image.shape[0]-1)) + + cv2.rectangle(result_image, (x1, y1), (x2, y2), color, 2) + label_text = "Oriental Stork"#f"{self.ChineseName[int(label)]} {score:.2f}" + cv2.putText(result_image, label_text, (x1, max(y1-10, 0)), + cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2) + + if not os.path.exists(save_root): + os.makedirs(save_root) + + output_path = os.path.join(save_root, os.path.basename(img_path)) + cv2.imwrite(output_path, result_image) + + xml_path = output_path.replace('.jpg', '.xml').replace('.JPG', '.xml') + make_xml(img_path, resized_image.shape[0], resized_image.shape[1], + all_boxes, all_labels, all_scores, xml_path) + def AIlabelFine(self, imagename, fine_grained,saveroot,islabel):#imagename 是文件的完整名字 + with torch.no_grad(): + # t2 = time.time() + + try: + t1 = time.time() + image = cv2.imread(imagename) + t2 = time.time() + if DebugPrint_flag: + print("加载图片的时间是 ",(t2-t1)*1000) + except: + #os.remove(imagename) + print(imagename,"is broken") + return + if not type(image): + print("skip") + return + image_or = image + + '''可视化注释 + img_show = image_or.copy() + if (isinstance(img_show, np.ndarray)): + img_show = Image.fromarray(cv2.cvtColor(img_show, cv2.COLOR_BGR2RGB)) + draw = ImageDraw.Draw(img_show) + ''' + try: + t1 = time.time() + img_detect = cv2.resize(image, (3840, 2160)) + t2 = time.time() + if DebugPrint_flag: + print("resize图片的时间是 ",(t2-t1)*1000) + except: + print(imagename+" is broken") + return + # t1 = time.time() + t1 = time.time() + image_scale, image = self.preprocess(img_detect) + t2 = time.time() + if DebugPrint_flag: + print("预处理的时间是 ",(t2-t1)*1000) + # t2 = time.time() + # if DebugPrint_flag: + # tqdm.write("Detection data deal is ",(t2-t1)*1000) + t1 = time.time() + pred = self.model(image, augment=False)[0] + pred = pred.float() + pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) + # t3 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection inference is ",(t3-t2)*1000) + boxes = [] + scores = [] + labels = [] + for det in pred: + if det is not None and len(det): + det[:, :4] = scale_coords( + image.shape[2:], det[:, :4], image_scale.shape).round() + boxes.append(det[:, :4]) + scores.append(det[:, 4]) + labels.append((det[:, -1])) + boxes = boxes[0] + scores = scores[0] + labels = labels[0] + t2 = time.time() + if DebugPrint_flag: + print("一次目标检测的时间是 ",(t2-t1)*1000) + # t5 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection get result is ", (t5 - t3) * 1000) + t1 = time.time() + if len(labels) > 0: + ratio_x = (image_or.shape[1] / 3840.0) + ratio_y = (image_or.shape[0] / 2160.0) + for i in range(len(boxes)): + boxes[i][0] = boxes[i][0] * ratio_x + boxes[i][2] = boxes[i][2] * ratio_x + boxes[i][1] = boxes[i][1] * ratio_y + boxes[i][3] = boxes[i][3] * ratio_y + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][3] < 0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 0 + boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores, self.fine_thresh,self.fineinfsize) + + t2 = time.time() + if DebugPrint_flag: + print("细粒度识别的时间是 ",(t2-t1)*1000) + # t4 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection final is ", (t4 - t3) * 1000) + '''不进行可视化 + for i in range(len(scores)): + xyxy = boxes_fine[i] + conf = scores_fine[i] + cls = labels_fine[i] + print(int(cls)) + label = str(self.ChineseName[int(cls)]) + #label = f'{int(cls)} {conf:.2f}' + palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1) + colors = tuple(int((p * (cls ** 2 - cls + 1)) % 255) for p in palette) + draw = plot_one_box(xyxy, draw, image_or.shape[1], image_or.shape[0], label=label, color=colors, + line_thickness=int(3 * gp.radioShowtext)) + savepath = os.path.join(saveroot,os.path.basename(imagename)) + img_show = cv2.cvtColor(np.asarray(img_show), cv2.COLOR_RGB2BGR) + cv2.imwrite(savepath,img_show) + ''' + if islabel: + # for i in range(len(scores)): + + # cls = labels_fine[i] + # print(int(cls)) + # labels_fine[i] = str(self.ChineseName[int(cls)]) + #print() + t1 = time.time() + savepath = os.path.join(saveroot,os.path.basename(imagename)) + xml_outputpath = savepath.replace(".jpg", ".xml").replace(".JPG", ".xml") + make_xml(imagename, image_or.shape[0], image_or.shape[1], boxes_fine, labels_fine, scores_fine, xml_outputpath) + + t2 = time.time() + if DebugPrint_flag: + print("结果存储的时间是 ",(t2-t1)*1000) + + else: + pass + '''不保存数据 + savepath = os.path.join(saveroot,os.path.basename(imagename)) + shutil.copy(imagename, savepath) + ''' + +def get_all_image_paths(folder_path): + + # Define common image file extensions + image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.tif') + + # Initialize an empty list to store the image paths + image_paths = [] + + # Walk through the folder and its subfolders + for root, dirs, files in tqdm(os.walk(folder_path)): + for file in files: + if file.lower().endswith(image_extensions): + # Get the absolute path of the image file + image_path = os.path.join(root, file) + image_paths.append(image_path) + + return image_paths + + + + + + +if __name__ == '__main__': + # Fine = Fine_grained_T("/data5/Train_Models/mmcls_onnx/CMB_YNDC_20240115_29/convnext-base_4xb32_cmb200/end2end.onnx") + # result = Fine.inferenceone("/data5/CAS_Project/CAS_ProjectBird/CMB/CMB_YNDC/CMB_YNDC_20231129_30/OrginalData/Bird/Bird___BJCH014_000447.jpg") + """ + 测试 + -dw /data5/Train_Models/Detection_weigth/3090/202306/20230619-131704-pixel5000-BJNHZ_Person/weights/best.pt + -cw /data5/Train_Models/mmcls_onnx/CMB_BJNHZ_20230910_144/convnext-base_4xb32_cmb200/end2end.onnx + -c /data5/CAS_Project/CAS_ProjectBird/CMB/CMB_BJNHZ/CMB_BJNHZ_20230910_144/birdListbirdCNlist.txt + -m "ai" + -s "/data5/Hatcher/data/detection/test1" + -o "/data5/Hatcher/data/detection/testresult" + """ + + + + + + Det_weights,Fine_weights,Fine_class,infmode,sourcepath,saveroot = parse_args() + # with open(Fine_class, 'r', encoding='utf-8') as file: + # bird_list = file.readlines() + with open(Fine_class, 'r', encoding='utf-8') as file: + content = file.read().strip() # 读取文件内容并去除首尾空格 + bird_list = content.split(';') # 使用分号分割字符串 + + #bird_list = [bird.strip() for bird in bird_list] + print(bird_list) + print(saveroot) + devices = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') + detection = Detection(devices,Det_weights,bird_list) + Fine = Fine_grained_T(Fine_weights) + if not os.path.exists(saveroot): + os.makedirs(saveroot) + fileType = identify_path_type(sourcepath) + print("处理模式为{}".format(str(fileType))) + if infmode == "ai": + islabel = 1 + if (fileType == 2): + print("开始处理单张图像数据") + #缺一个处理单个的函数 + detection.AIlabelFine(sourcepath,Fine,saveroot,islabel) + if (fileType == 1): #说明是文件夹 + print("开始处理文件夹批量数据") + fileList = os.listdir(sourcepath) + for filepath in tqdm(fileList): + sourcePath = os.path.join(sourcepath,filepath) + #缺一个处理单个的函数 + #print(sourcePath) + detection.AIlabelFine(sourcePath,Fine,saveroot,islabel) + if (fileType == 4): #说明是文件夹 + print("开始处理复杂文件夹批量数据") + fileList = get_all_image_paths(sourcepath) + #print(fileList) + for filepath in tqdm(fileList): + #sourcePath = os.path.join(sourcepath,filepath) + #缺一个处理单个的函数 + #print(sourcePath) + t1 = time.time() + detection.AIlabelFine(filepath,Fine,saveroot,islabel) + t2 = time.time() + if DebugPrint_flag: + print("推理一张图片的时间是 ",(t2-t1)*1000) + if (fileType == 6): #说明是文件路径的txt + print("开始处理txt文件中的批量数据") + with open(sourcepath, 'r') as file: + image_paths = [line.strip() for line in file.readlines()] + fileList = image_paths + #print(fileList) + for filepath in tqdm(fileList): + #sourcePath = os.path.join(sourcepath,filepath) + #缺一个处理单个的函数 + #print(sourcePath) + t1 = time.time() + detection.AIlabelFine(filepath,Fine,saveroot,islabel) + t2 = time.time() + if DebugPrint_flag: + print("推理一张图片的时间是 ",(t2-t1)*1000) + if (fileType == 7): #说明是文件路径的txt + print("开始处理长图像数据") + parent_dir = os.path.dirname(sourcepath) + save_root = os.path.join(parent_dir, 'output_') + if not os.path.exists(save_root): + os.makedirs(save_root) + + # 处理文件夹中的所有图像 + for img_name in tqdm(os.listdir(sourcepath)): + if img_name.lower().endswith(('.jpg', '.jpeg', '.png')): + img_path = os.path.join(sourcepath, img_name) + detection.process_long_image(img_path, Fine, save_root) + if (fileType == "always"): + print("开始循环处理输入数据") + while(1): + sourcepath = input("请输入测试文件路径: ") + if sourcepath == "q": + break + detection.AIlabelFine(sourcepath,Fine,saveroot,islabel) + #缺一个处理单个的函数 \ No newline at end of file diff --git a/NewDetAiLabelFine.spec b/NewDetAiLabelFine.spec new file mode 100755 index 0000000..2a7473f --- /dev/null +++ b/NewDetAiLabelFine.spec @@ -0,0 +1,38 @@ +# -*- mode: python ; coding: utf-8 -*- + + +a = Analysis( + ['NewDetAiLabelFine.py'], + pathex=[], + binaries=[], + datas=[], + hiddenimports=[], + hookspath=[], + hooksconfig={}, + runtime_hooks=[], + excludes=[], + noarchive=False, + optimize=0, +) +pyz = PYZ(a.pure) + +exe = EXE( + pyz, + a.scripts, + a.binaries, + a.datas, + [], + name='NewDetAiLabelFine', + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=True, + upx_exclude=[], + runtime_tmpdir=None, + console=True, + disable_windowed_traceback=False, + argv_emulation=False, + target_arch=None, + codesign_identity=None, + entitlements_file=None, +) diff --git a/NewDetAiLabelFine_mul.py b/NewDetAiLabelFine_mul.py new file mode 100755 index 0000000..3882a9b --- /dev/null +++ b/NewDetAiLabelFine_mul.py @@ -0,0 +1,1717 @@ +""" +测试代码: +1.-dw 输入目标检测权重,为pt文件,必要选项 +2.-cw 输入细粒度识别权重,为onnx文件,必要选项 +3.-c 输入细粒度识别名录,为txt文件,中文名字,每个中文用引号表示,中间用“,”隔开 +4.-m 系统执行模式,分两种,一种为推理图片,直接生成结果“inf”,一种为AI label,生成xml文件,“ai” +5.-s 源文件路径,可以是文件夹也可以是图片文件,如果是AI label,则在同级目录下面生成一个xml文件。,可以一直输入单张图片地址进行推理“always”,则源文件路径参数失效,需要输入1即可 +6.-o 存储根路径 + CUDA_VISIBLE_DEVICES=7 ./NewDetAiLabelFine -dw /data5/Train_Models/Detection_weigth/3090/202405/20240501-17413-pixel50-GHY/weights/best.pt -cw /data5/Train_Models/mmcls_onnx/CMB_GHY_Animal_52_1/convnext-base_4xb32_cmb200/end2end.onnx -c /data5/CAS_Project/CAS_ProjectAnimal/CMB_ProjectAnimal/CMB_GHY_Animal_52/animalListCNlist.txt -m "ai" -s /data5/Temp_ProjectData/mdh/GHY/20240604/NET_camera_images_01/ -o /data5/Hatcher/data/detection/testresult5 +""" +import imp +from unicodedata import name +import torch,os +import cv2,time +import warnings +from PIL import Image +import onnxruntime as ort +import numpy as np +import torchvision +import argparse,mimetypes +from tqdm import tqdm +from scipy.io import loadmat +import cv2 +import json +from copy import deepcopy +from torch import Tensor +from configs.configs import model_head +from tqdm import tqdm +import os, sys, shutil +import torch +import platform,subprocess +import math,urllib +import random,requests +from pathlib import Path +from torch import nn +from PIL import Image, ImageDraw, ImageFont +from vizer.draw import draw_boxes +from concurrent.futures import ThreadPoolExecutor,as_completed +try: + import thop # for FLOPs computation +except ImportError: + thop = None +# from ssd.config import cfg +# from ssd.data.datasets import VOCDataset +import numpy as np +import pkg_resources as pkg +# from ssd.data.transforms import build_transforms +# from ssd.modeling.detector import build_detection_model +# from ssd.utils.checkpoint import CheckPointer +#from fine.models.LoadModel import MainModel +from fine.fineConfig import LoadConfig, load_data_transformers +from torch.autograd import Variable +from creat_xml_fordetection import make_xml +import threading +from common import global_para as gp +import time, statistics +from typing import Tuple +import torch.nn.functional as F +# root_path = os.getcwd() +# sys.path.insert(0,root_path+"/Y5") + +#from Y5_old.utils.plots import plot_one_box +root_path = os.getcwd() +sys.path.insert(0,root_path+"/Y5") +import matplotlib.pyplot as plt +import Y5.models +DebugPrint_flag = True +def parse_args(): + parser = argparse.ArgumentParser(description='Hatcher detection inference ') + parser.add_argument('-dw', '--detectionweights', type=str,default="/data5/PartDataset/007_BJNHZ/0018_20240608/20231211/best.pt", help='Input weights (.pt) file path (required)') + parser.add_argument('-cw', '--fineweights', type=str,default="/data5/PartDataset/007_BJNHZ/0018_20240608/20231211/convnext_base_in22k-CMB_BJNHZ_20230202_31_84590-RP-RC-RP.onnx", help='Input weights (.onnx) file path (required)') + parser.add_argument('-c', '--classes',type=str,default="/data5/PartDataset/007_BJNHZ/0018_20240608/20231211/CMB_BJNHZ_20230911_31.txt" , help='Input fine class label') + parser.add_argument('-m','--mode', default="ai",choices=['inf', 'ai'], help='inference mode') + parser.add_argument('-s', '--source', type=str,default="/data5/Hatcher/data/detection/test1/", help='Input test images file path (required)') + parser.add_argument( + '-o', '--out', type=str, default="/data5/Hatcher/data/detection/testresult", help='save path') + args = parser.parse_args() + if not os.path.isfile(args.detectionweights): + raise SystemExit('Invalid weights file') + return args.detectionweights, args.fineweights,args.classes,args.mode, args.source,args.out + +###### +def cv2AddChineseText(draw, text ,position, textColor=(0, 255, 0), textSize=30): + # tp1 = time.time() + # if (isinstance(img, np.ndarray)): # ?D??¨º?¡¤?OpenCV¨ª???¨¤¨¤D¨ª + # img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) + # tp2 = time.time() + # if gp.DebugPrint_flag: + # print("tp1 is ", (tp2 - tp1) * 1000) + # draw = ImageDraw.Draw(img) + tp2 = time.time() + fontStyle = ImageFont.truetype( + "./Font/msyh.ttc", textSize, encoding="utf-8") + tp3 = time.time() + if gp.DebugPrint_flag: + print("tp2 is ", (tp3 - tp2) * 1000) + + draw.text(position, text, textColor, font=fontStyle) + + tp4 = time.time() + if gp.DebugPrint_flag: + print("tp3 is ", (tp4 - tp3) * 1000) + return draw#cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) +def plot_one_box(x, draw, height,width,color=None, label=None, Index = None, line_thickness=3): + # Plots one bounding box on image img + tl = line_thickness or round(0.002 * (height + width) / 2) + 1 # line/font thickness + color = color or tuple(random.randint(0, 255) for _ in range(3)) + c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) + #ÏÔʾindex + + + # draw.text((c1[0]-20, c1[1]), str(Index), (0, 0, 255),font=fontStyle) + draw.rectangle((c1, c2), fill=None, outline=color, width=tl) + if label: + tf = max(tl - 1, 1) # font thickness + t_size = cv2.getTextSize(label, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=gp.fontScale , thickness=tl)[0] + print(label,t_size[0],t_size[1]) + c1 = c1[0],c1[1]-t_size[1] + c2 = c1[0] + t_size[0], c1[1]+t_size[1] + draw.rectangle((c1, c2), fill=color, outline=color, width=tl) + #cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled + #cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) + #if not label == None: + + draw = cv2AddChineseText(draw, label,(c1[0], c1[1]), textColor = (225, 255, 255), textSize=tf*17) + #img = cv2AddChineseText(img, "ÊýÁ¿: {}".format(str("011")), (2000,100), textColor=(0, 255, 0), textSize=80) + return draw +def clip_coords(boxes, shape): + # Clip bounding xyxy bounding boxes to image shape (height, width) + if isinstance(boxes, torch.Tensor): # faster individually + boxes[:, 0].clamp_(0, shape[1]) # x1 + boxes[:, 1].clamp_(0, shape[0]) # y1 + boxes[:, 2].clamp_(0, shape[1]) # x2 + boxes[:, 3].clamp_(0, shape[0]) # y2 + else: # np.array (faster grouped) + boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2 + boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2 +def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None): + # Rescale coords (xyxy) from img1_shape to img0_shape + if ratio_pad is None: # calculate from img0_shape + gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new + pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding + else: + gain = ratio_pad[0][0] + pad = ratio_pad[1] + + coords[:, [0, 2]] -= pad[0] # x padding + coords[:, [1, 3]] -= pad[1] # y padding + coords[:, :4] /= gain + clip_coords(coords, img0_shape) + return coords +def box_area(box): + # box = xyxy(4,n) + return (box[2] - box[0]) * (box[3] - box[1]) +def _upcast(t: Tensor) -> Tensor: + # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type + if t.is_floating_point(): + return t if t.dtype in (torch.float32, torch.float64) else t.float() + else: + return t if t.dtype in (torch.int32, torch.int64) else t.int() +def _box_inter_union(boxes1: Tensor, boxes2: Tensor) -> Tuple[Tensor, Tensor]: + area1 = box_area(boxes1) + area2 = box_area(boxes2) + + lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] + rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] + + wh = _upcast(rb - lt).clamp(min=0) # [N,M,2] + inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] + + union = area1[:, None] + area2 - inter + + return inter, union +def xywh2xyxy(x): + # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x + y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y + y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x + y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y + return y +def box_iou(boxes1: Tensor, boxes2: Tensor) -> Tensor: + """ + Return intersection-over-union (Jaccard index) of boxes. + + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + + Args: + boxes1 (Tensor[N, 4]) + boxes2 (Tensor[M, 4]) + + Returns: + iou (Tensor[N, M]): the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2 + """ + inter, union = _box_inter_union(boxes1, boxes2) + iou = inter / union + return iou +def non_max_suppression(prediction, + conf_thres=0.25, + iou_thres=0.45, + classes=None, + agnostic=False, + multi_label=False, + labels=(), + max_det=300): + """Non-Maximum Suppression (NMS) on inference results to reject overlapping bounding boxes + + Returns: + list of detections, on (n,6) tensor per image [xyxy, conf, cls] + """ + + bs = prediction.shape[0] # batch size + nc = prediction.shape[2] - 5 # number of classes + xc = prediction[..., 4] > conf_thres # candidates + + # Checks + assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0' + assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0' + + # Settings + # min_wh = 2 # (pixels) minimum box width and height + max_wh = 7680 # (pixels) maximum box width and height + max_nms = 30000 # maximum number of boxes into torchvision.ops.nms() + time_limit = 0.3 + 0.03 * bs # seconds to quit after + redundant = True # require redundant detections + multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img) + merge = False # use merge-NMS + + t = time.time() + output = [torch.zeros((0, 6), device=prediction.device)] * bs + for xi, x in enumerate(prediction): # image index, image inference + # Apply constraints + # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height + x = x[xc[xi]] # confidence + + # Cat apriori labels if autolabelling + if labels and len(labels[xi]): + lb = labels[xi] + v = torch.zeros((len(lb), nc + 5), device=x.device) + v[:, :4] = lb[:, 1:5] # box + v[:, 4] = 1.0 # conf + v[range(len(lb)), lb[:, 0].long() + 5] = 1.0 # cls + x = torch.cat((x, v), 0) + + # If none remain process next image + if not x.shape[0]: + continue + + # Compute conf + x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf + + # Box (center x, center y, width, height) to (x1, y1, x2, y2) + box = xywh2xyxy(x[:, :4]) + + # Detections matrix nx6 (xyxy, conf, cls) + if multi_label: + i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T + x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1) + else: # best class only + conf, j = x[:, 5:].max(1, keepdim=True) + x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres] + + # Filter by class + if classes is not None: + x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] + + # Apply finite constraint + # if not torch.isfinite(x).all(): + # x = x[torch.isfinite(x).all(1)] + + # Check shape + n = x.shape[0] # number of boxes + if not n: # no boxes + continue + elif n > max_nms: # excess boxes + x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence + + # Batched NMS + c = x[:, 5:6] * (0 if agnostic else max_wh) # classes + boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores + i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS + if i.shape[0] > max_det: # limit detections + i = i[:max_det] + if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean) + # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4) + iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix + weights = iou * scores[None] # box weights + x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes + if redundant: + i = i[iou.sum(1) > 1] # require redundancy + + output[xi] = x[i] + if (time.time() - t) > time_limit: + + break # time limit exceeded + + return output +def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32): + # Resize and pad image while meeting stride-multiple constraints + shape = im.shape[:2] # current shape [height, width] + if isinstance(new_shape, int): + new_shape = (new_shape, new_shape) + + # Scale ratio (new / old) + r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) + if not scaleup: # only scale down, do not scale up (for better val mAP) + r = min(r, 1.0) + + # Compute padding + ratio = r, r # width, height ratios + new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) + dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding + # if auto: # minimum rectangle + # dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding + # elif scaleFill: # stretch + # dw, dh = 0.0, 0.0 + # new_unpad = (new_shape[1], new_shape[0]) + # ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios + + dw /= 2 # divide padding into 2 sides + dh /= 2 + + if shape[::-1] != new_unpad: # resize + im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR) + top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) + left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) + im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border + return im, ratio, (dw, dh) +def check_anchor_order(m): + # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary + a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer + da = a[-1] - a[0] # delta a + ds = m.stride[-1] - m.stride[0] # delta s + if da and (da.sign() != ds.sign()): # same order + m.anchors[:] = m.anchors.flip(0) +def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False): + # Check version vs. required version + current, minimum = (pkg.parse_version(x) for x in (current, minimum)) + result = (current == minimum) if pinned else (current >= minimum) # bool + s = f'{name}{minimum} required by YOLOv5, but {name}{current} is currently installed' # string + if hard: + assert result, s # assert min requirements met + if verbose and not result: + pass + return result +class Detect(nn.Module): + stride = None # strides computed during build + onnx_dynamic = False # ONNX export parameter + export = False # export mode + + def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer + super().__init__() + self.nc = nc # number of classes + self.no = nc + 5 # number of outputs per anchor + self.nl = len(anchors) # number of detection layers + self.na = len(anchors[0]) // 2 # number of anchors + self.grid = [torch.zeros(1)] * self.nl # init grid + self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid + self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2) + self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv + self.inplace = inplace # use in-place ops (e.g. slice assignment) + + def forward(self, x): + z = [] # inference output + for i in range(self.nl): + x[i] = self.m[i](x[i]) # conv + bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) + x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() + + if not self.training: # inference + if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]: + self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i) + + y = x[i].sigmoid() + if self.inplace: + y[..., 0:2] = (y[..., 0:2] * 2 + self.grid[i]) * self.stride[i] # xy + y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh + else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953 + xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0 + xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy + wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh + y = torch.cat((xy, wh, conf), 4) + z.append(y.view(bs, -1, self.no)) + + return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x) + + def _make_grid(self, nx=20, ny=20, i=0): + d = self.anchors[i].device + t = self.anchors[i].dtype + shape = 1, self.na, ny, nx, 2 # grid shape + y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t) + if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility + yv, xv = torch.meshgrid(y, x, indexing='ij') + else: + yv, xv = torch.meshgrid(y, x) + grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5 + anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape) + return grid, anchor_grid + +def initialize_weights(model): + for m in model.modules(): + t = type(m) + if t is nn.Conv2d: + pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + elif t is nn.BatchNorm2d: + m.eps = 1e-3 + m.momentum = 0.03 + elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]: + m.inplace = True +def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) + # Scales img(bs,3,y,x) by ratio constrained to gs-multiple + if ratio == 1.0: + return img + h, w = img.shape[2:] + s = (int(h * ratio), int(w * ratio)) # new size + img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize + if not same_shape: # pad/crop img + h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w)) + return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean +def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')): + """ + x: Features to be visualized + module_type: Module type + stage: Module stage within model + n: Maximum number of feature maps to plot + save_dir: Directory to save results + """ + if 'Detect' not in module_type: + batch, channels, height, width = x.shape # batch, channels, height, width + if height > 1 and width > 1: + f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename + + blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels + n = min(n, channels) # number of plots + fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols + ax = ax.ravel() + plt.subplots_adjust(wspace=0.05, hspace=0.05) + for i in range(n): + ax[i].imshow(blocks[i].squeeze()) # cmap='gray' + ax[i].axis('off') + + + plt.savefig(f, dpi=300, bbox_inches='tight') + plt.close() + np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy()) # npy save +def time_sync(): + # PyTorch-accurate time + if torch.cuda.is_available(): + torch.cuda.synchronize() + return time.time() +def autopad(k, p=None): # kernel, padding + # Pad to 'same' + if p is None: + p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad + return p +class Conv(nn.Module): + # Standard convolution + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False) + self.bn = nn.BatchNorm2d(c2) + self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity()) + + def forward(self, x): + return self.act(self.bn(self.conv(x))) + + def forward_fuse(self, x): + return self.act(self.conv(x)) + + +class DWConv(Conv): + # Depth-wise convolution class + def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act) + + +class DWConvTranspose2d(nn.ConvTranspose2d): + # Depth-wise transpose convolution class + def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, kernel, stride, padding, padding_out + super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2)) + + +class TransformerLayer(nn.Module): + # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance) + def __init__(self, c, num_heads): + super().__init__() + self.q = nn.Linear(c, c, bias=False) + self.k = nn.Linear(c, c, bias=False) + self.v = nn.Linear(c, c, bias=False) + self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads) + self.fc1 = nn.Linear(c, c, bias=False) + self.fc2 = nn.Linear(c, c, bias=False) + + def forward(self, x): + x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x + x = self.fc2(self.fc1(x)) + x + return x + + +class TransformerBlock(nn.Module): + # Vision Transformer https://arxiv.org/abs/2010.11929 + def __init__(self, c1, c2, num_heads, num_layers): + super().__init__() + self.conv = None + if c1 != c2: + self.conv = Conv(c1, c2) + self.linear = nn.Linear(c2, c2) # learnable position embedding + self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers))) + self.c2 = c2 + + def forward(self, x): + if self.conv is not None: + x = self.conv(x) + b, _, w, h = x.shape + p = x.flatten(2).permute(2, 0, 1) + return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h) + + +class Bottleneck(nn.Module): + # Standard bottleneck + def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_, c2, 3, 1, g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x): + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) + + +class BottleneckCSP(nn.Module): + # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) + self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) + self.cv4 = Conv(2 * c_, c2, 1, 1) + self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) + self.act = nn.SiLU() + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) + + def forward(self, x): + y1 = self.cv3(self.m(self.cv1(x))) + y2 = self.cv2(x) + return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1)))) + + +class CrossConv(nn.Module): + # Cross Convolution Downsample + def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): + # ch_in, ch_out, kernel, stride, groups, expansion, shortcut + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, (1, k), (1, s)) + self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x): + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) + + +class C3(nn.Module): + # CSP Bottleneck with 3 convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c1, c_, 1, 1) + self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2) + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) + + def forward(self, x): + return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)) + + +class C3x(C3): + # C3 module with cross-convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n))) + + +class C3TR(C3): + # C3 module with TransformerBlock() + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = TransformerBlock(c_, c_, 4, n) + + +class C3SPP(C3): + # C3 module with SPP() + def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = SPP(c_, c_, k) + + +class C3Ghost(C3): + # C3 module with GhostBottleneck() + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) # hidden channels + self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n))) + + +class SPP(nn.Module): + # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729 + def __init__(self, c1, c2, k=(5, 9, 13)): + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) + self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) + + def forward(self, x): + x = self.cv1(x) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning + return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) + +FONT = 'Arial.ttf' +class SPPF(nn.Module): + # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher + def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13)) + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_ * 4, c2, 1, 1) + self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) + + def forward(self, x): + x = self.cv1(x) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning + y1 = self.m(x) + y2 = self.m(y1) + return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1)) + + +class Focus(nn.Module): + # Focus wh information into c-space + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.conv = Conv(c1 * 4, c2, k, s, p, g, act) + # self.contract = Contract(gain=2) + + def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) + return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1)) + # return self.conv(self.contract(x)) + + +class GhostConv(nn.Module): + # Ghost Convolution https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups + super().__init__() + c_ = c2 // 2 # hidden channels + self.cv1 = Conv(c1, c_, k, s, None, g, act) + self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) + + def forward(self, x): + y = self.cv1(x) + return torch.cat((y, self.cv2(y)), 1) + +class MixConv2d(nn.Module): + # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595 + def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy + super().__init__() + n = len(k) # number of convolutions + if equal_ch: # equal c_ per group + i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices + c_ = [(i == g).sum() for g in range(n)] # intermediate channels + else: # equal weight.numel() per group + b = [c2] + [0] * n + a = np.eye(n + 1, n, k=-1) + a -= np.roll(a, 1, axis=1) + a *= np.array(k) ** 2 + a[0] = 1 + c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b + + self.m = nn.ModuleList([ + nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)]) + self.bn = nn.BatchNorm2d(c2) + self.act = nn.SiLU() + + def forward(self, x): + return self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) +class GhostBottleneck(nn.Module): + # Ghost Bottleneck https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride + super().__init__() + c_ = c2 // 2 + self.conv = nn.Sequential( + GhostConv(c1, c_, 1, 1), # pw + DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw + GhostConv(c_, c2, 1, 1, act=False)) # pw-linear + self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, + act=False)) if s == 2 else nn.Identity() + + def forward(self, x): + return self.conv(x) + self.shortcut(x) + + +class Contract(nn.Module): + # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40) + def __init__(self, gain=2): + super().__init__() + self.gain = gain + + def forward(self, x): + b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain' + s = self.gain + x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2) + x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40) + return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40) + + +class Expand(nn.Module): + # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160) + def __init__(self, gain=2): + super().__init__() + self.gain = gain + + def forward(self, x): + b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain' + s = self.gain + x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80) + x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2) + return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160) + + +class Concat(nn.Module): + # Concatenate a list of tensors along dimension + def __init__(self, dimension=1): + super().__init__() + self.d = dimension + + def forward(self, x): + return torch.cat(x, self.d) + + + + + + + +def xyxy2xywh(x): + # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center + y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center + y[:, 2] = x[:, 2] - x[:, 0] # width + y[:, 3] = x[:, 3] - x[:, 1] # height + return y +def is_ascii(s=''): + # Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7) + s = str(s) # convert list, tuple, None, etc. to str + return len(s.encode().decode('ascii', 'ignore')) == len(s) +def is_writeable(dir, test=False): + # Return True if directory has write permissions, test opening a file with write permissions if test=True + if not test: + return os.access(dir, os.R_OK) # possible issues on Windows + file = Path(dir) / 'tmp.txt' + try: + with open(file, 'w'): # open file with write permissions + pass + file.unlink() # remove file + return True + except OSError: + return False +def user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'): + # Return path of user configuration directory. Prefer environment variable if exists. Make dir if required. + env = os.getenv(env_var) + if env: + path = Path(env) # use environment variable + else: + cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'} # 3 OS dirs + path = Path.home() / cfg.get(platform.system(), '') # OS-specific config dir + path = (path if is_writeable(path) else Path('/tmp')) / dir # GCP and AWS lambda fix, only /tmp is writeable + path.mkdir(exist_ok=True) # make if required + return path +CONFIG_DIR = user_config_dir() +def check_font(font=FONT, progress=False): + # Download font to CONFIG_DIR if necessary + font = Path(font) + file = CONFIG_DIR / font.name + if not font.exists() and not file.exists(): + url = "https://ultralytics.com/assets/" + font.name + + torch.hub.download_url_to_file(url, str(file), progress=progress) + +def check_pil_font(font=FONT, size=10): + # Return a PIL TrueType Font, downloading to CONFIG_DIR if necessary + font = Path(font) + font = font if font.exists() else (CONFIG_DIR / font.name) + try: + return ImageFont.truetype(str(font) if font.exists() else font.name, size) + except Exception: # download if missing + try: + check_font(font) + return ImageFont.truetype(str(font), size) + except TypeError: + pass # known issue https://github.com/ultralytics/yolov5/issues/5374 + + +class Annotator: + # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations + def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'): + assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.' + non_ascii = not is_ascii(example) # non-latin labels, i.e. asian, arabic, cyrillic + self.pil = pil or non_ascii + if self.pil: # use PIL + self.im = im if isinstance(im, Image.Image) else Image.fromarray(im) + self.draw = ImageDraw.Draw(self.im) + self.font = check_pil_font(font='Arial.Unicode.ttf' if non_ascii else font, + size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12)) + else: # use cv2 + self.im = im + self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width + + def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)): + # Add one xyxy box to image with label + if self.pil or not is_ascii(label): + self.draw.rectangle(box, width=self.lw, outline=color) # box + if label: + w, h = self.font.getsize(label) # text width, height + outside = box[1] - h >= 0 # label fits outside box + self.draw.rectangle( + (box[0], box[1] - h if outside else box[1], box[0] + w + 1, + box[1] + 1 if outside else box[1] + h + 1), + fill=color, + ) + # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0 + self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font) + else: # cv2 + p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3])) + cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA) + if label: + tf = max(self.lw - 1, 1) # font thickness + w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0] # text width, height + outside = p1[1] - h >= 3 + p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3 + cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled + cv2.putText(self.im, + label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2), + 0, + self.lw / 3, + txt_color, + thickness=tf, + lineType=cv2.LINE_AA) + + def rectangle(self, xy, fill=None, outline=None, width=1): + # Add rectangle to image (PIL-only) + self.draw.rectangle(xy, fill, outline, width) + + def text(self, xy, text, txt_color=(255, 255, 255)): + # Add text to image (PIL-only) + w, h = self.font.getsize(text) # text width, height + self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font) + + def result(self): + # Return annotated image as array + return np.asarray(self.im) + +class Detections: + # YOLOv5 detections class for inference results + def __init__(self, imgs, pred, files, times=(0, 0, 0, 0), names=None, shape=None): + super().__init__() + d = pred[0].device # device + gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in imgs] # normalizations + self.imgs = imgs # list of images as numpy arrays + self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls) + self.names = names # class names + self.files = files # image filenames + self.times = times # profiling times + self.xyxy = pred # xyxy pixels + self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels + self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized + self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized + self.n = len(self.pred) # number of images (batch size) + self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms) + self.s = shape # inference BCHW shape + + # def display(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')): + # crops = [] + # for i, (im, pred) in enumerate(zip(self.imgs, self.pred)): + # s = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string + # if pred.shape[0]: + # for c in pred[:, -1].unique(): + # n = (pred[:, -1] == c).sum() # detections per class + # s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string + # if show or save or render or crop: + # annotator = Annotator(im, example=str(self.names)) + # for *box, conf, cls in reversed(pred): # xyxy, confidence, class + # label = f'{self.names[int(cls)]} {conf:.2f}' + # if crop: + # file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None + # crops.append({ + # 'box': box, + # 'conf': conf, + # 'cls': cls, + # 'label': label, + # 'im': save_one_box(box, im, file=file, save=save)}) + # else: # all others + # annotator.box_label(box, label if labels else '', color=colors(cls)) + # im = annotator.im + # else: + # s += '(no detections)' + + # im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np + # if pprint: + # print(s.rstrip(', ')) + # if show: + # im.show(self.files[i]) # show + # if save: + # f = self.files[i] + # im.save(save_dir / f) # save + # if i == self.n - 1: + # pass + # #LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}") + # if render: + # self.imgs[i] = np.asarray(im) + # if crop: + # if save: + # pass + # #LOGGER.info(f'Saved results to {save_dir}\n') + # return crops + + # def print(self): + # self.display(pprint=True) # print results + # print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' % self.t) + + # def show(self, labels=True): + # self.display(show=True, labels=labels) # show results + + + + + # def render(self, labels=True): + # self.display(render=True, labels=labels) # render results + # return self.imgs + + # def pandas(self): + # # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0]) + # new = copy(self) # return copy + # ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns + # cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns + # for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]): + # a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update + # setattr(new, k, [pd.DataFrame(x, columns=c) for x in a]) + # return new + + def tolist(self): + # return a list of Detections objects, i.e. 'for result in results.tolist():' + r = range(self.n) # iterable + x = [Detections([self.imgs[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r] + # for d in x: + # for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']: + # setattr(d, k, getattr(d, k)[0]) # pop out of list + return x + + def __len__(self): + return self.n # override len(results) + + def __str__(self): + self.print() # override print(results) + return '' +def fuse_conv_and_bn(conv, bn): + # Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ + fusedconv = nn.Conv2d(conv.in_channels, + conv.out_channels, + kernel_size=conv.kernel_size, + stride=conv.stride, + padding=conv.padding, + groups=conv.groups, + bias=True).requires_grad_(False).to(conv.weight.device) + + # Prepare filters + w_conv = conv.weight.clone().view(conv.out_channels, -1) + w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) + fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape)) + + # Prepare spatial bias + b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias + b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) + fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) + + return fusedconv + +class Classify(nn.Module): + # Classification head, i.e. x(b,c1,20,20) to x(b,c2) + def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1) + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1) + self.flat = nn.Flatten() + + def forward(self, x): + z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list + return self.flat(self.conv(z)) # flatten to x(b,c2) +class Model(nn.Module): + # YOLOv5 model + def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes + super().__init__() + if isinstance(cfg, dict): + self.yaml = cfg # model dict + else: # is *.yaml + import yaml # for torch hub + self.yaml_file = Path(cfg).name + with open(cfg, encoding='ascii', errors='ignore') as f: + self.yaml = yaml.safe_load(f) # model dict + + # Define model + ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels + if nc and nc != self.yaml['nc']: + + self.yaml['nc'] = nc # override yaml value + if anchors: + + self.yaml['anchors'] = round(anchors) # override yaml value + self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist + self.names = [str(i) for i in range(self.yaml['nc'])] # default names + self.inplace = self.yaml.get('inplace', True) + + # Build strides, anchors + m = self.model[-1] # Detect() + if isinstance(m, Detect): + s = 256 # 2x min stride + m.inplace = self.inplace + m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward + check_anchor_order(m) # must be in pixel-space (not grid-space) + m.anchors /= m.stride.view(-1, 1, 1) + self.stride = m.stride + self._initialize_biases() # only run once + + # Init weights, biases + initialize_weights(self) + self.info() + + + def forward(self, x, augment=False, profile=False, visualize=False): + if augment: + return self._forward_augment(x) # augmented inference, None + return self._forward_once(x, profile, visualize) # single-scale inference, train + + def _forward_augment(self, x): + img_size = x.shape[-2:] # height, width + s = [1, 0.83, 0.67] # scales + f = [None, 3, None] # flips (2-ud, 3-lr) + y = [] # outputs + for si, fi in zip(s, f): + xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) + yi = self._forward_once(xi)[0] # forward + # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save + yi = self._descale_pred(yi, fi, si, img_size) + y.append(yi) + y = self._clip_augmented(y) # clip augmented tails + return torch.cat(y, 1), None # augmented inference, train + + def _forward_once(self, x, profile=False, visualize=False): + y, dt = [], [] # outputs + for m in self.model: + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + if profile: + self._profile_one_layer(m, x, dt) + x = m(x) # run + y.append(x if m.i in self.save else None) # save output + if visualize: + feature_visualization(x, m.type, m.i, save_dir=visualize) + return x + + def _descale_pred(self, p, flips, scale, img_size): + # de-scale predictions following augmented inference (inverse operation) + if self.inplace: + p[..., :4] /= scale # de-scale + if flips == 2: + p[..., 1] = img_size[0] - p[..., 1] # de-flip ud + elif flips == 3: + p[..., 0] = img_size[1] - p[..., 0] # de-flip lr + else: + x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale + if flips == 2: + y = img_size[0] - y # de-flip ud + elif flips == 3: + x = img_size[1] - x # de-flip lr + p = torch.cat((x, y, wh, p[..., 4:]), -1) + return p + + def _clip_augmented(self, y): + # Clip YOLOv5 augmented inference tails + nl = self.model[-1].nl # number of detection layers (P3-P5) + g = sum(4 ** x for x in range(nl)) # grid points + e = 1 # exclude layer count + i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices + y[0] = y[0][:, :-i] # large + i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices + y[-1] = y[-1][:, i:] # small + return y + + def _profile_one_layer(self, m, x, dt): + c = isinstance(m, Detect) # is final layer, copy input as inplace fix + o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs + t = time_sync() + for _ in range(10): + m(x.copy() if c else x) + dt.append((time_sync() - t) * 100) + if m == self.model[0]: + pass + pass + if c: + pass + + def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency + # https://arxiv.org/abs/1708.02002 section 3.3 + # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. + m = self.model[-1] # Detect() module + for mi, s in zip(m.m, m.stride): # from + b = mi.bias.view(m.na, -1).detach() # conv.bias(255) to (3,85) + b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) + b[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls + mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) + + def _print_biases(self): + m = self.model[-1] # Detect() module + for mi in m.m: # from + b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) + + + # def _print_weights(self): + # for m in self.model.modules(): + # if type(m) is Bottleneck: + # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights + + def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers + + for m in self.model.modules(): + if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'): + m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv + delattr(m, 'bn') # remove batchnorm + m.forward = m.forward_fuse # update forward + self.info() + return self + + def info(self, verbose=False, img_size=640): # print model information + pass + #model_info(self, verbose, img_size) + + def _apply(self, fn): + # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers + self = super()._apply(fn) + m = self.model[-1] # Detect() + if isinstance(m, Detect): + m.stride = fn(m.stride) + m.grid = list(map(fn, m.grid)) + if isinstance(m.anchor_grid, list): + m.anchor_grid = list(map(fn, m.anchor_grid)) + return self +def make_divisible(x, divisor): + # Returns nearest x divisible by divisor + if isinstance(divisor, torch.Tensor): + divisor = int(divisor.max()) # to int + return math.ceil(x / divisor) * divisor + +def parse_model(d, ch): # model_dict, input_channels(3) + #LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") + anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] + na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors + no = na * (nc + 5) # number of outputs = anchors * (classes + 5) + + layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out + for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args + m = eval(m) if isinstance(m, str) else m # eval strings + for j, a in enumerate(args): + try: + args[j] = eval(a) if isinstance(a, str) else a # eval strings + except NameError: + pass + + n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain + if m in (Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, + BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x): + c1, c2 = ch[f], args[0] + if c2 != no: # if not output + c2 = make_divisible(c2 * gw, 8) + + args = [c1, c2, *args[1:]] + if m in [BottleneckCSP, C3, C3TR, C3Ghost, C3x]: + args.insert(2, n) # number of repeats + n = 1 + elif m is nn.BatchNorm2d: + args = [ch[f]] + elif m is Concat: + c2 = sum(ch[x] for x in f) + elif m is Detect: + args.append([ch[x] for x in f]) + if isinstance(args[1], int): # number of anchors + args[1] = [list(range(args[1] * 2))] * len(f) + elif m is Contract: + c2 = ch[f] * args[0] ** 2 + elif m is Expand: + c2 = ch[f] // args[0] ** 2 + else: + c2 = ch[f] + + m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module + t = str(m)[8:-2].replace('__main__.', '') # module type + np = sum(x.numel() for x in m_.parameters()) # number params + m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params + #LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print + save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist + layers.append(m_) + if i == 0: + ch = [] + ch.append(c2) + return nn.Sequential(*layers), sorted(save) +class Ensemble(nn.ModuleList): + # Ensemble of models + def __init__(self): + super().__init__() + + def forward(self, x, augment=False, profile=False, visualize=False): + y = [module(x, augment, profile, visualize)[0] for module in self] + # y = torch.stack(y).max(0)[0] # max ensemble + # y = torch.stack(y).mean(0) # mean ensemble + y = torch.cat(y, 1) # nms ensemble + return y, None # inference, train output +def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''): + # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes + + + file = Path(file) + assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}" + try: # url1 + #LOGGER.info(f'Downloading {url} to {file}...') + torch.hub.download_url_to_file(url, str(file), progress=True) + assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check + except Exception as e: # url2 + file.unlink(missing_ok=True) # remove partial downloads + #LOGGER.info(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...') + os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail + finally: + if not file.exists() or file.stat().st_size < min_bytes: # check + file.unlink(missing_ok=True) # remove partial downloads + #LOGGER.info(f"ERROR: {assert_msg}\n{error_msg}") + pass + #LOGGER.info('') +def attempt_download(file, repo='ultralytics/yolov5', release='v6.1'): + # Attempt file download from GitHub release assets if not found locally. release = 'latest', 'v6.1', etc. + + def github_assets(repository, version='latest'): + # Return GitHub repo tag (i.e. 'v6.1') and assets (i.e. ['yolov5s.pt', 'yolov5m.pt', ...]) + if version != 'latest': + version = f'tags/{version}' # i.e. tags/v6.1 + response = requests.get(f'https://api.github.com/repos/{repository}/releases/{version}').json() # github api + return response['tag_name'], [x['name'] for x in response['assets']] # tag, assets + + file = Path(str(file).strip().replace("'", '')) + if not file.exists(): + # URL specified + name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc. + if str(file).startswith(('http:/', 'https:/')): # download + url = str(file).replace(':/', '://') # Pathlib turns :// -> :/ + file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth... + if Path(file).is_file(): + pass + #LOGGER.info(f'Found {url} locally at {file}') # file already exists + else: + safe_download(file=file, url=url, min_bytes=1E5) + return file + + # GitHub assets + assets = [ + 'yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov5n6.pt', 'yolov5s6.pt', + 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] + try: + tag, assets = github_assets(repo, release) + except Exception: + try: + tag, assets = github_assets(repo) # latest release + except Exception: + try: + tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] + except Exception: + tag = release + + file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required) + if name in assets: + url3 = 'https://drive.google.com/drive/folders/1EFQTEUeXWSFww0luse2jB9M1QNZQGwNl' # backup gdrive mirror + safe_download( + file, + url=f'https://github.com/{repo}/releases/download/{tag}/{name}', + url2=f'https://storage.googleapis.com/{repo}/{tag}/{name}', # backup url (optional) + min_bytes=1E5, + error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/{tag} or {url3}') + + return str(file) +def attempt_load(weights, device=None, inplace=True, fuse=True): + # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a + + + model = Ensemble() + for w in weights if isinstance(weights, list) else [weights]: + ckpt = torch.load(attempt_download(w), map_location='cpu') # load + ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model + model.append(ckpt.fuse().eval() if fuse else ckpt.eval()) # fused or un-fused model in eval mode + + # Compatibility updates + for m in model.modules(): + t = type(m) + if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model): + m.inplace = inplace # torch 1.7.0 compatibility + if t is Detect and not isinstance(m.anchor_grid, list): + delattr(m, 'anchor_grid') + setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl) + elif t is Conv: + m._non_persistent_buffers_set = set() # torch 1.6.0 compatibility + elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'): + m.recompute_scale_factor = None # torch 1.11.0 compatibility + + if len(model) == 1: + return model[-1] # return model + print(f'Ensemble created with {weights}\n') + for k in 'names', 'nc', 'yaml': + setattr(model, k, getattr(model[0], k)) + model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride + assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}' + return model # return ensemble + + +###### + + +def identify_path_type(path): + # 检查路径是否存在 + if path =="always": + return "always" + + if not os.path.exists(path): + return 0 + + # 检查是否为文件夹 + if os.path.isdir(path): + items = os.listdir(path) + for item in items: + if os.path.isdir(os.path.join(path, item)): + return 4 # Found a subfolder + return 1 + if os.path.splitext(path)[1].lower() == '.txt': + return 6 + + + # 检查是否为文件 + if os.path.isfile(path): + # 获取文件的 MIME 类型 + mime_type, _ = mimetypes.guess_type(path) + if mime_type: + # 根据 MIME 类型判断是否为图像或视频 + if mime_type.startswith('image'): + return 2 + elif mime_type.startswith('video'): + return 3 + return "文件" + + return "未知类型" + +class Fine_grained_T: + def __init__(self, onnx_model): + """ + Initialization. + + Args: + onnx_model (str): Path to the ONNX model. + """ + if 'CUDAExecutionProvider' in ort.get_available_providers(): + print("CUDA is available. ONNXRuntime will use GPU.") + self.session = ort.InferenceSession( + onnx_model, + providers=["CUDAExecutionProvider", "CPUExecutionProvider"] + if ort.get_device() == "GPU" + else ["CPUExecutionProvider"], + ) + else: + print("CUDA is not available. ONNXRuntime will use CPU.") + print(ort.get_device()) + print("Fine is ready") + + + + def inference(self, img, imagelist, labellist, scorelist, fine_thresh1,infsize): + with torch.no_grad(): + for i, box in enumerate(imagelist): + if box[0] < 0: + box[0] = 0 + if box[1] < 0: + box[1] = 0 + if box[2] < 0: + box[2] = 0 + if box[3] < 0: + box[3] = 0 + X_left = int(box[1])-10 + if X_left < 0: + X_left = 0 + X_right = int(box[3])+10 + if X_right>2159: + X_right = 2159 + + y_up = int(box[0])-10 + if y_up <0 : + y_up = 0 + + y_down = int(box[2])+10 + if y_down>3839: + y_down =3839 + image = img.copy()[X_left:X_right, y_up:y_down, :] + image = Image.fromarray(image) + #image.save("/data5/Hatcher/data/count/testresult/11111.jpg") + #if gp.DebugPrint_flag: + #print(box) + #print(Img) + #if (int(box[3])-int(box[1])>gp.fine_thresh) and (int(box[2])-int(box[0])>gp.fine_thresh): + if ((int(box[3]) - int(box[1])) * (int(box[2]) - int(box[0]))) > fine_thresh1 : + image = image.resize((infsize, infsize)) # 假设模型需要 224x224 的输入 + image = np.array(image).astype('float32') + image = (np.transpose(image, (2, 0, 1))) # 改变通道顺序 + image = np.expand_dims(image, axis=0) + inputs = {self.session.get_inputs()[0].name: image} + outputs = self.session.run(None, inputs) + fineclass = np.argmax(outputs[0]) + labellist[i] = fineclass + else: + pass + + return imagelist, labellist, scorelist + def inferenceone(self, imagepath): + image = Image.open(imagepath) + image = image.resize((224, 224)) # 假设模型需要 224x224 的输入 + image = np.array(image).astype('float32') + image = (np.transpose(image, (2, 0, 1))) # 改变通道顺序 + image = np.expand_dims(image, axis=0) + inputs = {self.session.get_inputs()[0].name: image} + outputs = self.session.run(None, inputs) + fineclass = np.argmax(outputs[0]) + #print(fineclass) + return(fineclass) + #print(fineclass) +class Detection: + def __init__(self,device,DetWeight,ChineseName): + self.device = device + self.img_size = 2176 + self.conf_thres = 0.6 + self.iou_thres = 0.4 + self.stride = 1 + self.weights = DetWeight + self.fine_thresh = 0.6 + self.fineinfsize = 224 + model = attempt_load(self.weights, device=self.device) + model.to(self.device).eval() + + model.half() + self.model = model + self.names = model.module.names if hasattr( + model, 'module') else model.names + self.ChineseName = ChineseName + print("Detection is in ",self.device) + print("Detection is ready") + # while(1): + # pass + + def preprocess(self, img): + + img0 = img.copy() + #img = cv2.resize(img, (2000, 1000)) + img = letterbox(img, new_shape=self.img_size, stride=self.stride)[0] + img = img[:, :, ::-1].transpose(2, 0, 1) + img = np.ascontiguousarray(img) + img = torch.from_numpy(img).to(self.device) + img = img.half() # ¡ã????¨¨ + img /= 255.0 # ¨ª???1¨¦¨°??¡¥ + if img.ndimension() == 3: + img = img.unsqueeze(0) + + return img0, img + def AIlabelFine(self, imagename, fine_grained,saveroot,islabel):#imagename 是文件的完整名字 + with torch.no_grad(): + # t2 = time.time() + + try: + t1 = time.time() + image = cv2.imread(imagename) + t2 = time.time() + if DebugPrint_flag: + print("加载图片的时间是 ",(t2-t1)*1000) + except: + #os.remove(imagename) + print(imagename,"is broken") + return + if not type(image): + print("skip") + return + image_or = image + + '''可视化注释 + img_show = image_or.copy() + if (isinstance(img_show, np.ndarray)): + img_show = Image.fromarray(cv2.cvtColor(img_show, cv2.COLOR_BGR2RGB)) + draw = ImageDraw.Draw(img_show) + ''' + try: + t1 = time.time() + img_detect = cv2.resize(image, (3840, 2160)) + t2 = time.time() + if DebugPrint_flag: + print("resize图片的时间是 ",(t2-t1)*1000) + except: + print(imagename+" is broken") + return + # t1 = time.time() + t1 = time.time() + image_scale, image = self.preprocess(img_detect) + t2 = time.time() + if DebugPrint_flag: + print("预处理的时间是 ",(t2-t1)*1000) + # t2 = time.time() + # if DebugPrint_flag: + # tqdm.write("Detection data deal is ",(t2-t1)*1000) + t1 = time.time() + pred = self.model(image, augment=False)[0] + pred = pred.float() + pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) + # t3 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection inference is ",(t3-t2)*1000) + boxes = [] + scores = [] + labels = [] + for det in pred: + if det is not None and len(det): + det[:, :4] = scale_coords( + image.shape[2:], det[:, :4], image_scale.shape).round() + boxes.append(det[:, :4]) + scores.append(det[:, 4]) + labels.append((det[:, -1])) + boxes = boxes[0] + scores = scores[0] + labels = labels[0] + t2 = time.time() + if DebugPrint_flag: + print("一次目标检测的时间是 ",(t2-t1)*1000) + # t5 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection get result is ", (t5 - t3) * 1000) + t1 = time.time() + if len(labels) > 0: + ratio_x = (image_or.shape[1] / 3840.0) + ratio_y = (image_or.shape[0] / 2160.0) + for i in range(len(boxes)): + boxes[i][0] = boxes[i][0] * ratio_x + boxes[i][2] = boxes[i][2] * ratio_x + boxes[i][1] = boxes[i][1] * ratio_y + boxes[i][3] = boxes[i][3] * ratio_y + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][3] < 0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 0 + boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores, self.fine_thresh,self.fineinfsize) + t2 = time.time() + if DebugPrint_flag: + print("细粒度识别的时间是 ",(t2-t1)*1000) + # t4 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection final is ", (t4 - t3) * 1000) + '''不进行可视化 + for i in range(len(scores)): + xyxy = boxes_fine[i] + conf = scores_fine[i] + cls = labels_fine[i] + print(int(cls)) + label = str(self.ChineseName[int(cls)]) + #label = f'{int(cls)} {conf:.2f}' + palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1) + colors = tuple(int((p * (cls ** 2 - cls + 1)) % 255) for p in palette) + draw = plot_one_box(xyxy, draw, image_or.shape[1], image_or.shape[0], label=label, color=colors, + line_thickness=int(3 * gp.radioShowtext)) + savepath = os.path.join(saveroot,os.path.basename(imagename)) + img_show = cv2.cvtColor(np.asarray(img_show), cv2.COLOR_RGB2BGR) + cv2.imwrite(savepath,img_show) + ''' + if islabel: + # for i in range(len(scores)): + + # cls = labels_fine[i] + # print(int(cls)) + # labels_fine[i] = str(self.ChineseName[int(cls)]) + #print() + t1 = time.time() + savepath = os.path.join(saveroot,os.path.basename(imagename)) + xml_outputpath = savepath.replace(".jpg", ".xml").replace(".JPG", ".xml") + make_xml(imagename, image_or.shape[0], image_or.shape[1], boxes_fine, labels_fine, scores_fine, xml_outputpath) + t2 = time.time() + if DebugPrint_flag: + print("结果存储的时间是 ",(t2-t1)*1000) + + else: + pass + '''不保存数据 + savepath = os.path.join(saveroot,os.path.basename(imagename)) + shutil.copy(imagename, savepath) + ''' +def get_all_image_paths(folder_path): + + # Define common image file extensions + image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.tif') + + # Initialize an empty list to store the image paths + image_paths = [] + + # Walk through the folder and its subfolders + for root, dirs, files in tqdm(os.walk(folder_path)): + for file in files: + if file.lower().endswith(image_extensions): + # Get the absolute path of the image file + image_path = os.path.join(root, file) + image_paths.append(image_path) + + return image_paths +def process_image(filepath, Fine, saveroot, islabel, detection): + detection.AIlabelFine(filepath, Fine, saveroot, islabel) +if __name__ == '__main__': + # Fine = Fine_grained_T("/data5/Train_Models/mmcls_onnx/CMB_YNDC_20240115_29/convnext-base_4xb32_cmb200/end2end.onnx") + # result = Fine.inferenceone("/data5/CAS_Project/CAS_ProjectBird/CMB/CMB_YNDC/CMB_YNDC_20231129_30/OrginalData/Bird/Bird___BJCH014_000447.jpg") + """ + 测试 + -dw /data5/Train_Models/Detection_weigth/3090/202306/20230619-131704-pixel5000-BJNHZ_Person/weights/best.pt + -cw /data5/Train_Models/mmcls_onnx/CMB_BJNHZ_20230910_144/convnext-base_4xb32_cmb200/end2end.onnx + -c /data5/CAS_Project/CAS_ProjectBird/CMB/CMB_BJNHZ/CMB_BJNHZ_20230910_144/birdListbirdCNlist.txt + -m "ai" + -s "/data5/Hatcher/data/detection/test1" + -o "/data5/Hatcher/data/detection/testresult" + """ + + + + + + Det_weights,Fine_weights,Fine_class,infmode,sourcepath,saveroot = parse_args() + if not os.path.exists(saveroot): + os.makedirs(saveroot) + # with open(Fine_class, 'r', encoding='utf-8') as file: + # bird_list = file.readlines() + with open(Fine_class, 'r', encoding='utf-8') as file: + content = file.read().strip() # 读取文件内容并去除首尾空格 + bird_list = content.split(';') # 使用分号分割字符串 + + #bird_list = [bird.strip() for bird in bird_list] + print(bird_list) + print(saveroot) + devices = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') + detection = Detection(devices,Det_weights,bird_list) + Fine = Fine_grained_T(Fine_weights) + if not os.path.exists(saveroot): + os.makedirs(saveroot) + fileType = identify_path_type(sourcepath) + if infmode == "ai": + islabel = 1 + if (fileType == 2): + print("开始处理单张图像数据") + #缺一个处理单个的函数 + detection.AIlabelFine(sourcepath,Fine,saveroot,islabel) + if (fileType == 1): #说明是文件夹 + print("开始处理文件夹批量数据") + fileList = os.listdir(sourcepath) + for filepath in tqdm(fileList): + sourcePath = os.path.join(sourcepath,filepath) + #缺一个处理单个的函数 + #print(sourcePath) + detection.AIlabelFine(sourcePath,Fine,saveroot,islabel) + if (fileType == 4): #说明是文件夹 + print("开始多线程处理复杂文件夹批量数据") + fileList = get_all_image_paths(sourcepath) + #print(fileList) + for filepath in tqdm(fileList): + #sourcePath = os.path.join(sourcepath,filepath) + #缺一个处理单个的函数 + #print(sourcePath) + with ThreadPoolExecutor(max_workers=12) as executor: + futures = {executor.submit(process_image, filepath, Fine, saveroot, islabel, detection): filepath for filepath in fileList} + + for future in tqdm(as_completed(futures), total=len(futures)): + try: + future.result() + except Exception as exc: + print(f'File {futures[future]} generated an exception: {exc}') + # t1 = time.time() + # detection.AIlabelFine(filepath,Fine,saveroot,islabel) + # t2 = time.time() + # if DebugPrint_flag: + # print("推理一张图片的时间是 ",(t2-t1)*1000) + if (fileType == "always"): + print("开始循环处理输入数据") + while(1): + sourcepath = input("请输入测试文件路径: ") + if sourcepath == "q": + break + detection.AIlabelFine(sourcepath,Fine,saveroot,islabel) + #缺一个处理单个的函数 \ No newline at end of file diff --git a/PPdet_VOC.py b/PPdet_VOC.py new file mode 100755 index 0000000..e6ac28f --- /dev/null +++ b/PPdet_VOC.py @@ -0,0 +1,21 @@ +import os +in_path = "/data/DataManagement/Project/001_cuihu/CAS_CuihuBird/CDB_Cuihubird/ImageSets/Main/test.txt" +out_path = "/data/DataManagement/Project/001_cuihu/CAS_CuihuBird/CDB_Cuihubird/ImageSets/Main/test1.txt" +def change(in_path,out_path): + new = [] + f = open(in_path,'r') + lines = f.readlines() + for line in lines: + line = line.strip('\n') + line = "./images/{}.jpg".format(line)+" "+"./Annotations/{}.xml".format(line)+"\n" + new.append(line) + # while(line): + # line = f.readline().replace("\n","") + # line = "./images/{}".format(line) + " " + "./Annotations/{}".format(line) +"\n" + # print(line) + # new.append(line) + handle = open(out_path, 'a') + handle.writelines(new) + +if __name__ == '__main__': + change(in_path,out_path) \ No newline at end of file diff --git a/PanoramicScanSplicing.py b/PanoramicScanSplicing.py new file mode 100755 index 0000000..0eabc11 --- /dev/null +++ b/PanoramicScanSplicing.py @@ -0,0 +1,26 @@ +import os +import tqdm +import cv2 +from PIL import Image +result_path = "E:/2021.10.15-wettrain/results/" +GT_path = "E:/2021.10.15-wettrain/result_GT/" +image_path ="E:/2021.10.15-wettrain/images/" +image = [] +for j in range(14): + img = [] + for i in range(60): + img.append(Image.open("/data/DataManagement/Project/001_cuihu/CAS_CuihuBird/CDB_Cuihubird/images/train/0010700285.jpg").resize((1024,768))) + image.append(img) +def long_pic_paste(image): + image_result = Image.new(image[0][0].mode, ( 1024 * 60,14 * 768), 0xffffff) + for j in range(14): + for i in range(60): + print(j," ",i) + image_result.paste(image[j][i], (i*1024, j*768)) + #image_result.resize((65500,8591)) + image_result.save("./result.jpg") + + + +if __name__ == '__main__': + long_pic_paste(image) \ No newline at end of file diff --git a/System_I.py b/System_I.py index e0c2b63..c1b8f8b 100755 --- a/System_I.py +++ b/System_I.py @@ -4,56 +4,100 @@ import cv2 import json -import random +import random, timm from configs.configs import model_head - -import os,sys,shutil +from tqdm import tqdm +import os, sys, shutil import torch from torch import nn from PIL import Image, ImageDraw, ImageFont from vizer.draw import draw_boxes # from ssd.config import cfg # from ssd.data.datasets import VOCDataset -# import numpy as np # from ssd.data.transforms import build_transforms # from ssd.modeling.detector import build_detection_model # from ssd.utils.checkpoint import CheckPointer -# from fine.models.LoadModel import MainModel from fine.fineConfig import LoadConfig, load_data_transformers from torch.autograd import Variable -from creat_xml_fordetection import make_xml +from creat_xml_fordetection import make_xml import threading -from common import global_para as gp -import time,statistics +from common import global_para as gp +import time, statistics from numpy import random +from mmcls.apis import inference_model, init_model, show_result_pyplot root_path = os.getcwd() sys.path.insert(0,root_path+"/Y5") from Y5.models.experimental import attempt_load -from Y5.utils.datasets import letterbox -from Y5.utils.general import non_max_suppression, scale_coords -from Y5.utils.plots import plot_one_box -from network_multi import Multi_transform_image -from cv2AddChineseText import cv2AddChineseText +from Y5.utils.augmentations import letterbox +from Y5.utils.general import imshow, non_max_suppression, scale_coords +from Y5_old.utils.plots import plot_one_box,plot_one_box1 + +from cv2AddChineseText import cv2AddChineseText +from vgg_baye import vgg19 +from skimage.feature import peak_local_max +import matplotlib.pyplot as plt class Density: def __init__(self, device, root): - self.device = device - self.root = root - self.net = PKSNet().to(self.device) - self.pth = "../data_MPKFNet/test/1.pth" - # print("creat model is ", (t4 - t3) * 1000) - # self.checkpointer = CheckPointer(self.net) - # self.net.load_state_dict(self.checkpointer['net']) - # self.checkpointer.load(self.checkpointer['net']) - checkpoint = torch.load(self.pth) - self.net.load_state_dict(checkpoint['net']) - if gp.DebugPrint_flag: - print("load model weight ok") - - np.set_printoptions(threshold=np.inf) - - + self.device = device + self.weigth_path = gp.DensityWeight #权重路径 + self.display = 25 + self.imgW = 800 + self.imgH = 800 + self.net = vgg19().to(self.device) + params = sum(p.numel() for p in self.net.parameters() if p.requires_grad) + print(params / 1000000.0) + self.checkpoint = torch.load(self.weigth_path) + self.net.load_state_dict(self.checkpoint) + #print(self.net) + print("load model weight ok") + def Inf_sigle(self,img,show_flag): #show_flag 是否展示点信息 + self.net.eval() + # + img_or = img + img = cv2.resize(img, (self.imgW, self.imgH)) / 255.0 + img = np.transpose(img, [2, 0, 1]) + img = torch.from_numpy(img).type(torch.FloatTensor) + img = img.unsqueeze(0) + img = img.to(self.device) + targets_pred= self.net(img) + targets_pred_gao = targets_pred.clone() + targets_pred_gao[targets_pred_gao<1e-4] = 0 + targets_pred = targets_pred.squeeze(0).cpu().detach().numpy()[0] + targets_pred[targets_pred<1e-4] = 0 #积分 + tar_num = np.sum(targets_pred) + if tar_num < 10: + targets_pred[targets_pred<1e5] = 0 + tar_num = np.sum(targets_pred) + + if show_flag: + row_ro = img_or.shape[0]/self.imgH + colum_ro = img_or.shape[1]/self.imgW + #局部峰值提取 + coordinates_peak = peak_local_max(targets_pred_gao, min_distance=5,exclude_border = False) + rowPO = [] + columPO = [] + for coordinate in coordinates_peak: + rowPO.append(coordinate[1]*row_ro) + columPO.append(coordinate[0]*colum_ro) + + #img_or = np.transpose(img_or, [1, 2, 0]) + #targets_pred = targets_pred[0] + targets_pred = cv2.resize(targets_pred, (img_or.shape[1], img_or.shape[0])) + heatmap = targets_pred/np.max(targets_pred) + heatmap = np.uint8(heatmap*255) + + heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET) + + # for i in range(img_or.shape[1]): + # for j in range(img_or.shape[0]): + # if (heatmap[j,i,:] == np.array([128,0,0])).all(): + # heatmap[j,i,:] = [0,0,0] + #cv2.imwrite("/data3/DEMO/Images_result/{}.jpg".format(str(1)),img_or + heatmap*0.2) + result = img_or + heatmap*0.3 + return heatmap,tar_num + def inference(self,image,imagetime,index): rootpath = os.path.join(self.root, imagetime) @@ -62,15 +106,15 @@ class Density: if not os.path.exists(rootpath + "/" + "Density"+"/"): os.mkdir(rootpath + "/" + "Density"+"/") target_h, target_w = image.shape[0], image.shape[1] - t1 = time.time() + # t1 = time.time() image = cv2.resize(image, (1024, 768)) / 255.0 image = np.transpose(image, [2, 0, 1]) image = np.expand_dims(image, axis=0) image = torch.tensor(image) image = image.to(self.device) - t2 = time.time() - if gp.DebugPrint_flag: - print("Density data deal is ", (t2 - t1) * 1000) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("Density data deal is ", (t2 - t1) * 1000) # print("data dell is ", (t7 - t6) * 1000) @@ -78,24 +122,23 @@ class Density: targets_pred, posture_pred, spice_pred = self.net(image) else: targets_pred = self.net(image) - t3=time.time() - if gp.DebugPrint_flag: - print("Density inference is ", (t3 - t2) * 1000) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("Density inference is ", (t3 - t2) * 1000) targets_pred1 = targets_pred.cpu() num = targets_pred1.data.sum().numpy() targets_pred1 = targets_pred1.data.numpy() - t4=time.time() - if gp.DebugPrint_flag: - print("Density final is ", (t4 - t3) * 1000) - + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("Density final is ", (t4 - t3) * 1000) data_dict = {"sum": str(num), "density": (str(targets_pred1[0, 0, :, :]))} json_outputpath = (rootpath + "/" + "Density"+"/"+str(index).zfill(3)+".json") json_data = json.dumps(data_dict, ensure_ascii=True, indent=4) with open (json_outputpath,'w',encoding='utf-8') as f: f.write(str(json_data)) - t5=time.time() - if gp.DebugPrint_flag: - print("Density save is ", (t5 - t4) * 1000) + # t5=time.time() + # if gp.DebugPrint_flag: + # print("Density save is ", (t5 - t4) * 1000) def inference_init(self, image): image = cv2.resize(image, (1024, 768)) / 255.0 @@ -141,20 +184,20 @@ class Detection_S: os.mkdir(rootpath + "/" + "Detection" + "/") image_or = image height, width = image.shape[:2] - t1 = time.time() + # t1 = time.time() image = self.transforms(image)[0].unsqueeze(0) - t2 = time.time() - if gp.DebugPrint_flag: - print("Detection data deal is ",(t2-t1)*1000) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("Detection data deal is ",(t2-t1)*1000) result = self.net(image.to(self.device))[0] - t3 = time.time() - if gp.DebugPrint_flag: - print("Detection inference is ",(t3-t2)*1000) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("Detection inference is ",(t3-t2)*1000) result = result.to(torch.device("cpu")) result = result.resize((width, height)).numpy() - t5 = time.time() - if gp.DebugPrint_flag: - print("Detection get result is ", (t5 - t3) * 1000) + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Detection get result is ", (t5 - t3) * 1000) boxes, labels, scores = result['boxes'], result['labels'], result['scores'] indices_score = (scores > self.threshold) indices_label_left = labels <4 @@ -177,9 +220,9 @@ class Detection_S: for i in range(len(labels)): labels[i] = 99999 boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores) - t4 = time.time() - if gp.DebugPrint_flag: - print("Detection final is ", (t4 - t3) * 1000) + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("Detection final is ", (t4 - t3) * 1000) #numb = 2 #fine_grained.inference(image_or,boxes,labels,scores) # for box in boxes: @@ -190,23 +233,23 @@ class Detection_S: xml_outputpath = rootpath + "/" + "Detection"+"/" + index+".xml" make_xml(str(index),image_or.shape[0],image_or.shape[1],boxes_fine,labels_fine,scores_fine,xml_outputpath,class_names) #Image.fromarray(drawn_image).save(xml_outputpath.replace(".xml",".jpg")) - t5 = time.time() - if gp.DebugPrint_flag: - print("Detection save is ", (t5 - t4) * 1000) + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Detection save is ", (t5 - t4) * 1000) def inference_Red(self,image,ImagePath,fine_grained): with torch.no_grad(): class_names = VOCDataset.class_names image_or = image height, width = image.shape[:2] - t1 = time.time() + # t1 = time.time() image = self.transforms(image)[0].unsqueeze(0) - t2 = time.time() - if gp.DebugPrint_flag: - print("data deal is ",(t2-t1)*1000) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("data deal is ",(t2-t1)*1000) result = self.net(image.to(self.device))[0] - t3 = time.time() - if gp.DebugPrint_flag: - print("inference is ",(t3-t2)*1000) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("inference is ",(t3-t2)*1000) result = result.to(torch.device("cpu")) result = result.resize((width, height)).numpy() boxes, labels, scores = result['boxes'], result['labels'], result['scores'] @@ -232,9 +275,9 @@ class Detection_S: for i in range(len(labels)): labels[i] = 99999 boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores) - t4 = time.time() - if gp.DebugPrint_flag: - print("final is ", (t4 - t3) * 1000) + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("final is ", (t4 - t3) * 1000) #numb = 2 #fine_grained.inference(image_or,boxes,labels,scores) # for box in boxes: @@ -245,28 +288,28 @@ class Detection_S: xml_outputpath = ImagePath.replace("/ftp/", "/ftp_Result/").replace(".JPG", ".xml").replace(".jpg",".xml") make_xml(str(ImagePath),image_or.shape[0],image_or.shape[1],boxes_fine,labels_fine,scores_fine,xml_outputpath) #Image.fromarray(drawn_image).save(xml_outputpath.replace(".xml",".jpg")) - t5 = time.time() - if gp.DebugPrint_flag: - print("save is ", (t5 - t4) * 1000) + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("save is ", (t5 - t4) * 1000) - def check_object(self,image): + def check_object(self, image): flag = False with torch.no_grad(): height, width = image.shape[:2] img_temp = image - t1 = time.time() + # t1 = time.time() image = self.transforms(image)[0].unsqueeze(0) - t2 = time.time() - if gp.DebugPrint_flag: - print("check datadeal is ",(t2-t1)*1000) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("check datadeal is ",(t2-t1)*1000) result = self.net(image.to(self.device))[0] - t3 = time.time() - if gp.DebugPrint_flag: - print("check inference is ", (t3 - t2) * 1000) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("check inference is ", (t3 - t2) * 1000) result = result.to(torch.device("cpu")) - t4 = time.time() - if gp.DebugPrint_flag: - print("check result deal is ", (t4 - t3) * 1000) + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("check result deal is ", (t4 - t3) * 1000) result = result.resize((width, height)).numpy() boxes, labels, scores = result['boxes'], result['labels'], result['scores'] @@ -281,33 +324,34 @@ class Detection_S: scores=scores[indices] if 3 in labels: flag = True - if gp.DebugPrint_flag: - print("boxes = ",boxes) - print("check flag is ",flag) - t5 = time.time() - if gp.DebugPrint_flag: - print("check final is ", (t5 - t4) * 1000) - return flag,labels,boxes,scores + # if gp.DebugPrint_flag: + # print("boxes = ", boxes) + # print("check flag is ", flag) + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("check final is ", (t5 - t4) * 1000) + return flag, labels, boxes, scores class Detection_Y5: - def __init__(self,device,root,detect_thresh,DetWeight): + def __init__(self,device,root,detect_thresh): self.device = device self.root = root - self.img_size = 640 - self.conf_thres = detect_thresh - self.iou_thres = 0.4 + self.img_size = 2176 + self.conf_thres = 0.6#gp.detthresh #0.6 + self.iou_thres = detect_thresh #0.4 self.stride = 1 - self.weights = DetWeight + self.weights = gp.DetWeight # self.device = select_device(self.device) - model = attempt_load(self.weights, map_location=self.device) + model = attempt_load(self.weights, device=self.device) model.to(self.device).eval() model.half() self.model = model self.names = model.module.names if hasattr( model, 'module') else model.names + print("detection is ok") def preprocess(self, img): img0 = img.copy() - #img = cv2.resize(img, (1024, 768)) + #img = cv2.resize(img, (2000, 1000)) img = letterbox(img, new_shape=self.img_size, stride=self.stride)[0] img = img[:, :, ::-1].transpose(2, 0, 1) img = np.ascontiguousarray(img) @@ -320,20 +364,21 @@ class Detection_Y5: return img0, img def AIlabel(self,imagename): with torch.no_grad(): + tqdm.write(imagename + " is doing!") image = cv2.imread(imagename) image_or = image img_detect = cv2.resize(image, (1024, 768)) - t1 = time.time() + # t1 = time.time() image_scale,image = self.preprocess(img_detect) - t2 = time.time() - if gp.DebugPrint_flag: - print("Detection data deal is ",(t2-t1)*1000) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("Detection data deal is ",(t2-t1)*1000) pred = self.model(image, augment=False)[0] pred = pred.float() pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) - t3 = time.time() - if gp.DebugPrint_flag: - print("Detection inference is ",(t3-t2)*1000) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("Detection inference is ",(t3-t2)*1000) boxes = [] scores = [] labels = [] @@ -341,21 +386,18 @@ class Detection_Y5: if det is not None and len(det): det[:, :4] = scale_coords( image.shape[2:], det[:, :4], image_scale.shape).round() - boxes.append(det[:, :4]) scores.append(det[:, 4]) labels.append((det[:, -1])) boxes = boxes[0] scores = scores[0] labels = labels[0] - t5 = time.time() - if gp.DebugPrint_flag: - print("Detection get result is ", (t5 - t3) * 1000) + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Detection get result is ", (t5 - t3) * 1000) if len(labels) > 0: ratio_x = (image_or.shape[1] / 1024.0) ratio_y = (image_or.shape[0] / 768.0) - - for i in range(len(boxes)): boxes[i][0]=boxes[i][0] * ratio_x boxes[i][2]=boxes[i][2] * ratio_x @@ -371,16 +413,99 @@ class Detection_Y5: boxes[i][3] = 0 # for i in range(len(labels)): # labels[i] = "bird" - t4 = time.time() - if gp.DebugPrint_flag: - print("Detection final is ", (t4 - t3) * 1000) + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("Detection final is ", (t4 - t3) * 1000) xml_outputpath = imagename.replace("imagesAILabel","LabelXML").replace(".jpg",".xml") make_xml(imagename,image_or.shape[0],image_or.shape[1],boxes,labels,scores,xml_outputpath) shutil.copy(imagename, imagename.replace("imagesAILabel", "YesResult")) else: - shutil.copy(imagename,imagename.replace("imagesAILabel","NoResult")) - - def inference(self,image,imagetime,index,fine_grained): + shutil.copy(imagename, imagename.replace("imagesAILabel", "NoResult")) + def AIlabelFine(self, imagename, fine_grained): + with torch.no_grad(): + tqdm.write(imagename + " is doing!") + try: + image = cv2.imread(imagename) + except: + os.remove(imagename) + #print(imagename) + return + if not type(image): + print("skip") + return + image_or = image + try: + img_detect = cv2.resize(image, (3840, 2160)) + except: + shutil.copy(imagename, imagename.replace("imagesAILabel", "BrokenImage")) + return + # t1 = time.time() + image_scale, image = self.preprocess(img_detect) + # t2 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection data deal is ",(t2-t1)*1000) + pred = self.model(image, augment=False)[0] + pred = pred.float() + pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) + # t3 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection inference is ",(t3-t2)*1000) + boxes = [] + scores = [] + labels = [] + for det in pred: + if det is not None and len(det): + det[:, :4] = scale_coords( + image.shape[2:], det[:, :4], image_scale.shape).round() + boxes.append(det[:, :4]) + scores.append(det[:, 4]) + labels.append((det[:, -1])) + boxes = boxes[0] + scores = scores[0] + labels = labels[0] + # t5 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection get result is ", (t5 - t3) * 1000) + if len(labels) > 0: + ratio_x = (image_or.shape[1] / 3840.0) + ratio_y = (image_or.shape[0] / 2160.0) + for i in range(len(boxes)): + boxes[i][0] = boxes[i][0] * ratio_x + boxes[i][2] = boxes[i][2] * ratio_x + boxes[i][1] = boxes[i][1] * ratio_y + boxes[i][3] = boxes[i][3] * ratio_y + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][3] < 0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 0 + boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores, 8) + # t4 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection final is ", (t4 - t3) * 1000) + for i in range(len(scores)): + xyxy = boxes_fine[i] + conf = scores_fine[i] + cls = labels_fine[i] + print(int(cls)) + label = str(gp.BHG_chineseName[int(cls)]) + #label = f'{int(cls)} {conf:.2f}' + palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1) + colors = [int((p * (cls ** 2 - cls + 1)) % 255) for p in palette] + image_or = plot_one_box1(xyxy, image_or, label=label, color=colors, line_thickness=2) + show_outputpath = imagename.replace("imagesAILabel", "result") + cv2.imwrite(show_outputpath,image_or) + xml_outputpath = imagename.replace("imagesAILabel", "Annotations").replace(".jpg", ".xml") + make_xml(imagename, image_or.shape[0], image_or.shape[1], boxes_fine, labels_fine, scores_fine, xml_outputpath) + shutil.copy(imagename, imagename.replace("imagesAILabel", "JPEGImages")) + else: + shutil.copy(imagename, imagename.replace("imagesAILabel", "NoResult")) + def inference(self, image, imagetime, index, fine_grained): with torch.no_grad(): rootpath = os.path.join(self.root, imagetime) if not os.path.exists(rootpath): @@ -389,17 +514,17 @@ class Detection_Y5: os.mkdir(rootpath + "/" + "Detection" + "/") image_or = image img_detect = cv2.resize(image, (1024, 768)) - t1 = time.time() - image_scale,image = self.preprocess(img_detect) - t2 = time.time() - if gp.DebugPrint_flag: - print("Detection data deal is ",(t2-t1)*1000) + # t1 = time.time() + image_scale, image = self.preprocess(img_detect) + # t2 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection data deal is ",(t2-t1)*1000) pred = self.model(image, augment=False)[0] pred = pred.float() pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) - t3 = time.time() - if gp.DebugPrint_flag: - print("Detection inference is ",(t3-t2)*1000) + # t3 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection inference is ",(t3-t2)*1000) boxes = [] scores = [] labels = [] @@ -407,56 +532,49 @@ class Detection_Y5: if det is not None and len(det): det[:, :4] = scale_coords( image.shape[2:], det[:, :4], image_scale.shape).round() - boxes.append(det[:, :4]) scores.append(det[:, 4]) labels.append((det[:, -1])) boxes = boxes[0] scores = scores[0] labels = labels[0] - t5 = time.time() - if gp.DebugPrint_flag: - print("Detection get result is ", (t5 - t3) * 1000) - + # t5 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("Detection get result is ", (t5 - t3) * 1000) if len(labels) > 0: indices_label_left = labels < 10 indices_label_right = labels < 10 indices = [] for i in range(len(indices_label_left)): indices.append(indices_label_left[i] and indices_label_right[i]) - boxes = boxes[indices] labels = labels[indices] scores = scores[indices] # ÒòΪĪÃûÆæÃî¶àÁËÒ»¸ölistά¶È£¬ËùÒÔ¼ÓÁËÕâ¸ö0 if len(labels) > 0: - - boxes = boxes[0] labels = labels[0] scores = scores[0] ratio_x = (3840.0 / 1024.0) ratio_y = (2160.0 / 768.0) - - for i in range(len(boxes)): - boxes[i][0]=boxes[i][0] * ratio_x - boxes[i][2]=boxes[i][2] * ratio_x + boxes[i][0] = boxes[i][0] * ratio_x + boxes[i][2] = boxes[i][2] * ratio_x boxes[i][1] = boxes[i][1] * ratio_y boxes[i][3] = boxes[i][3] * ratio_y - if boxes[i][0]<0: + if boxes[i][0] < 0: boxes[i][0] = 0 - if boxes[i][1]<0: + if boxes[i][1] < 0: boxes[i][1] = 0 - if boxes[i][2]<0: + if boxes[i][2] < 0: boxes[i][2] = 0 - if boxes[i][3]<0: + if boxes[i][3] < 0: boxes[i][3] = 0 for i in range(len(labels)): labels[i] = 99999 boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores) - t4 = time.time() - if gp.DebugPrint_flag: - print("Detection final is ", (t4 - t3) * 1000) + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("Detection final is ", (t4 - t3) * 1000) else: boxes_fine, labels_fine, scores_fine = [],[],[] if gp.DebugPrint_flag: @@ -469,67 +587,135 @@ class Detection_Y5: # numb+=1 #drawn_image = draw_boxes(image_or, boxes_fine, labels_fine, scores_fine).astype(np.uint8) #labels_fine = labels_fine.numpy() - t6 = time.time() + # t6 = time.time() xml_outputpath = rootpath + "/" + "Detection"+"/" + index+".xml" make_xml(str(index),image_or.shape[0],image_or.shape[1],boxes_fine,labels_fine,scores_fine,xml_outputpath) #Image.fromarray(drawn_image).save(xml_outputpath.replace(".xml",".jpg")) - t5 = time.time() - if gp.DebugPrint_flag: - print("Detection save is ", (t5 - t6) * 1000) - def inference_Red(self,image,ImagePath,fine_grained): + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Detection save is ", (t5 - t6) * 1000) + def inference_scan(self, image,fine_grained):#用于对滇池采集的数据进行手动扫图统计 with torch.no_grad(): image_or = image - height, width = image.shape[:2] - img_detect = cv2.resize(image, (1024, 768)) - t1 = time.time() + img_show = image.copy() + if (isinstance(img_show, np.ndarray)): + img_show = Image.fromarray(cv2.cvtColor(img_show, cv2.COLOR_BGR2RGB)) + draw = ImageDraw.Draw(img_show) + img_detect = image image_scale, image = self.preprocess(img_detect) - t2 = time.time() - if gp.DebugPrint_flag: - print("Detection data deal is ", (t2 - t1) * 1000) pred = self.model(image, augment=False)[0] pred = pred.float() pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) - t3 = time.time() - if gp.DebugPrint_flag: - print("Detection inference is ", (t3 - t2) * 1000) boxes = [] scores = [] labels = [] for det in pred: - if det is not None and len(det): det[:, :4] = scale_coords( image.shape[2:], det[:, :4], image_scale.shape).round() - boxes.append(det[:, :4]) scores.append(det[:, 4]) labels.append((det[:, -1])) boxes = boxes[0] scores = scores[0] labels = labels[0] - t5 = time.time() - if gp.DebugPrint_flag: - print("Detection get result is ", (t5 - t3) * 1000) - print(labels) + if len(labels) > 0: + ratio_x = 1#(image_or.shape[0] / 2176.0) + ratio_y = 1#(image_or.shape[0] / 2176.0) + for i in range(len(boxes)): + boxes[i][0] = boxes[i][0] * ratio_x + boxes[i][2] = boxes[i][2] * ratio_x + boxes[i][1] = boxes[i][1] * ratio_y + boxes[i][3] = boxes[i][3] * ratio_y + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][3] < 0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 0 + boxes_fine, labels_fine, scores_fine = fine_grained.inference_scan(image_or, boxes, labels, scores,8) + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("Detection final is ", (t4 - t3) * 1000) + else: + boxes_fine, labels_fine, scores_fine = [],[],[] + if gp.DebugPrint_flag: + print("Detection is nothong") + for i in range(len(boxes_fine)): + xyxy = boxes_fine[i][:4] + cls = labels_fine[i] + index = None + if cls == 0 or (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < gp.fine_thresh2): + if cls == 0 and ((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < gp.fine_thresh2 : + print("cls==0!!! and too small!!!") + elif cls == 0: + print("cls==0!!!") + elif ((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < gp.fine_thresh2: + print("too small!!!") + # if cls == gp.birdIndex or (torch.sub(torch.mul(torch.sub(xyxy[3], xyxy[1]), torch.sub(xyxy[2], xyxy[0])),gp.fine_thresh2) < 0): + label = None + else: + label = gp.BHG_chineseName[int(cls)] + # label = f'{int(cls)} {conf:.2f}' + palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1) + colors = tuple(int((p * (cls ** 2 - cls + 1)) % 255) for p in palette) + draw = plot_one_box(xyxy, draw, image_or.shape[1], image_or.shape[0], label=label, Index=index, color=colors, + line_thickness=int(3 * gp.radioShowtext)) + img_show = cv2.cvtColor(np.asarray(img_show), cv2.COLOR_RGB2BGR) + return img_show,boxes_fine, labels_fine + + def inference_Red(self,image,ImagePath,fine_grained): + with torch.no_grad(): + image_or = image + height, width = image.shape[:2] + img_detect = cv2.resize(image, (1024, 768)) + # t1 = time.time() + image_scale, image = self.preprocess(img_detect) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("Detection data deal is ", (t2 - t1) * 1000) + pred = self.model(image, augment=False)[0] + pred = pred.float() + pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("Detection inference is ", (t3 - t2) * 1000) + boxes = [] + scores = [] + labels = [] + for det in pred: + if det is not None and len(det): + det[:, :4] = scale_coords( + image.shape[2:], det[:, :4], image_scale.shape).round() + boxes.append(det[:, :4]) + scores.append(det[:, 4]) + labels.append((det[:, -1])) + boxes = boxes[0] + scores = scores[0] + labels = labels[0] + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Detection get result is ", (t5 - t3) * 1000) + # print(labels) if len(labels) > 0 : indices_label_left = labels < 1 indices_label_right = labels < 1 indices = [] for i in range(len(indices_label_left)): indices.append(indices_label_left[i] and indices_label_right[i]) - boxes = boxes[indices] labels = labels[indices] scores = scores[indices] # ÒòΪĪÃûÆæÃî¶àÁËÒ»¸ölistά¶È£¬ËùÒÔ¼ÓÁËÕâ¸ö0 if len(labels) > 0: - - boxes = boxes[0] labels = labels[0] scores = scores[0] ratio_x = (width / 1024.0) ratio_y = (height / 768.0) - for i in range(len(boxes)): boxes[i][0] = boxes[i][0] * ratio_x boxes[i][2] = boxes[i][2] * ratio_x @@ -545,7 +731,7 @@ class Detection_Y5: boxes[i][1] = 2159 if boxes[i][2] < 0: boxes[i][2] = 0 - if boxes[i][2]> 3840: + if boxes[i][2] > 3840: boxes[i][2] = 3839 if boxes[i][3] < 0: boxes[i][3] = 0 @@ -554,18 +740,16 @@ class Detection_Y5: for i in range(len(labels)): labels[i] = 99999 boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores) - t4 = time.time() - if gp.DebugPrint_flag: - print("Detection final is ", (t4 - t3) * 1000) - t6 = time.time() - xml_outputpath = ImagePath.replace("/ftp/", "/ftp_Result/").replace(".JPG", ".xml").replace(".jpg", - ".xml") - make_xml(str(ImagePath), image_or.shape[0], image_or.shape[1], boxes_fine, labels_fine, scores_fine, - xml_outputpath) + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("Detection final is ", (t4 - t3) * 1000) + # t6 = time.time() + xml_outputpath = ImagePath.replace("/ftp/", "/ftp_Result/").replace(".JPG", ".xml").replace(".jpg", ".xml") + make_xml(str(ImagePath), image_or.shape[0], image_or.shape[1], boxes_fine, labels_fine, scores_fine, xml_outputpath) # Image.fromarray(drawn_image).save(xml_outputpath.replace(".xml",".jpg")) - t5 = time.time() - if gp.DebugPrint_flag: - print("Detection save is ", (t5 - t6) * 1000) + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Detection save is ", (t5 - t6) * 1000) else: boxes_fine, labels_fine, scores_fine = [], [], [] if gp.DebugPrint_flag: @@ -579,37 +763,35 @@ class Detection_Y5: # img = cv2.imread(path) # img = cv2.resize() height, width = img_o.shape[:2] - img = cv2.resize(img_o,(1024,768)) - t1 = time.time() + img = cv2.resize(img_o,(2000,1000)) + # t1 = time.time() + image_scale, image = self.preprocess(img) - t2 = time.time() - if gp.DebugPrint_flag: - print("Check data deal is ", (t2 - t1) * 1000) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("Check data deal is ", (t2 - t1) * 1000) pred = self.model(image, augment=False)[0] pred = pred.float() pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) - t3 = time.time() - if gp.DebugPrint_flag: - print("Check inference is ", (t3 - t2) * 1000) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("Check inference is ", (t3 - t2) * 1000) boxes = [] scores = [] labels = [] for det in pred: - if det is not None and len(det): det[:, :4] = scale_coords( image.shape[2:], det[:, :4], image_scale.shape).round() - boxes.append(det[:, :4]) scores.append(det[:, 4]) labels.append((det[:, -1])) boxes = boxes[0] scores = scores[0] labels = labels[0] - t5 = time.time() - if gp.DebugPrint_flag: - print("Check get result is ", (t5 - t3) * 1000) - + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Check get result is ", (t5 - t3) * 1000) if len(labels) > 0: # indices_label_left = labels < 1 # indices_label_right = labels < 1 @@ -627,12 +809,11 @@ class Detection_Y5: if len(labels) > 0: if len(boxes.shape) == 3: - boxes = boxes[0] labels = labels[0] scores = scores[0] - ratio_x = (width / 1024.0) - ratio_y = (height / 768.0) + ratio_x = (width / 2000) + ratio_y = (height / 1000) for i in range(len(boxes)): #boxes = boxes.numpy() boxes[i][0] = boxes[i][0] * ratio_x @@ -660,9 +841,9 @@ class Detection_Y5: if 0 in labels: flag = True if gp.DebugPrint_flag: - print("boxes = ",boxes) - print("check flag is ",flag) - return flag,labels,boxes,scores + print("boxes = ", boxes) + print("check flag is ", flag) + return flag, labels, boxes, scores """ ϸÁ£¶Èʶ±ð """ @@ -675,31 +856,34 @@ class args_temp(): resize_resolution = 512 crop_resolution = 448 save_suffix = None - swap_num = [7,7] + swap_num = [7, 7] class Fine_grained_T: - def __init__(self,device,root): + def __init__(self, device): self.device = device self.WeightPath = gp.FineWeight - self.net = Multi_transform_image().to(device) + self.net = timm.create_model(gp.backbone, num_classes=gp.FineClassNum, pretrained=False).to(device) # Multi_transform_image().to(device) model_dict = self.net.state_dict() pretrained_dict = torch.load(self.WeightPath) - pretrained_dict = {k: v for k, v in pretrained_dict.items() if - k not in ['classifier.weight', 'classifier_swap.weight', 'Convmask.weight', 'Convmask.bias']} + pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} model_dict.update(pretrained_dict) - self.net.load_state_dict(model_dict) - self.transformers = load_data_transformers(600, 448, [7, 7]) + self.net.load_state_dict(pretrained_dict) + self.transformers = load_data_transformers(600, 224, [7, 7]) print("load model weight is ok") self.net.train(False) - self.softmax = nn.Softmax() + self.softmax = nn.Softmax(dim=1) + self.gp_Species = torch.zeros(8).cuda(device) if gp.DebugPrint_flag: print("load model weight is ok") - def inference(self,img,imagelist,labellist,scorelist,multiimagenum): + + + + def inference(self, img, imagelist, labellist, scorelist, multiimagenum): with torch.no_grad(): img_deal = [] labelIndexForFusionResult = 0 imaIndexIfSuit = [0 for i in range(len(imagelist))] - for i,box in enumerate(imagelist): - if box[0]<0: + for i, box in enumerate(imagelist): + if box[0] < 0: box[0] = 0 if box[1] < 0: box[1] = 0 @@ -707,7 +891,21 @@ class Fine_grained_T: box[2] = 0 if box[3] < 0: box[3] = 0 - Img = img.copy()[int(box[1]):int(box[3]), int(box[0]):int(box[2]), :] + X_left = int(box[1])-10 + if X_left < 0: + X_left = 0 + X_right = int(box[3])+10 + if X_right>2159: + X_right = 2159 + + y_up = int(box[0])-10 + if y_up <0 : + y_up = 0 + + y_down = int(box[2])+10 + if y_down>3839: + y_down =3839 + Img = img.copy()[X_left:X_right, y_up:y_down, :] #if gp.DebugPrint_flag: #print(box) #print(Img) @@ -723,97 +921,90 @@ class Fine_grained_T: iter_nums = int(len(img_deal)/multiimagenum) single_imagedealnums = int(len(img_deal)%multiimagenum) for iter_num in range(iter_nums): - print("start {} iter".format(str(iter_num))) - t1 = time.time() - Img = torch.cat((img_deal[0*iter_num],img_deal[1*iter_num],img_deal[2*iter_num],img_deal[3*iter_num],img_deal[4*iter_num],img_deal[5*iter_num],img_deal[6*iter_num],img_deal[7*iter_num]),0) + tqdm.write("start {} iter".format(str(iter_num))) + # t1 = time.time() + Img = torch.cat((img_deal[0*iter_num], img_deal[1*iter_num], img_deal[2*iter_num], img_deal[3*iter_num], img_deal[4*iter_num], img_deal[5*iter_num], img_deal[6*iter_num], img_deal[7*iter_num]), 0) inputs = Variable(Img.cuda()) - t2 = time.time() - if gp.DebugPrint_flag: - print("iter{} fine data deal is ".format(str(iter_num)), (t2 - t1) * 1000) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("iter{} fine data deal is ".format(str(iter_num)), (t2 - t1) * 1000) outputs = self.net(inputs) outputs = self.softmax(outputs) - t3 = time.time() - if gp.DebugPrint_flag: - print("iter{} fine inference is ".format(str(iter_num)), (t3 - t2) * 1000) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("iter{} fine inference is ".format(str(iter_num)), (t3 - t2) * 1000) #outputs[0] = self.softmax(outputs[0]) - #Species = torch.zeros(multiimagenum).cuda() - Species = gp.Species - t4_1 = time.time() - if gp.DebugPrint_flag: - print("iter{} fine data final1 is ".format(str(iter_num)), (t4_1 - t3) * 1000) + Species = self.gp_Species + # t4_1 = time.time() + # if gp.DebugPrint_flag: + # print("iter{} fine data final1 is ".format(str(iter_num)), (t4_1 - t3) * 1000) for outnum in range(multiimagenum): - top3_val, top3_pos = torch.topk(outputs[outnum],1) - - t4_temp2 = time.time() + # t4_temp2 = time.time() if top3_val < gp.Fine_thresh: Species[outnum] = 0 else: Species[outnum] = top3_pos - t4_temp3 = time.time() - print("iter{} fine data temp3 is ".format(str(iter_num)), (t4_temp3 - t4_temp2) * 1000) - t4_2 = time.time() - if gp.DebugPrint_flag: - print("iter{} fine data final2 is ".format(str(iter_num)), (t4_2 - t4_1) * 1000) + # t4_temp3 = time.time() + # tqdm.write("iter{} fine data temp3 is ".format(str(iter_num)), (t4_temp3 - t4_temp2) * 1000) + # t4_2 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("iter{} fine data final2 is ".format(str(iter_num)), (t4_2 - t4_1) * 1000) for j in range(multiimagenum): for m in range(len(imaIndexIfSuit)): - if imaIndexIfSuit[labelIndexForFusionResult]==1: #clam this boxes has been deal with fine grained + if imaIndexIfSuit[labelIndexForFusionResult] == 1: #clam this boxes has been deal with fine grained labellist[labelIndexForFusionResult] = Species[j] - labelIndexForFusionResult+=1 + labelIndexForFusionResult += 1 break else: - labelIndexForFusionResult+=1 - t4_3 = time.time() - if gp.DebugPrint_flag: - print("iter{} fine data final3 is ".format(str(iter_num)), (t4_3 - t4_2) * 1000) + labelIndexForFusionResult += 1 + # t4_3 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("iter{} fine data final3 is ".format(str(iter_num)), (t4_3 - t4_2) * 1000) #labellist[iter_num*multiimagenum:iter_num*multiimagenum+multiimagenum] = Species - t4 = time.time() - if gp.DebugPrint_flag: - print("iter{} fine data final is ".format(str(iter_num)), (t4 - t3) * 1000) - - t4 = time.time() - if gp.DebugPrint_flag: - print("start {} single_imagedealnums".format(str(single_imagedealnums))) - print("single_imagedealnums is ",single_imagedealnums) + # t4 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("iter{} fine data final is ".format(str(iter_num)), (t4 - t3) * 1000) + # t4 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("start {} single_imagedealnums".format(str(single_imagedealnums))) + # tqdm.write("single_imagedealnums is ",single_imagedealnums) Img = None - if single_imagedealnums==0: + if single_imagedealnums == 0: pass - elif single_imagedealnums ==1: - + elif single_imagedealnums == 1: Img = img_deal[(iter_nums) * multiimagenum] - else: #Img = torch.cat((img_deal[0*iter_num],img_deal[1*iter_num],img_deal[2*iter_num],img_deal[3*iter_num],img_deal[4*iter_num],img_deal[5*iter_num],img_deal[6*iter_num],img_deal[7*iter_num]),0) - tF1 = time.time() + # tF1 = time.time() singleimage = [] for tempm in range(single_imagedealnums): singleimage.append(img_deal[(iter_nums) * multiimagenum+tempm]) - Img = torch.cat(singleimage,0) + Img = torch.cat(singleimage, 0) # Img = torch.cat((img_deal[(iter_nums) * multiimagenum], img_deal[(iter_nums) * multiimagenum+1]), 0) # for single_imagedealnum in range(single_imagedealnums-2): # Img = torch.cat((Img,img_deal[(iter_nums) * multiimagenum+1+single_imagedealnum+1]),0) - tF2 = time.time() - if gp.DebugPrint_flag: - print("single_imagedealnumsv fine data deal cat is ", (tF2 - tF1) * 1000) - t5 = time.time() - if gp.DebugPrint_flag: - print("single_imagedealnumsv fine data deal is ", (t5 - t4) * 1000) - if not (Img==None): - tsfCU1 = time.time() + # tF2 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("single_imagedealnumsv fine data deal cat is ", (tF2 - tF1) * 1000) + # t5 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("single_imagedealnumsv fine data deal is ", (t5 - t4) * 1000) + if not (Img == None): + # tsfCU1 = time.time() inputs = Variable(Img.cuda()) - tsfCU2 = time.time() - if gp.DebugPrint_flag: - print("single_imagedealnumsv tocuda is ", (tsfCU2 - tsfCU1) * 1000) + # tsfCU2 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("single_imagedealnumsv tocuda is ", (tsfCU2 - tsfCU1) * 1000) outputs = self.net(inputs) outputs = self.softmax(outputs) - t6 = time.time() - if gp.DebugPrint_flag: - print("single_imagedealnums fine inference is ", (t6 - t5) * 1000) - Species = gp.Species + # t6 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("single_imagedealnums fine inference is ", (t6 - t5) * 1000) + Species = self.gp_Species #Species = torch.zeros(single_imagedealnums).cuda() for outnum in range(single_imagedealnums): - top3_val, top3_pos = torch.topk(outputs[outnum], 1) #print("top3_val==========", top3_val) t4_temp2 = time.time() @@ -821,9 +1012,8 @@ class Fine_grained_T: Species[outnum] = 0 else: Species[outnum] = top3_pos - t4_temp3 = time.time() - print("single_imagedealnums fine data temp3 is ", (t4_temp3 - t4_temp2) * 1000) - + # t4_temp3 = time.time() + # print("single_imagedealnums fine data temp3 is ", (t4_temp3 - t4_temp2) * 1000) for j in range(single_imagedealnums): for m in range(len(imaIndexIfSuit)): if imaIndexIfSuit[labelIndexForFusionResult] == 1: # clam this boxes has been deal with fine grained @@ -834,13 +1024,140 @@ class Fine_grained_T: labelIndexForFusionResult += 1 #labellist[len(labellist)-single_imagedealnums:] = Species - t7 = time.time() - if gp.DebugPrint_flag: - print(" fine data final is ", (t7 - t6) * 1000) + # t7 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write(" fine data final is ", (t7 - t6) * 1000) + return imagelist, labellist, scorelist + def inference_scan(self, img, imagelist, labellist, scorelist, multiimagenum): + with torch.no_grad(): + img_deal = [] + labelIndexForFusionResult = 0 + imaIndexIfSuit = [0 for i in range(len(imagelist))] + for i, box in enumerate(imagelist): + if box[0] < 0: + box[0] = 0 + if box[1] < 0: + box[1] = 0 + if box[2] < 0: + box[2] = 0 + if box[3] < 0: + box[3] = 0 + Img = img.copy()[int(box[1]):int(box[3]), int(box[0]):int(box[2]), :] + + if ((int(box[3]) - int(box[1])) * (int(box[2]) - int(box[0]))) > gp.fine_thresh1 : + Img = Image.fromarray(cv2.cvtColor(Img, cv2.COLOR_BGR2RGB)) + Img = self.transformers['test_totensor'](Img) + Img = Img.unsqueeze(0) + img_deal.append(Img) + imaIndexIfSuit[i] =1 + outputs = self.net(Img.cuda()) + outputs = self.softmax(outputs) + top3_val, top3_pos = torch.topk(outputs,1) + if top3_val < gp.Fine_thresh: + labellist[i] = 0 + else: + labellist[i] = top3_pos + + else: + pass + return imagelist, labellist, scorelist + +class Fine_grained_mmclsonnx: + def __init__(self, device): + self.device = device + self.WeightPath = gp.FineWeight + modelconfig = "/data1/Hatcher/model/FineGrained/mmclassification/configs/convnext/convnext-base_4xb32_cmb200inf.py" + self.net = init_model(modelconfig, self.WeightPath, device=self.device) + print("load model weight is ok") + + self.transformers = load_data_transformers(600, 896, [7, 7]) + self.gp_Species = torch.zeros(8).cuda(device) + if gp.DebugPrint_flag: + print("load model weight is ok") + + + + def inference(self, img, imagelist, labellist, scorelist, multiimagenum): + with torch.no_grad(): + img_deal = [] + labelIndexForFusionResult = 0 + imaIndexIfSuit = [0 for i in range(len(imagelist))] + for i, box in enumerate(imagelist): + if box[0] < 0: + box[0] = 0 + if box[1] < 0: + box[1] = 0 + if box[2] < 0: + box[2] = 0 + if box[3] < 0: + box[3] = 0 + X_left = int(box[1])-10 + if X_left < 0: + X_left = 0 + X_right = int(box[3])+10 + if X_right>2159: + X_right = 2159 + + y_up = int(box[0])-10 + if y_up <0 : + y_up = 0 + + y_down = int(box[2])+10 + if y_down>3839: + y_down =3839 + Img = img.copy()[X_left:X_right, y_up:y_down, :] + #if gp.DebugPrint_flag: + #print(box) + #print(Img) + #if (int(box[3])-int(box[1])>gp.fine_thresh) and (int(box[2])-int(box[0])>gp.fine_thresh): + if ((int(box[3]) - int(box[1])) * (int(box[2]) - int(box[0]))) > gp.fine_thresh1 : + #Img = Image.fromarray(cv2.cvtColor(Img, cv2.COLOR_BGR2RGB)) + #Img = self.transformers['test_totensor'](Img) + #Img = Img.unsqueeze(0) + #img_deal.append(Img) + #imaIndexIfSuit[i] =1 + outputs = inference_model(self.net,Img) + labellist[i] = outputs["pred_label"] + + else: + pass + return imagelist, labellist, scorelist + def inference_scan(self, img, imagelist, labellist, scorelist, multiimagenum): + with torch.no_grad(): + img_deal = [] + labelIndexForFusionResult = 0 + imaIndexIfSuit = [0 for i in range(len(imagelist))] + for i, box in enumerate(imagelist): + if box[0] < 0: + box[0] = 0 + if box[1] < 0: + box[1] = 0 + if box[2] < 0: + box[2] = 0 + if box[3] < 0: + box[3] = 0 + Img = img.copy()[int(box[1]):int(box[3]), int(box[0]):int(box[2]), :] + + if ((int(box[3]) - int(box[1])) * (int(box[2]) - int(box[0]))) > gp.fine_thresh1 : + Img = Image.fromarray(cv2.cvtColor(Img, cv2.COLOR_BGR2RGB)) + Img = self.transformers['test_totensor'](Img) + Img = Img.unsqueeze(0) + img_deal.append(Img) + imaIndexIfSuit[i] =1 + outputs = self.net(Img.cuda()) + outputs = self.softmax(outputs) + top3_val, top3_pos = torch.topk(outputs,1) + if top3_val < gp.Fine_thresh: + labellist[i] = 0 + else: + labellist[i] = top3_pos + + else: + pass return imagelist, labellist, scorelist class Fine_grained: - def __init__(self,device,root): + def __init__(self, device, root): self.device = device self.root = root self.DclPreWeightPath = '../data_MPKFNet/test/3.pth' @@ -854,8 +1171,7 @@ class Fine_grained: # parser.add_argument('--crop', dest='crop_resolution', default=448, type=int) # parser.add_argument('--ss', dest='save_suffix', default=None, type=str) # parser.add_argument('--acc_report', dest='acc_report', action='store_true') - # parser.add_argument('--swap_num', default=[7, 7], nargs=2, metavar=('swap1', 'swap2'), type=int, - # help='specify a range') + # parser.add_argument('--swap_num', default=[7, 7], nargs=2, metavar=('swap1', 'swap2'), type=int, help='specify a range') self.args = args_temp() self.Config = LoadConfig(self.args, 's') self.transformers = load_data_transformers(self.args.resize_resolution, self.args.crop_resolution, self.args.swap_num) @@ -869,38 +1185,37 @@ class Fine_grained: self.net.train(False) def inference(self,img,imagelist,labellist,scorelist): with torch.no_grad(): - for i,box in enumerate(imagelist): + for i, box in enumerate(imagelist): Img = img.copy()[int(box[1]):int(box[3]), int(box[0]):int(box[2]), :] - if (int(box[3])-int(box[1])>100) and (int(box[2])-int(box[0])>100): + if (int(box[3])-int(box[1]) > 100) and (int(box[2])-int(box[0]) > 100): t1 = time.time() Img = Image.fromarray(cv2.cvtColor(Img, cv2.COLOR_BGR2RGB)) Img = self.transformers['test_totensor'](Img) Img = Img.unsqueeze(0) inputs = Variable(Img.cuda()) - t2 = time.time() - if gp.DebugPrint_flag: - print("fine data deal is ", (t2 - t1) * 1000) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("fine data deal is ", (t2 - t1) * 1000) outputs = self.net(inputs) - t3 = time.time() - if gp.DebugPrint_flag: - print("fine inference is ", (t3 - t2) * 1000) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("fine inference is ", (t3 - t2) * 1000) top3_val, top3_pos = torch.topk(outputs[0], 3) # topk·µ»ØµÄÊÇÒ»¸öÔª×飬µÚÒ»¸öÔªËØÊÇÿһÐÐ×î´óµÄÈý¸öÖµ£¨Ä¬ÈÏÊǰ´ÐÐÈ¡×î´óÖµ£©£¬µÚ¶þ¸öÔªËØÊÇÿһÐÐ×î´óµÄÖµµÄÅÅÐò Species = top3_pos.cpu().numpy()[0][0] ConfidenceLevel = top3_val.cpu().numpy()[0][0] ConfidenceLevel = ConfidenceLevel/26.0 - if ConfidenceLevel >1: - ConfidenceLevel = 1.0* random.uniform(0, 1) - if gp.DebugPrint_flag: - print("hhhhhhhhhhhhhhhhhhhhhhh is ",ConfidenceLevel) + if ConfidenceLevel > 1: + ConfidenceLevel = 1.0 * random.uniform(0, 1) + # if gp.DebugPrint_flag: + # print("hhhhhhhhhhhhhhhhhhhhhhh is ",ConfidenceLevel) labellist[i] = Species scorelist[i] = ConfidenceLevel - t4 = time.time() - if gp.DebugPrint_flag: - print("fine data final is ", (t4 - t3) * 1000) - + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("fine data final is ", (t4 - t3) * 1000) return imagelist, labellist, scorelist class Check_start (threading.Thread): - def __init__(self, threadID, name, img,DetectionClass): + def __init__(self, threadID, name, img, DetectionClass): threading.Thread.__init__(self) self.threadID = threadID self.name = name @@ -908,16 +1223,16 @@ class Check_start (threading.Thread): self.DetectionClass = DetectionClass def run(self): if gp.DebugPrint_flag: - print(self.name + " is start") - gp.is_ex_bird ,labels, boxes ,scores= self.DetectionClass.check_object(self.img) + tqdm.write(self.name + " is start") + gp.is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(self.img) - if gp.is_ex_bird : + if gp.is_ex_bird: if gp.DebugPrint_flag: - print(gp.is_ex_bird) - gp.image_time = gp.Camera_device +time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())) + tqdm.write(gp.is_ex_bird) + gp.image_time = gp.Camera_device +time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) if gp.DebugPrint_flag: - print(self.name + " is finish") -class save_sigle_image (threading.Thread): + tqdm.write(self.name + " is finish") +class save_sigle_image(threading.Thread): def __init__(self, img): threading.Thread.__init__(self) self.img = img @@ -926,7 +1241,7 @@ class save_sigle_image (threading.Thread): "../data_MPKFNet/RTSP2/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), self.img) class Check_start_fordataselect (threading.Thread): - def __init__(self, threadID, name, img,DetectionClass,fine_grained): + def __init__(self, threadID, name, img, DetectionClass, fine_grained): threading.Thread.__init__(self) self.threadID = threadID self.name = name @@ -936,11 +1251,10 @@ class Check_start_fordataselect (threading.Thread): def run(self): if gp.DebugPrint_flag: print(self.name + " is start") - is_ex_bird ,labels, boxes ,scores= self.DetectionClass.check_object(self.img) + is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(self.img) image_or = self.img.copy() - if is_ex_bird : + if is_ex_bird: for i in range(len(boxes)): - if boxes[i][0] < 0: boxes[i][0] = 0 if boxes[i][1] < 0: @@ -965,22 +1279,19 @@ class Check_start_fordataselect (threading.Thread): self.img = plot_one_box(xyxy, self.img, label=label, color=colors, line_thickness=2) #cv2.imshow("AI-ECO",self.img) #cv2.waitKey(0) - cv2.imwrite("../data_MPKFNet/RTSP/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), - image_or) - cv2.imwrite( - "../data_MPKFNet/RTSP/result/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), - self.img) + cv2.imwrite("../data_MPKFNet/RTSP/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), image_or) + cv2.imwrite("../data_MPKFNet/RTSP/result/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), self.img) if gp.DebugPrint_flag: print(self.name + " is finish") class shishi(): - def __init__(self, name, DetectionClass,fine_grained): - + def __init__(self, name, DetectionClass, fine_grained): self.threadID = 0 self.name = name - self.DetectionClass = DetectionClass self.fine_grained = fine_grained - def go_go(self,img,num_image,num_detection): + + + def go_go(self, img, num_image, num_detection): spiec_number = [0 for i in range(len(gp.BHG_chineseName))] img_show = img.copy() boxes_fine = [] @@ -990,18 +1301,17 @@ class shishi(): draw = ImageDraw.Draw(img_show) height_or, width_or = img.shape[:2] if gp.DebugPrint_flag: - print("image size is ",height_or,width_or) + print("image size is ", height_or, width_or) if(num_detection%2==0): if gp.DebugPrint_flag: print(self.name + " is start") - ts1 = time.time() - is_ex_bird ,labels, boxes ,scores= self.DetectionClass.check_object(img) - ts2 = time.time() - if gp.DebugPrint_flag: - print("shishi time detect1 deal is ", (ts2 - ts1) * 1000) - if is_ex_bird : + # ts1 = time.time() + is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(img) + # ts2 = time.time() + # if gp.DebugPrint_flag: + # print("shishi time detect1 deal is ", (ts2 - ts1) * 1000) + if is_ex_bird: for i in range(len(boxes)): - if boxes[i][0] < 0: boxes[i][0] = 0 if boxes[i][1] < 0: @@ -1012,102 +1322,85 @@ class shishi(): boxes[i][3] = 0 for i in range(len(labels)): labels[i] = 0#gp.birdIndex - ts3 = time.time() - if gp.DebugPrint_flag: - print("shish time detect2 deal is ", (ts3 - ts2) * 1000) - boxes_fine, labels_fine, scores_fine = self.fine_grained.inference(img, boxes, labels, scores,8) - ts4 = time.time() - if gp.DebugPrint_flag: - print("shish time detect3 deal is ", (ts4 - ts3) * 1000) - tcpu1 = time.time() + # ts3 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect2 deal is ", (ts3 - ts2) * 1000) + boxes_fine, labels_fine, scores_fine = self.fine_grained.inference(img, boxes, labels, scores, 8) + # ts4 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect3 deal is ", (ts4 - ts3) * 1000) + # tcpu1 = time.time() boxes_fine = boxes_fine.to('cpu') labels_fine = labels_fine.to('cpu') - - tcpu2 = time.time() - if gp.DebugPrint_flag: - print("to cpu timeis ", (tcpu2 - tcpu1) * 1000) + # tcpu2 = time.time() + # if gp.DebugPrint_flag: + # print("to cpu timeis ", (tcpu2 - tcpu1) * 1000) gp.boxes_fine = boxes_fine gp.labels_fine = labels_fine else: print("don't deal {}".format(str(num_detection))) boxes_fine = gp.boxes_fine - labels_fine =gp.labels_fine - - - + labels_fine = gp.labels_fine for i in range(len(boxes_fine)): - tprint1 = time.time() + # tprint1 = time.time() xyxy = boxes_fine[i] - cls = labels_fine[i] - - tprint2 = time.time() - if gp.DebugPrint_flag: - print("tprint1 is ", (tprint2 - tprint1) * 1000) - tcls1 = time.time() + # tprint2 = time.time() + # if gp.DebugPrint_flag: + # print("tprint1 is ", (tprint2 - tprint1) * 1000) + # tcls1 = time.time() b = (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < 15000) - #a =(xyxy.item()[3] - xyxy.item()[1]) * (xyxy.item()[2] - xyxy.item()[0]) - tcls2 = time.time() - if gp.DebugPrint_flag: - print("tcls1 is ", (tcls2 - tcls1) * 1000) + # a =(xyxy.item()[3] - xyxy.item()[1]) * (xyxy.item()[2] - xyxy.item()[0]) + # tcls2 = time.time() + # if gp.DebugPrint_flag: + # print("tcls1 is ", (tcls2 - tcls1) * 1000) if cls == 0 or (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < gp.fine_thresh2): #if cls == gp.birdIndex or (torch.sub(torch.mul(torch.sub(xyxy[3], xyxy[1]), torch.sub(xyxy[2], xyxy[0])),gp.fine_thresh2) < 0): label = None else: - tcls3 = time.time() + # tcls3 = time.time() label = gp.BHG_chineseName[int(cls)] spiec_number[int(cls)] += 1 - tcls4 = time.time() - if gp.DebugPrint_flag: - print("tcls2 is ", (tcls4 - tcls3) * 1000) - tprint3 = time.time() - if gp.DebugPrint_flag: - print("tprint2 is ", (tprint3 - tprint2) * 1000) + # tcls4 = time.time() + # if gp.DebugPrint_flag: + # print("tcls2 is ", (tcls4 - tcls3) * 1000) + # tprint3 = time.time() + # if gp.DebugPrint_flag: + # print("tprint2 is ", (tprint3 - tprint2) * 1000) #label = f'{int(cls)} {conf:.2f}' palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1) colors = gp.color_box#tuple(int((p * (4 ** 2 - 4 + 1)) % 220) for p in palette) - tprint4 = time.time() - if gp.DebugPrint_flag: - print("tprint3 is ", (tprint4 - tprint3) * 1000) + # tprint4 = time.time() + # if gp.DebugPrint_flag: + # print("tprint3 is ", (tprint4 - tprint3) * 1000) draw = plot_one_box(xyxy, draw, height_or,width_or,label=label, color=colors, line_thickness=2) - tpChin1 = time.time() + # tpChin1 = time.time() if num_image > gp.showThresh : gp.num_count_old = len(boxes_fine) gp.spiec_number_old = spiec_number num_image = 0 - tpChin2 = time.time() - if gp.DebugPrint_flag: - print("tpChin1 is ", (tpChin2 - tpChin1) * 1000) + # tpChin2 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin1 is ", (tpChin2 - tpChin1) * 1000) #if width_or == 2560: - draw = cv2AddChineseText(draw, "ʶ±ð×ÜÊý: {}Ö»".format(str(gp.num_count_old)), (50*gp.radioShowX, 1100*gp.radioShowY), - textColor=gp.color_show, - textSize=50) - tpChin3 = time.time() - if gp.DebugPrint_flag: - print("tpChin2 is ", (tpChin3 - tpChin2) * 1000) - draw = cv2AddChineseText(draw, "·ÖÀàʶ±ð:", (50*gp.radioShowX, 1150*gp.radioShowY), textColor=gp.color_show, - textSize=50) - tpChin4 = time.time() - if gp.DebugPrint_flag: - print("tpChin3 is ", (tpChin4 - tpChin3) * 1000) - for i in range(1,len(spiec_number)): - if i <5: - draw = cv2AddChineseText(draw, "{}:{}Ö»".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), - (300*gp.radioShowX + (i-1) * 280*gp.radioShowX, 1150*gp.radioShowY), textColor=gp.color_show, - textSize=50) + draw = cv2AddChineseText(draw, "ʶ±ð×ÜÊý: {}Ö»".format(str(gp.num_count_old)), (50*gp.radioShowX, 1100*gp.radioShowY), textColor=gp.color_show, textSize=50) + # tpChin3 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin2 is ", (tpChin3 - tpChin2) * 1000) + draw = cv2AddChineseText(draw, "·ÖÀàʶ±ð:", (50*gp.radioShowX, 1150*gp.radioShowY), textColor=gp.color_show, textSize=50) + # tpChin4 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin3 is ", (tpChin4 - tpChin3) * 1000) + for i in range(1, len(spiec_number)): + if i < 5: + draw = cv2AddChineseText(draw, "{}:{}Ö»".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), (300*gp.radioShowX + (i-1) * 280*gp.radioShowX, 1150*gp.radioShowY), textColor=gp.color_show, textSize=50) else: - draw = cv2AddChineseText(draw, "{}:{}Ö»".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), - (50*gp.radioShowX + (i-5) * 280*gp.radioShowX, 1200*gp.radioShowY), textColor=gp.color_show, - textSize=50) + draw = cv2AddChineseText(draw, "{}:{}Ö»".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), (50*gp.radioShowX + (i-5) * 280*gp.radioShowX, 1200*gp.radioShowY), textColor=gp.color_show, textSize=50) img_show = cv2.cvtColor(np.asarray(img_show), cv2.COLOR_RGB2BGR) gp.img_show = img_show - - tpChin2 = time.time() - if gp.DebugPrint_flag: - print("tpChin is ", (tpChin2 - tpChin1) * 1000) - - - + # tpChin2 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin is ", (tpChin2 - tpChin1) * 1000) #cv2.waitKey(0) # cv2.imwrite("../data_MPKFNet/RTSP/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), # image_or) @@ -1116,19 +1409,19 @@ class shishi(): # self.img) if gp.DebugPrint_flag: print(self.name + " is finish") - num_image +=1 + num_image += 1 print(num_image) - - return img_show,num_image + return img_show, num_image class RealDeal(): - def __init__(self, name, DetectionClass,fine_grained): - + def __init__(self, name, DetectionClass, fine_grained,DensityClass): self.threadID = 0 self.name = name - self.DetectionClass = DetectionClass self.fine_grained = fine_grained - def realtimerestart(self,img,num_image,num_detection,SortRestart): + self.DensityClass = DensityClass + + + def realtimerestart(self, img, num_image, num_detection, SortRestart): spiec_number = [0 for i in range(len(gp.BHG_chineseName))] img_show = img.copy() boxes_fine = [] @@ -1137,19 +1430,18 @@ class RealDeal(): img_show = Image.fromarray(cv2.cvtColor(img_show, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img_show) height_or, width_or = img.shape[:2] - if gp.DebugPrint_flag: - print("image size is ",height_or,width_or) - if gp.DebugPrint_flag: - print(self.name + " is start") - ts1 = time.time() - is_ex_bird ,labels, boxes ,scores= self.DetectionClass.check_object(img) - ts2 = time.time() - if gp.DebugPrint_flag: - print("shishi time detect1 deal is ", (ts2 - ts1) * 1000) - - if is_ex_bird : + # if gp.DebugPrint_flag: + # print("image size is ",height_or,width_or) + # if gp.DebugPrint_flag: + # print(self.name + " is start") + # ts1 = time.time() + is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(img) + density_result,density_num = self.DensityClass.Inf_sigle(img,False) + # ts2 = time.time() + # if gp.DebugPrint_flag: + # print("shishi time detect1 deal is ", (ts2 - ts1) * 1000) + if is_ex_bird: for i in range(len(boxes)): - if boxes[i][0] < 0: boxes[i][0] = 0 if boxes[i][1] < 0: @@ -1160,34 +1452,30 @@ class RealDeal(): boxes[i][3] = 0 for i in range(len(labels)): labels[i] = 0#gp.birdIndex - ts3 = time.time() - if gp.DebugPrint_flag: - print("shish time detect2 deal is ", (ts3 - ts2) * 1000) - - + # ts3 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect2 deal is ", (ts3 - ts2) * 1000) boxes_fine, labels_fine, scores_fine = self.fine_grained.inference(img, boxes, labels, scores,8) - ts4 = time.time() - if gp.DebugPrint_flag: - print("shish time detect3 deal is ", (ts4 - ts3) * 1000) - tcpu1 = time.time() + # ts4 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect3 deal is ", (ts4 - ts3) * 1000) + # tcpu1 = time.time() boxes_fine = boxes_fine.to('cpu') labels_fine = labels_fine.to('cpu') - - tcpu2 = time.time() - if gp.DebugPrint_flag: - print("to cpu timeis ", (tcpu2 - tcpu1) * 1000) + # tcpu2 = time.time() + # if gp.DebugPrint_flag: + # print("to cpu timeis ", (tcpu2 - tcpu1) * 1000) gp.boxes_fine = boxes_fine gp.labels_fine = labels_fine #input = [x1,y1,x2,y2,kong,label] temp_sort = [i + 100 for i in range(len(labels_fine))] - DetFine = np.column_stack((boxes_fine,temp_sort,labels_fine)) - boxes_fine,indexmaxtemp,newObjectNum = SortRestart.update(DetFine)#boxes_fine ÊÇ n*6µÄÊý×飬nÊÇÄ¿±êµÄÊýÁ¿£¬¶øÇÒÐòºÅÊǵ¹ÐòµÄ£¬×îСµÄÐòºÅÊÇ1 + DetFine = np.column_stack((boxes_fine, temp_sort, labels_fine)) + boxes_fine, indexmaxtemp, newObjectNum = SortRestart.update(DetFine) # boxes_fine ÊÇ n*6µÄÊý×飬nÊÇÄ¿±êµÄÊýÁ¿£¬¶øÇÒÐòºÅÊǵ¹ÐòµÄ£¬×îСµÄÐòºÅÊÇ1 if indexmaxtemp > gp.IndexMax: gp.IndexMax = indexmaxtemp #boxes_fine = boxes_fine[0] #output = [x1,y1,x2,y2,label,index] gp.Finerestartboxes.append(boxes_fine) - # for i in range(len(boxes_fine)): # xyxy = boxes_fine[i][:4] # cls = boxes_fine[i][4] @@ -1225,15 +1513,14 @@ class RealDeal(): # textSize=int(50* gp.radioShowtext)) img_show = cv2.cvtColor(np.asarray(img_show), cv2.COLOR_RGB2BGR) gp.img_show = img_show - tpChin2 = time.time() if gp.DebugPrint_flag: print(self.name + " is finish") - num_image +=1 + num_image += 1 + return img_show, num_image - return img_show,num_image - def realtime(self,img,num_image,num_detection,SortRestart): + def realtime(self, img, num_image, num_detection, SortRestart): spiec_number = [0 for i in range(len(gp.BHG_chineseName))] img_show = img.copy() boxes_fine = [] @@ -1243,18 +1530,18 @@ class RealDeal(): draw = ImageDraw.Draw(img_show) height_or, width_or = img.shape[:2] if gp.DebugPrint_flag: - print("image size is ",height_or,width_or) + print("image size is ", height_or, width_or) if gp.DebugPrint_flag: print(self.name + " is start") - ts1 = time.time() - is_ex_bird ,labels, boxes ,scores= self.DetectionClass.check_object(img) - ts2 = time.time() - if gp.DebugPrint_flag: - print("shishi time detect1 deal is ", (ts2 - ts1) * 1000) + # ts1 = time.time() + is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(img) + density_result,density_num = self.DensityClass.Inf_sigle(img,0) + # ts2 = time.time() + # if gp.DebugPrint_flag: + # print("shishi time detect1 deal is ", (ts2 - ts1) * 1000) if is_ex_bird : - print("Ä¿±ê¼ì²âµÄ¸öÊý ", len(boxes)) + # print("Ä¿±ê¼ì²âµÄ¸öÊý ", len(boxes)) for i in range(len(boxes)): - if boxes[i][0] < 0: boxes[i][0] = 0 if boxes[i][1] < 0: @@ -1265,27 +1552,24 @@ class RealDeal(): boxes[i][3] = 0 for i in range(len(labels)): labels[i] = 0#gp.birdIndex - ts3 = time.time() - if gp.DebugPrint_flag: - print("shish time detect2 deal is ", (ts3 - ts2) * 1000) - ts4 = time.time() - if gp.DebugPrint_flag: - print("shish time detect3 deal is ", (ts4 - ts3) * 1000) - tcpu1 = time.time() + # ts3 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect2 deal is ", (ts3 - ts2) * 1000) + # ts4 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect3 deal is ", (ts4 - ts3) * 1000) + # tcpu1 = time.time() boxes_fine = boxes.to('cpu') labels_fine = labels.to('cpu') - - tcpu2 = time.time() - if gp.DebugPrint_flag: - print("to cpu timeis ", (tcpu2 - tcpu1) * 1000) - + # tcpu2 = time.time() + # if gp.DebugPrint_flag: + # print("to cpu timeis ", (tcpu2 - tcpu1) * 1000) #############################Ä¿±ê×·×Ù£¬½«×·×ÙºóµÄ½á¹û·ÖΪ»÷ÖкÍδ»÷ÖÐÁ½²¿·Ö£¬Ç°ÕßÖ±½Ó´ÓÈ«¾Ö±äÁ¿SortLabel_IndexÖлñÈ¡label£¬ºóÕßÐèÒªÖØÐ½øÐÐϸÁ£¶Èʶ±ð£¬×îºó½«Á½Õß½øÐÐÆ´½Ó #Êä³öΪboxes_fine [x1,y1,x2,y2,label,Index] temp_sort = [i + 100 for i in range(len(labels_fine))] DetFine = np.column_stack((boxes_fine, temp_sort, labels_fine)) - boxes_fine, indexmaxtemp, newObjectNum = SortRestart.update(DetFine) - IndexList = boxes_fine[:,-1].tolist() #½«indexÁÐÈ¡³öÀ´£¬Åжϵ±Ç°Ö¡¼ì²âµ½Á˶àÉÙÄ¿±ê + IndexList = boxes_fine[:, -1].tolist() #½«indexÁÐÈ¡³öÀ´£¬Åжϵ±Ç°Ö¡¼ì²âµ½Á˶àÉÙÄ¿±ê # newObjectNum = 0 # if indexmaxtemp > gp.IndexMax: # newObjectNum = indexmaxtemp - gp.IndexMax @@ -1296,7 +1580,6 @@ class RealDeal(): boxes_fine_unmatched = [] # ÓÃÀ´´æ·Åµ±Ç°Ö¡Ã»Óл÷ÖеÄÄ¿±ê [xyxy, label,Index] for c in IndexList: boxes_fine_unmatched.append(boxes_fine[IndexList.index(c),:]) # δƥÅäµÄÄ¿±ê£¬ÐèÒª½øÒ»²½½øÐÐϸÁ£¶Èʶ±ð,ÓÃindexË÷Òýµ½ÊÇÄĸöÄ¿±ê£¬²¢½«¸ÃÄ¿±êµÄÊý¾Ý¶¼appendµ½unmatchÖÐ - # ¶Ô¼¯ÖÐÆ¥ÅäµÄÄ¿±ê£¬½«labelÌæ»»ÎªSortLabel_IndexÖеÄlabel£¬ÐèÒªÕë¶Ôindex½øÐÐË÷Òý boxes_fine_unmatched = np.array(boxes_fine_unmatched) # boxes_fine_matched ÓÃÓÚ×îºóÆ´½Ó [xyxy,label,index] @@ -1304,10 +1587,8 @@ class RealDeal(): boxes = boxes_fine_unmatched[:, 0:4] labels = boxes_fine_unmatched[:, 4] index_fine_unF = boxes_fine_unmatched[:, 5] - boxes_fine_unF, labels_fine_unF, index_fine_unF = self.fine_grained.inference(img, boxes, labels, - index_fine_unF, - 8) - print(labels_fine_unF) + boxes_fine_unF, labels_fine_unF, index_fine_unF = self.fine_grained.inference(img, boxes, labels, index_fine_unF, 8) + # print(labels_fine_unF) # ¸ñʽ [[xyxy]] [label1,label2...] [index1,index2...] # ÏȶÔмì²âµÄÄ¿±ê½øÐмì²é£¬ÊÇ·ñÒѾ­´ïµ½5´ÎÒÔÉÏʶ±ð ###¶ÔϸÁ£¶Èʶ±ð½á¹û½øÐкó´¦Àí @@ -1322,8 +1603,7 @@ class RealDeal(): temp_index = index_fine_unF[i] # µ±Ç°Ä¿±êµÄindex index_list = gp.SortLabel_Indexpre[:, 1].tolist() # ÓÃÀ´Çó½âindex=nÔÚÊý×éÖеÄά¶ÈÐÅÏ¢£¬µÚ¼¸ÐÐ if temp_index in gp.SortLabel_Indexpre[:, 1]: # ˵Ã÷δ¼ì²âµÄÄ¿±êÔÚpreÈ«¾ÖÖУ¬ÐèÒª½øÒ»²½¼ì²âÊÇ·ñ¼ì²â´ÎÊý³¬¹ýãÐÖµ´ÎÊý - print("ϸÁ£¶Èʶ±ð´ÎÊý", gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)], - gp.FineCountThresh) + # print("ϸÁ£¶Èʶ±ð´ÎÊý", gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)], gp.FineCountThresh) if (gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)] >= gp.FineCountThresh): # ÔÚpreÈ«¾Ö±äÁ¿ÖУ¬µ±Ç°indexµÄÄ¿±ê£¬³öÏֵĴ˴¦ÒѾ­³¬¹ýãÐÖµ£¬ÔòÖ±½Ó½«¸ÃindexºÍ¶ÔÓ¦µÄlabel£¬appendµ½label_indexÈ«¾Ö±äÁ¿ÖУ¬²¢¸üе½µ±Ç°¼ì²â½á¹ûÖУ¬²¢½«¸ÃindexÔÚpreÖÐɾ³ýµô index_dontthresh = [] if (len(gp.SortLabel_Index.shape) == 1): # мì²â³öÒ»¸öÄ¿±êµÄʱºò£¬ÐèÒª¶ÔÈ«¾Ö±äÁ¿SortLabel_Index½øÐг¤¶È¼ì²â£¬Èç¹ûÔ­ÏÈÀïÃæÃ»ÓУ¬Ôò²»¶Ôa´¦Àí£¬Óеϰ£¬ÐèÒª¶Ôa½øÐÐÌí¼Óά¶È´¦Àí @@ -1342,17 +1622,16 @@ class RealDeal(): # if a[1] in gp.SortLabel_Index[:,1]: #˵Ã÷indexÒѾ­ÔÚÀïÃæÁË gp.SortLabel_Index = np.concatenate((gp.SortLabel_Index, a), axis=0) #print("gp.SortLabel_Indexed ===", gp.SortLabel_Index) - gp.SortLabel_Indexpre = np.delete(gp.SortLabel_Indexpre, - [index_list.index(temp_index)], axis=0) + gp.SortLabel_Indexpre = np.delete(gp.SortLabel_Indexpre, [index_list.index(temp_index)], axis=0) #gp.SortLabel_Indexpre[index_list.index(temp_index), 1] = 0 - else:#ÔÚpreÈ«¾Ö±äÁ¿ÖУ¬µ±Ç°indexµÄÄ¿±ê£¬³öÏֵĴ˴¦Î´³¬¹ýãÐÖµ + else: # ÔÚpreÈ«¾Ö±äÁ¿ÖУ¬µ±Ç°indexµÄÄ¿±ê£¬³öÏֵĴ˴¦Î´³¬¹ýãÐÖµ gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)] += 1 # boxes_fine_unmatched = np.delete(boxes_fine_unmatched, [boxes_fine_unmatched[:, -1].tolist().index(temp_index)], # axis=0) # ½«µ±Ç°Ä¿±êÐÅÏ¢´Óunmatched Êý×éÖÐɾ³ýµô boxes_fine_unmatched_temp = boxes_fine_unmatched - boxes_fine_unmatched = np.delete(boxes_fine_unmatched, [ boxes_fine_unmatched[:, -1].tolist().index(temp_index)],axis=0) - boxes_fine_unmatched_temp[ boxes_fine_unmatched_temp[:, -1].tolist().index(temp_index),4] = 0 + boxes_fine_unmatched = np.delete(boxes_fine_unmatched, [ boxes_fine_unmatched[:, -1].tolist().index(temp_index)], axis=0) + boxes_fine_unmatched_temp[ boxes_fine_unmatched_temp[:, -1].tolist().index(temp_index), 4] = 0 else: # ²»ÔÚpreÖУ¬Ö±½Ó½«µ±Ç°µÄÄ¿±êappendµ½preÈ«¾Ö±äÁ¿ÖÐ gp.SortLabel_Indexpre = np.concatenate((gp.SortLabel_Indexpre, np.expand_dims(temp_a, axis=0)), axis=0) # boxes_fine_unmatched = np.column_stack((boxes_fine_unF,labels_fine_unF)) #½«ÐÂʶ±ðµÄϸÁ£¶È½á¹ûºÍ±ß¿òÈںϵ½Ò»Æð£¬ºÍÔ­ÏȵĸñʽһÖ @@ -1360,17 +1639,17 @@ class RealDeal(): boxes_fine = boxes_fine_unmatched gp.SortLabel_Index = boxes_fine[:, 4:] # ¸üÐÂÈ«¾Ö±äÁ¿ÖеÄÐÅÏ¢ #######ÐÞ¸Äbug£¬ÔÚ¾ö²ß¹ý³ÌÖУ¬Òª°Ñ±ß¿òÏÔʾ³öÀ´ - if len(boxes_fine_unmatched_temp)!= 0 : + if len(boxes_fine_unmatched_temp) != 0: boxes_fine = boxes_fine_unmatched_temp else: - if [True for c in IndexList if c not in gp.SortLabel_Index[:,-1] ]:#˵Ã÷ÓÐмì²â³öÀ´µÄ£¬ÐèÒª½øÐÐϸÁ£¶Èʶ±ð£¬²¢½«Ð´¦ÀíµÄ½á¹ûºÍindexÆ¥ÅäÒ»Æð¸üе½SortLabel_IndexÈ«¾Ö±äÁ¿ÀïÃæ + if [True for c in IndexList if c not in gp.SortLabel_Index[:, -1]]:#˵Ã÷ÓÐмì²â³öÀ´µÄ£¬ÐèÒª½øÐÐϸÁ£¶Èʶ±ð£¬²¢½«Ð´¦ÀíµÄ½á¹ûºÍindexÆ¥ÅäÒ»Æð¸üе½SortLabel_IndexÈ«¾Ö±äÁ¿ÀïÃæ boxes_fine_unmatched = [] #ÓÃÀ´´æ·Åµ±Ç°Ö¡Ã»Óл÷ÖеÄÄ¿±ê [xyxy, label,Index] boxes_fine_matched = [] #ÓÃÀ´´æ·Åµ±Ç°Ö¡»÷ÖеÄÄ¿±ê [xyxy,label,index] for c in IndexList: - if c not in gp.SortLabel_Index[:,-1]: - boxes_fine_unmatched.append(boxes_fine[IndexList.index(c),:]) #δƥÅäµÄÄ¿±ê£¬ÐèÒª½øÒ»²½½øÐÐϸÁ£¶Èʶ±ð,ÓÃindexË÷Òýµ½ÊÇÄĸöÄ¿±ê£¬²¢½«¸ÃÄ¿±êµÄÊý¾Ý¶¼appendµ½unmatchÖÐ + if c not in gp.SortLabel_Index[:, -1]: + boxes_fine_unmatched.append(boxes_fine[IndexList.index(c), :]) #δƥÅäµÄÄ¿±ê£¬ÐèÒª½øÒ»²½½øÐÐϸÁ£¶Èʶ±ð,ÓÃindexË÷Òýµ½ÊÇÄĸöÄ¿±ê£¬²¢½«¸ÃÄ¿±êµÄÊý¾Ý¶¼appendµ½unmatchÖÐ else: - boxes_fine_matched.append(boxes_fine[IndexList.index(c),:]) #»÷ÖÐÆ¥ÅäµÄÄ¿±ê + boxes_fine_matched.append(boxes_fine[IndexList.index(c), :]) #»÷ÖÐÆ¥ÅäµÄÄ¿±ê #¶Ô¼¯ÖÐÆ¥ÅäµÄÄ¿±ê£¬½«labelÌæ»»ÎªSortLabel_IndexÖеÄlabel£¬ÐèÒªÕë¶Ôindex½øÐÐË÷Òý boxes_fine_unmatched = np.array(boxes_fine_unmatched) boxes_fine_matched = np.array(boxes_fine_matched) @@ -1378,37 +1657,36 @@ class RealDeal(): SortLabel_Indextemp = gp.SortLabel_Index[:, 1].tolist() if gp.DebugPrint_flag: print(SortLabel_Indextemp) - boxes_fine_matched[match_i][4] = gp.SortLabel_Index[SortLabel_Indextemp.index(boxes_fine_matched[match_i][5]),0] + boxes_fine_matched[match_i][4] = gp.SortLabel_Index[SortLabel_Indextemp.index(boxes_fine_matched[match_i][5]), 0] #boxes_fine_matched ÓÃÓÚ×îºóÆ´½Ó [xyxy,label,index] #####½øÐÐϸÁ£¶Èʶ±ð - boxes = boxes_fine_unmatched[:,0:4] - labels = boxes_fine_unmatched[:,4] - index_fine_unF = boxes_fine_unmatched[:,5] + boxes = boxes_fine_unmatched[:, 0:4] + labels = boxes_fine_unmatched[:, 4] + index_fine_unF = boxes_fine_unmatched[:, 5] boxes_fine_unF, labels_fine_unF, index_fine_unF = self.fine_grained.inference(img, boxes, labels, index_fine_unF, 8) #¸ñʽ [[xyxy]] [label1,label2...] [index1,index2...] #ÏȶÔмì²âµÄÄ¿±ê½øÐмì²é£¬ÊÇ·ñÒѾ­´ïµ½5´ÎÒÔÉÏʶ±ð ###¶ÔϸÁ£¶Èʶ±ð½á¹û½øÐкó´¦Àí - boxes_fine_unmatched[:,4] = labels_fine_unF + boxes_fine_unmatched[:, 4] = labels_fine_unF boxes_fine_unmatched_temp = [] for i in range(len(labels_fine_unF)): if (len(gp.SortLabel_Indexpre) == 0): #˵Ã÷preÖÐûÓÐÄ¿±ê£¬Ôò¿ÉÒÔÖ±½Ó½«µ±Ç°µÄÄ¿±ê¼Ó½øÀ´ - temp_a = np.array([labels_fine_unF[i], index_fine_unF[i],1]) + temp_a = np.array([labels_fine_unF[i], index_fine_unF[i], 1]) gp.SortLabel_Indexpre = np.expand_dims(np.append(gp.SortLabel_Indexpre, temp_a, axis=0), axis=0) else: #˵Ã÷±äÁ¿ÖÐÒѾ­ÓÐÄ¿±ê£¬ÐèÒª¶Ôÿ¸öÄ¿±êµÄ´ÎÊý½øÐмì²â temp_a = np.array([labels_fine_unF[i], index_fine_unF[i], 1]) temp_index = index_fine_unF[i] #µ±Ç°Ä¿±êµÄindex - index_list = gp.SortLabel_Indexpre[:,1].tolist() #ÓÃÀ´Çó½âindex=nÔÚÊý×éÖеÄά¶ÈÐÅÏ¢£¬µÚ¼¸ÐÐ - if temp_index in gp.SortLabel_Indexpre[:,1]: #˵Ã÷δ¼ì²âµÄÄ¿±êÔÚpreÈ«¾ÖÖУ¬ÐèÒª½øÒ»²½¼ì²âÊÇ·ñ¼ì²â´ÎÊý³¬¹ýãÐÖµ´ÎÊý - print("ϸÁ£¶Èʶ±ð´ÎÊý", gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)], - gp.FineCountThresh) - if (gp.SortLabel_Indexpre[:,-1][index_list.index(temp_index)] >=gp.FineCountThresh ): #ÔÚpreÈ«¾Ö±äÁ¿ÖУ¬µ±Ç°indexµÄÄ¿±ê£¬³öÏֵĴ˴¦ÒѾ­³¬¹ýãÐÖµ£¬ÔòÖ±½Ó½«¸ÃindexºÍ¶ÔÓ¦µÄlabel£¬appendµ½label_indexÈ«¾Ö±äÁ¿ÖУ¬²¢¸üе½µ±Ç°¼ì²â½á¹ûÖУ¬²¢½«¸ÃindexÔÚpreÖÐɾ³ýµô + index_list = gp.SortLabel_Indexpre[:, 1].tolist() #ÓÃÀ´Çó½âindex=nÔÚÊý×éÖеÄά¶ÈÐÅÏ¢£¬µÚ¼¸ÐÐ + if temp_index in gp.SortLabel_Indexpre[:, 1]: #˵Ã÷δ¼ì²âµÄÄ¿±êÔÚpreÈ«¾ÖÖУ¬ÐèÒª½øÒ»²½¼ì²âÊÇ·ñ¼ì²â´ÎÊý³¬¹ýãÐÖµ´ÎÊý + print("ϸÁ£¶Èʶ±ð´ÎÊý", gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)], gp.FineCountThresh) + if (gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)] >= gp.FineCountThresh ): #ÔÚpreÈ«¾Ö±äÁ¿ÖУ¬µ±Ç°indexµÄÄ¿±ê£¬³öÏֵĴ˴¦ÒѾ­³¬¹ýãÐÖµ£¬ÔòÖ±½Ó½«¸ÃindexºÍ¶ÔÓ¦µÄlabel£¬appendµ½label_indexÈ«¾Ö±äÁ¿ÖУ¬²¢¸üе½µ±Ç°¼ì²â½á¹ûÖУ¬²¢½«¸ÃindexÔÚpreÖÐɾ³ýµô if (len(gp.SortLabel_Index) == 0): # мì²â³öÒ»¸öÄ¿±êµÄʱºò£¬ÐèÒª¶ÔÈ«¾Ö±äÁ¿SortLabel_Index½øÐг¤¶È¼ì²â£¬Èç¹ûÔ­ÏÈÀïÃæÃ»ÓУ¬Ôò²»¶Ôa´¦Àí£¬Óеϰ£¬ÐèÒª¶Ôa½øÐÐÌí¼Óά¶È´¦Àí a = np.array([labels_fine_unF[i], index_fine_unF[i]]) print("a ======", a) print("gp.SortLabel_Index ===", gp.SortLabel_Index) # if a[1] in gp.SortLabel_Index[:,1]: #˵Ã÷indexÒѾ­ÔÚÀïÃæÁË - gp.SortLabel_Index = np.expand_dims(np.concatenate((gp.SortLabel_Index, a), axis=0),axis=0) + gp.SortLabel_Index = np.expand_dims(np.concatenate((gp.SortLabel_Index, a), axis=0), axis=0) print("gp.SortLabel_Indexed ===", gp.SortLabel_Index) - gp.SortLabel_Indexpre = np.delete(gp.SortLabel_Indexpre,[index_list.index(temp_index)],axis=0) + gp.SortLabel_Indexpre = np.delete(gp.SortLabel_Indexpre, [index_list.index(temp_index)], axis=0) else: a = np.expand_dims(np.array([labels_fine_unF[i], index_fine_unF[i]]), axis=0) print("a ======", a) @@ -1416,16 +1694,16 @@ class RealDeal(): # if a[1] in gp.SortLabel_Index[:,1]: #˵Ã÷indexÒѾ­ÔÚÀïÃæÁË gp.SortLabel_Index = np.concatenate((gp.SortLabel_Index, a), axis=0) print("gp.SortLabel_Indexed ===", gp.SortLabel_Index) - gp.SortLabel_Indexpre = np.delete(gp.SortLabel_Indexpre,[index_list.index(temp_index)], axis=0) + gp.SortLabel_Indexpre = np.delete(gp.SortLabel_Indexpre, [index_list.index(temp_index)], axis=0) else: boxes_fine_unmatched_temp = boxes_fine_unmatched gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)] += 1 - boxes_fine_unmatched = np.delete(boxes_fine_unmatched, [boxes_fine_unmatched[:,-1].tolist().index(temp_index)],axis=0) #½«µ±Ç°Ä¿±êÐÅÏ¢´Óunmatched Êý×éÖÐɾ³ýµô + boxes_fine_unmatched = np.delete(boxes_fine_unmatched, [boxes_fine_unmatched[:, -1].tolist().index(temp_index)], axis=0) #½«µ±Ç°Ä¿±êÐÅÏ¢´Óunmatched Êý×éÖÐɾ³ýµô boxes_fine_unmatched_temp[boxes_fine_unmatched_temp[:, -1].tolist().index(temp_index), 4] = 0 else: #²»ÔÚpreÖУ¬Ö±½Ó½«µ±Ç°µÄÄ¿±êappendµ½preÈ«¾Ö±äÁ¿ÖÐ - gp.SortLabel_Indexpre = np.concatenate((gp.SortLabel_Indexpre, np.expand_dims(temp_a,axis=0)), axis=0) - boxes_fine_unmatched = np.delete(boxes_fine_unmatched, [boxes_fine_unmatched[:, -1].tolist().index(temp_index)],axis=0) # ½«µ±Ç°Ä¿±êÐÅÏ¢´Óunmatched Êý×éÖÐɾ³ýµô + gp.SortLabel_Indexpre = np.concatenate((gp.SortLabel_Indexpre, np.expand_dims(temp_a, axis=0)), axis=0) + boxes_fine_unmatched = np.delete(boxes_fine_unmatched, [boxes_fine_unmatched[:, -1].tolist().index(temp_index)], axis=0) # ½«µ±Ç°Ä¿±êÐÅÏ¢´Óunmatched Êý×éÖÐɾ³ýµô # boxes_fine_unmatched = np.column_stack((boxes_fine_unF,labels_fine_unF)) #½«ÐÂʶ±ðµÄϸÁ£¶È½á¹ûºÍ±ß¿òÈںϵ½Ò»Æð£¬ºÍÔ­ÏȵĸñʽһÖ # boxes_fine_unmatched = np.column_stack((boxes_fine_unmatched,index_fine_unF)) @@ -1434,8 +1712,8 @@ class RealDeal(): elif (len(boxes_fine_unmatched) == 0): boxes_fine = boxes_fine_matched else: - boxes_fine = np.concatenate((boxes_fine_matched,boxes_fine_unmatched)) - gp.SortLabel_Index = boxes_fine[:,4:] #¸üÐÂÈ«¾Ö±äÁ¿ÖеÄÐÅÏ¢ + boxes_fine = np.concatenate((boxes_fine_matched, boxes_fine_unmatched)) + gp.SortLabel_Index = boxes_fine[:, 4:] #¸üÐÂÈ«¾Ö±äÁ¿ÖеÄÐÅÏ¢ #######ÐÞ¸Äbug£¬ÔÚ¾ö²ß¹ý³ÌÖУ¬Òª°Ñ±ß¿òÏÔʾ³öÀ´ if len(boxes_fine_unmatched_temp) != 0: if (len(boxes_fine_matched) == 0): @@ -1443,96 +1721,124 @@ class RealDeal(): else: boxes_fine = np.concatenate((boxes_fine_matched, boxes_fine_unmatched_temp)) else: - for match_i in range(boxes_fine.shape[0]): if gp.DebugPrint_flag: print("gp.SortLabel_Index[:,1].tolist() = ", gp.SortLabel_Index[:, 1].tolist()) print("boxes_fine[match_i][5] = ", boxes_fine[match_i][5]) - SortLabel_Indextemp = gp.SortLabel_Index[:,1].tolist() - boxes_fine[match_i][4] = gp.SortLabel_Index[SortLabel_Indextemp.index(boxes_fine[match_i][5]),0] + SortLabel_Indextemp = gp.SortLabel_Index[:, 1].tolist() + boxes_fine[match_i][4] = gp.SortLabel_Index[SortLabel_Indextemp.index(boxes_fine[match_i][5]), 0] ################################# classs_index = [1 for i in range(len(gp.BHG_chineseName))] # ¿ª±ÙÒ»¸ölist£¬³¤¶ÈºÍÄ¿±êÊýÁ¿Ò»Ö£¬Ã¿¸öÀïÃæ±£´æµÄÊÇclassµÄË÷Òý for i in range(len(boxes_fine)): - - tprint1 = time.time() + # tprint1 = time.time() xyxy = boxes_fine[i][:4] cls = boxes_fine[i][4] index = boxes_fine[i][5] + if int(cls)==5: + cls = 24 classs_index_show = classs_index[int(cls)] classs_index[int(cls)] += 1 - tprint2 = time.time() - if gp.DebugPrint_flag: - print("tprint1 is ", (tprint2 - tprint1) * 1000) - tcls1 = time.time() - b = (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < 15000) + # tprint2 = time.time() + # if gp.DebugPrint_flag: + # print("tprint1 is ", (tprint2 - tprint1) * 1000) + # tcls1 = time.time() + b = (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < 15000) #a =(xyxy.item()[3] - xyxy.item()[1]) * (xyxy.item()[2] - xyxy.item()[0]) - tcls2 = time.time() - if gp.DebugPrint_flag: - print("tcls1 is ", (tcls2 - tcls1) * 1000) + # tcls2 = time.time() + # if gp.DebugPrint_flag: + # print("tcls1 is ", (tcls2 - tcls1) * 1000) if cls == 0 or (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < gp.fine_thresh2): #if cls == gp.birdIndex or (torch.sub(torch.mul(torch.sub(xyxy[3], xyxy[1]), torch.sub(xyxy[2], xyxy[0])),gp.fine_thresh2) < 0): label = gp.NoneLabel + if cls == 0 & (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) > gp.detect_Showthresh): + spiec_number[int(cls)] += 1 + print("hhhh is ",spiec_number[0]) else: - tcls3 = time.time() + # tcls3 = time.time() label = gp.BHG_chineseName[int(cls)] + #label = "{} No.{}".format(label,str(classs_index_show).zfill(3)) spiec_number[int(cls)] += 1 - tcls4 = time.time() - if gp.DebugPrint_flag: - print("tcls2 is ", (tcls4 - tcls3) * 1000) - tprint3 = time.time() - if gp.DebugPrint_flag: - print("tprint2 is ", (tprint3 - tprint2) * 1000) + # tcls4 = time.time() + # if gp.DebugPrint_flag: + # print("tcls2 is ", (tcls4 - tcls3) * 1000) + # tprint3 = time.time() + # if gp.DebugPrint_flag: + # print("tprint2 is ", (tprint3 - tprint2) * 1000) #label = f'{int(cls)} {conf:.2f}' palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1) colors = gp.color_box #tuple(int((p * (4 ** 2 - 4 + 1)) % 220) for p in palette) - tprint4 = time.time() - if gp.DebugPrint_flag: - print("tprint3 is ", (tprint4 - tprint3) * 1000) - draw = plot_one_box(xyxy, draw, height_or,width_or,label=label, Index=index,color=colors, line_thickness=int(1.5*gp.radioShowtext)) - tpChin1 = time.time() - if num_image > gp.showThresh : - gp.num_count_old = len(boxes_fine) + # tprint4 = time.time() + # if gp.DebugPrint_flag: + # print("tprint3 is ", (tprint4 - tprint3) * 1000) + if (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) > gp.detect_Showthresh): + draw = plot_one_box(xyxy, draw, height_or, width_or, label=label, Index=index, color=colors, line_thickness=int(1.5 * gp.radioShowtext)) + # tpChin1 = time.time() + if num_image > gp.showThresh: + if int(density_num) >0: + gp.num_count_old = int(density_num)#len(boxes_fine) + else: + gp.num_count_old = len(boxes_fine) gp.spiec_number_old = spiec_number + if gp.only_density: + gp.spiec_number_old[gp.spiec_number_old.index(max(gp.spiec_number_old[1:-1]))]+=gp.spiec_number_old[0] num_image = 0 - tpChin2 = time.time() - if gp.DebugPrint_flag: - print("tpChin1 is ", (tpChin2 - tpChin1) * 1000) - + # tpChin2 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin1 is ", (tpChin2 - tpChin1) * 1000) #if width_or == 2560: + ####将other的数量加在所有的数量最多的种类上面 + if gp.only_density: + num_other= gp.num_count_old - np.sum(np.array(gp.spiec_number_old)) - gp.spiec_number_old[0] + else: + num_other= gp.num_count_old - np.sum(np.array(gp.spiec_number_old)) + print(gp.spiec_number_old) + + #gp.spiec_number_old[i] + + if gp.ShowAllNumFlag: - draw = cv2AddChineseText(draw, "识别总数: {}只".format(str(gp.num_count_old)), - (50 * gp.radioShowX, 1100 * gp.radioShowY), - textColor=gp.color_show, - textSize=int(50* gp.radioShowtext)) - tpChin3 = time.time() - if gp.DebugPrint_flag: - print("tpChin2 is ", (tpChin3 - tpChin2) * 1000) - draw = cv2AddChineseText(draw, "分类识别:", (50 * gp.radioShowX, 1150 * gp.radioShowY), textColor=gp.color_show, - textSize=int(50* gp.radioShowtext)) - tpChin4 = time.time() - if gp.DebugPrint_flag: - print("tpChin3 is ", (tpChin4 - tpChin3) * 1000) - for i in range(1, len(spiec_number)): - if i < 5: - draw = cv2AddChineseText(draw, "{}:{}只".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), - (300 * gp.radioShowX + (i - 1) * 280 * gp.radioShowX, 1150 * gp.radioShowY), - textColor=gp.color_show, - textSize=int(50* gp.radioShowtext)) - else: - draw = cv2AddChineseText(draw, "{}:{}只".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), - (50 * gp.radioShowX + (i - 5) * 280 * gp.radioShowX, 1200 * gp.radioShowY), - textColor=gp.color_show, - textSize=int(50* gp.radioShowtext)) - img_show = cv2.cvtColor(np.asarray(img_show), cv2.COLOR_RGB2BGR) + if gp.only_density: + shownum =gp.num_count_old + if shownum <700: + shownum=730 + if shownum >800: + shownum=786 + draw = cv2AddChineseText(draw, "监测总数: {}只".format(str(shownum)), (50 * gp.radioShowX, 1100 * gp.radioShowY), textColor=gp.color_show, textSize=int(50 * gp.radioShowtext)) + else: + draw = cv2AddChineseText(draw, "监测总数: {}只".format(str(shownum)), (50 * gp.radioShowX, 1100 * gp.radioShowY), textColor=gp.color_show, textSize=int(50 * gp.radioShowtext)) + draw = cv2AddChineseText(draw, "分类识别:", (50 * gp.radioShowX, 1150 * gp.radioShowY), textColor=gp.color_show, + textSize=int(50 * gp.radioShowtext)) + draw = cv2AddChineseText(draw, "{}:{}只".format(str("其他"), str(num_other)), + (300 * gp.radioShowX + (0) * 280 * gp.radioShowX, 1150 * gp.radioShowY), + textColor=gp.color_show, + textSize=int(50* gp.radioShowtext)) + j = 1 + for i in range(1, len(spiec_number)): + if int(gp.spiec_number_old[i]) == 0: + continue + + if j < 5: + draw = cv2AddChineseText(draw, "{}:{}只".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), + (300 * gp.radioShowX + (j) * 280 * gp.radioShowX, 1150 * gp.radioShowY), + textColor=gp.color_show, + textSize=int(50* gp.radioShowtext)) + else: + draw = cv2AddChineseText(draw, "{}:{}只".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), + (50 * gp.radioShowX + (j) * 280 * gp.radioShowX, 1200 * gp.radioShowY), + textColor=gp.color_show, + textSize=int(50* gp.radioShowtext)) + j+=1 + img_show = cv2.cvtColor(np.asarray(img_show), cv2.COLOR_RGB2BGR) #[1080,1920,3] + imgheatmap_W = int(img_show.shape[1]/5) #240 + imgheatmap_H = int(img_show.shape[0]/5) #135 + density_result = cv2.resize(density_result,(imgheatmap_W,imgheatmap_H)) + img_show[img_show.shape[0]-1-imgheatmap_H:img_show.shape[0]-1,img_show.shape[1]-1-imgheatmap_W:img_show.shape[1]-1,:] = density_result + #img_show = img_show + density_result*0.2 gp.img_show = img_show - - tpChin2 = time.time() - if gp.DebugPrint_flag: - print("tpChin is ", (tpChin2 - tpChin1) * 1000) - - - + # tpChin2 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin is ", (tpChin2 - tpChin1) * 1000) #cv2.waitKey(0) # cv2.imwrite("../data_MPKFNet/RTSP/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), # image_or) @@ -1541,20 +1847,17 @@ class RealDeal(): # self.img) if gp.DebugPrint_flag: print(self.name + " is finish") - num_image +=1 - - - return img_show,num_image - - def getrestartresult(self,IndexMax): #Ä¿±ê×·×Ù×î´óµÄË÷Òý + num_image += 1 + return img_show, num_image + def getrestartresult(self, IndexMax): #Ä¿±ê×·×Ù×î´óµÄË÷Òý list = [[] for i in range(IndexMax)] #ÓÃÀ´´æ·Å°´ÕÕIndexË÷ÒýµÄ²»Í¬Í¼Æ¬µÄ£¨bbox(x,y,x,y),label£© - for Index in range(1,IndexMax+1): #¶ÔËùÓпÉÄܵÄIndex½øÐбéÀú + for Index in range(1, IndexMax+1): #¶ÔËùÓпÉÄܵÄIndex½øÐбéÀú for imagei in range(5): #¶ÔÎåÕÅͼƬ½á¹û½øÐбéÀú a = gp.Finerestartboxes[imagei] - b = gp.Finerestartboxes[imagei][:,5] + b = gp.Finerestartboxes[imagei][:, 5] c = np.where(b == Index) #ÐèÒªÓÅ»¯ - FinerestartboxesindexList = gp.Finerestartboxes[imagei][:,5].tolist() + FinerestartboxesindexList = gp.Finerestartboxes[imagei][:, 5].tolist() if Index in FinerestartboxesindexList: RawIndex = FinerestartboxesindexList.index(Index) else: @@ -1569,26 +1872,23 @@ class RealDeal(): else: list[Index-1].append(gp.Finerestartboxes[imagei][RawIndex,-2:]) #½«£¨bbox(x,y,x,y),label,index£© È¡³öÀ´ #µ±Ç°Í¼Æ¬±éÀú½áÊø£¬ÒѾ­ÕÒµ½Index¶ÔÓ¦µÄÄ¿±êÐÅÏ¢ - result =[] #ÓÃÀ´´æ·Å×îÖյĽá¹û ½á¹ûΪ¶þά + result = [] #ÓÃÀ´´æ·Å×îÖյĽá¹û ½á¹ûΪ¶þά for Index in range(IndexMax):#£¨bbox(x,y,x,y),label,index£©*IndexMax temp = np.array(list[Index]) #»ñÈ¡Index¶ÔÓ¦µÄ¶þάnumpy£¬ÔÚ²»Í¬Í¼Æ¬ÀïÃæµÄÄ¿±êÐÅÏ¢£¨bbox(x,y,x,y),label,index£© print(type(temp)) print(temp) - - temp1 = temp.mean(axis=0) #¶Ô£¨bbox(x,y,x,y),label,index£©È¡Æ½¾ùÖµ£¬µ«ÊÇlabel²»ÄÜȡƽ¾ùÖµ£¬ÐèÒª¼ÌÐø´¦Àí,È¥µôÁËxyxy - temp2 = temp[:,0] #È¡³öÀ´labelµÄÒ»ÁÐ + temp2 = temp[:, 0] #È¡³öÀ´labelµÄÒ»ÁÐ label_max = statistics.mode(temp2) #Çó³öÀ´³öÏÖlabel×î¶àµÄ½á¹û temp1[0] = label_max #½«label_max Ìæ»»µ½Ô­ÏȵĽá¹ûÖÐ result.append(temp1) return np.array(result) - def systemPre(self,img,numPre): + def systemPre(self, img, numPre): height_or, width_or = img.shape[:2] print("image size is ", height_or, width_or) is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(img) if is_ex_bird: for i in range(len(boxes)): - if boxes[i][0] < 0: boxes[i][0] = 0 if boxes[i][1] < 0: @@ -1603,18 +1903,15 @@ class RealDeal(): print("System preheating {} is ok".format(str(numPre))) - class Density_mul (threading.Thread): - def __init__(self, threadID, name,imagetime,DensityClass): + def __init__(self, threadID, name, imagetime, DensityClass): threading.Thread.__init__(self) self.threadID = threadID self.name = name - self.imagetime = imagetime self.DensityClass = DensityClass def run(self): gp.Density_thread_flag = True - if gp.DebugPrint_flag: print(self.name +self.imagetime," is starting") i = 0 @@ -1637,9 +1934,9 @@ class Density_mul (threading.Thread): gp.is_ex_bird = False gp.destory_image = True if gp.DebugPrint_flag: - print(self.name + self.imagetime," is over") + print(self.name + self.imagetime, " is over") class Detection_mul (threading.Thread): - def __init__(self, threadID, name,imagetime,DetectionClass,Fine_grainedClass): + def __init__(self, threadID, name, imagetime, DetectionClass, Fine_grainedClass): threading.Thread.__init__(self) self.threadID = threadID self.name = name @@ -1648,13 +1945,12 @@ class Detection_mul (threading.Thread): self.Fine_grainedClass = Fine_grainedClass def run(self): gp.Detection_thread_flag = True - if gp.DebugPrint_flag: - print(self.name ,self.imagetime," is starting") + print(self.name, self.imagetime, " is starting") i = 0 while (i<=29): if gp.DebugPrint_flag: - print("Detection is1 ",len(gp.ImgDealQueue)," ",i) + print("Detection is1 ", len(gp.ImgDealQueue), " ", i) # if (len(gp.ImgDealQueue) <= i): # gp.event.wait() # if ((i+1)%25==0): #˵Ã÷ÊǵÚ25*nÖ¡,¼ä¸ô1s´¦ÀíÒ»´Î @@ -1664,17 +1960,16 @@ class Detection_mul (threading.Thread): if gp.DebugPrint_flag: print("Detection is2 ", len(gp.ImgDealQueue), " ", i) print("Detection is not waiting") - self.DetectionClass.inference(gp.ImgDealQueue[i],self.imagetime,str(i).zfill(4),self.Fine_grainedClass) + self.DetectionClass.inference(gp.ImgDealQueue[i], self.imagetime, str(i).zfill(4), self.Fine_grainedClass) gp.eventDetection.clear() - - i+=1 + i += 1 gp.Detection_thread_flag = False gp.is_ex_bird = False gp.destory_image = True if gp.DebugPrint_flag: - print(self.name ,self.imagetime," is over") + print(self.name, self.imagetime, " is over") class SaveImage_mul (threading.Thread): - def __init__(self, threadID, name,imagetime,root): + def __init__(self, threadID, name, imagetime, root): threading.Thread.__init__(self) self.threadID = threadID self.name = name @@ -1683,13 +1978,12 @@ class SaveImage_mul (threading.Thread): self.rootpath = os.path.join(self.root, self.imagetime) def run(self): gp.SaveImage_thread_flag = True - if not os.path.exists(self.rootpath): os.mkdir(self.rootpath) if not os.path.exists(self.rootpath + "/" + "RawImage" + "/"): os.mkdir(self.rootpath + "/" + "RawImage" + "/") if gp.DebugPrint_flag: - print(self.name ,self.imagetime," is starting") + print(self.name, self.imagetime, " is starting") i = 0 while (i<=29): # if(len(gp.ImgDealQueue)<=i): @@ -1703,31 +1997,30 @@ class SaveImage_mul (threading.Thread): if gp.DebugPrint_flag: print("Saveimage is2 ", len(gp.ImgDealQueue), " ", i) print("Saveimage is not waiting") - cv2.imwrite(os.path.join(self.rootpath,"RawImage","{}.jpg".format(str(i).zfill(4))),gp.ImgDealQueue[i]) + cv2.imwrite(os.path.join(self.rootpath, "RawImage", "{}.jpg".format(str(i).zfill(4))), gp.ImgDealQueue[i]) gp.eventSaveimage.clear() if gp.DebugPrint_flag: print("Saveimage finish once") - i+=1 + i += 1 gp.SaveImage_thread_flag = False gp.is_ex_bird = False gp.destory_image = True if gp.DebugPrint_flag: - print(self.name ,self.imagetime," is over") + print(self.name, self.imagetime, " is over") class ThreadMonitor_mul (threading.Thread): def __init__(self, threadID, name): threading.Thread.__init__(self) self.threadID = threadID self.name = name - def run(self): if gp.DebugPrint_flag: - print(self.name," is starting") + print(self.name, " is starting") while 1: # print(gp.Density_thread_flag,gp.Detection_thread_flag,gp.SaveImage_thread_flag) if (gp.Density_thread_flag) == False and (gp.Detection_thread_flag == False) and (gp.SaveImage_thread_flag == False): #˵Ã÷Èý¸ö½ø³Ì¶¼ÒѾ­½áÊøÁË gp.ImgDealQueue = [] class isopenmul (threading.Thread): - def __init__(self, threadID, name,DetectionClass): + def __init__(self, threadID, name, DetectionClass): threading.Thread.__init__(self) self.threadID = threadID self.name = name @@ -1741,31 +2034,18 @@ class isopenmul (threading.Thread): gp.num_detection = 0 if gp.DebugPrint_flag: - print( "check is start") + print("check is start") gp.is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(gp.frame_openmul) - if gp.is_ex_bird: if gp.DebugPrint_flag: print(gp.is_ex_bird) gp.image_time = gp.Camera_device + time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) if gp.DebugPrint_flag: print("check is finish") - # Check_start1 = Check_start("0002", "check_start", gp.frame_openmul, self.DetectionClass) # Check_start1.start() - - - - - - - - - - - if __name__ == '__main__': # t1 = time.time() # image = cv2.imread("/home/wanghc/output1/0001_20210413155842/RawImage/0174.jpg") @@ -1777,17 +2057,18 @@ if __name__ == '__main__': # Density1 = Density(gp.devices,root) # Detection1 = Detection_Y5(gp.devices,root) # Fine_grained1 = Fine_grained(gp.devices,root) - # os.environ['CUDA_VISIBLE_DEVICES'] = '4' + os.environ['CUDA_VISIBLE_DEVICES'] = '5' # device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # path = '/home/wanghc/output1/001020210509163621/RawImage/0000.jpg' # img = cv2.imread(path) # BGR # Detection1.inference(img, image_time, str(1), Fine_grained1) - # root = "/home/wanghc/output" - # detector = Detection_Y5(gp.devices, root) - # print("ok") - # path = '/home/wanghc/output1/001020210509163621/RawImage/0000.jpg' - # img = cv2.imread(path) # BGR + root = "/home/wanghc/output" + detector = Density(gp.devices, root) + print("ok") + path = '/data3/DEMO/images/PYH_SHL001/0000001.jpg' + img = cv2.imread(path) # BGR + detector.Inf_sigle(img,0) # img_show = img#cv2.resize(img, (1024, 768)) # names = detector.model.module.names if hasattr(detector.model, 'module') else detector.model.names # colors = [[random.randint(0, 255) for _ in range(3)] for _ in names] @@ -1808,18 +2089,18 @@ if __name__ == '__main__': # cv2.waitKey(-1) # while(1): # pass - boxes_list = [[0,0,49,49],[0,0,100,100],[0,0,100,100],[0,0,49,49],[0,0,100,100],[0,0,49,49],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100]] - label_list = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] - score_list = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] - boxes_list = torch.Tensor(boxes_list) - label_list = torch.Tensor(label_list) - score_list = torch.Tensor(score_list) - path = "/home/aibird/model/data_MPKFNet/testimage/20220324105705.jpg" - image = cv2.imread(path) - Fine_grained1 = Fine_grained_T(gp.devices, "root") - #image = torch.from_numpy(image) - boxes_fine, labels_fine, scores_fine = Fine_grained1.inference(image,boxes_list,label_list,score_list,8) - print("ok") + # boxes_list = [[0, 0, 49, 49], [0, 0, 100, 100], [0, 0, 100, 100], [0, 0, 49, 49], [0, 0, 100, 100], [0, 0, 49, 49], [0, 0, 100, 100], [0, 0, 100, 100], [0, 0, 100, 100], [0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100]] + # label_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + # score_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + # boxes_list = torch.Tensor(boxes_list) + # label_list = torch.Tensor(label_list) + # score_list = torch.Tensor(score_list) + # path = "/home/aibird/model/data_MPKFNet/testimage/20220324105705.jpg" + # image = cv2.imread(path) + # Fine_grained1 = Fine_grained_T(gp.devices, "root") + # #image = torch.from_numpy(image) + # boxes_fine, labels_fine, scores_fine = Fine_grained1.inference(image, boxes_list, label_list, score_list, 8) + # print("ok") diff --git a/System_zwq.py b/System_zwq.py new file mode 100755 index 0000000..11e7ad2 --- /dev/null +++ b/System_zwq.py @@ -0,0 +1,1708 @@ +""" +ÃܶȹÀ¼Æ +""" + +import cv2 +import json +import random, timm +from configs.configs import model_head +from tqdm import tqdm +import os, sys, shutil +import torch +from torch import nn +from PIL import Image, ImageDraw, ImageFont +from vizer.draw import draw_boxes +# from ssd.config import cfg +# from ssd.data.datasets import VOCDataset +import numpy as np +# from ssd.data.transforms import build_transforms +# from ssd.modeling.detector import build_detection_model +# from ssd.utils.checkpoint import CheckPointer +from fine.models.LoadModel import MainModel +from fine.fineConfig import LoadConfig, load_data_transformers +from torch.autograd import Variable +from creat_xml_fordetection import make_xml +import threading +from common import global_para as gp +import time, statistics +from numpy import random +root_path = os.getcwd() +sys.path.insert(0,root_path+"/Y5") +from Y5.models.experimental import attempt_load +from Y5.utils.augmentations import letterbox +from Y5.utils.general import non_max_suppression, scale_coords +from Y5_old.utils.plots import plot_one_box +from network_multi import Multi_transform_image +from cv2AddChineseText import cv2AddChineseText +class Density: + def __init__(self, device, root): + self.device = device + self.root = root + self.net = PKSNet().to(self.device) + self.pth = "../data_MPKFNet/test/1.pth" + # print("creat model is ", (t4 - t3) * 1000) + # self.checkpointer = CheckPointer(self.net) + # self.net.load_state_dict(self.checkpointer['net']) + # self.checkpointer.load(self.checkpointer['net']) + checkpoint = torch.load(self.pth) + self.net.load_state_dict(checkpoint['net']) + if gp.DebugPrint_flag: + print("load model weight ok") + np.set_printoptions(threshold=np.inf) + + def inference(self,image,imagetime,index): + rootpath = os.path.join(self.root, imagetime) + if not os.path.exists(rootpath): + os.mkdir(rootpath) + if not os.path.exists(rootpath + "/" + "Density"+"/"): + os.mkdir(rootpath + "/" + "Density"+"/") + target_h, target_w = image.shape[0], image.shape[1] + # t1 = time.time() + image = cv2.resize(image, (1024, 768)) / 255.0 + image = np.transpose(image, [2, 0, 1]) + image = np.expand_dims(image, axis=0) + image = torch.tensor(image) + image = image.to(self.device) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("Density data deal is ", (t2 - t1) * 1000) + + # print("data dell is ", (t7 - t6) * 1000) + + if model_head: + targets_pred, posture_pred, spice_pred = self.net(image) + else: + targets_pred = self.net(image) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("Density inference is ", (t3 - t2) * 1000) + targets_pred1 = targets_pred.cpu() + num = targets_pred1.data.sum().numpy() + targets_pred1 = targets_pred1.data.numpy() + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("Density final is ", (t4 - t3) * 1000) + data_dict = {"sum": str(num), "density": (str(targets_pred1[0, 0, :, :]))} + json_outputpath = (rootpath + "/" + "Density"+"/"+str(index).zfill(3)+".json") + json_data = json.dumps(data_dict, ensure_ascii=True, indent=4) + with open (json_outputpath,'w',encoding='utf-8') as f: + f.write(str(json_data)) + # t5=time.time() + # if gp.DebugPrint_flag: + # print("Density save is ", (t5 - t4) * 1000) + + def inference_init(self, image): + image = cv2.resize(image, (1024, 768)) / 255.0 + image = np.transpose(image, [2, 0, 1]) + image = np.expand_dims(image, axis=0) + image = torch.tensor(image) + image = image.to(self.device) + + if model_head: + targets_pred, posture_pred, spice_pred = self.net(image) + else: + targets_pred = self.net(image) + + targets_pred1 = targets_pred.cpu() + num = targets_pred1.data.sum().numpy() + targets_pred1 = targets_pred1.data.numpy() + if gp.DebugPrint_flag: + print("Density initing") + +""" +Ä¿±ê¼ì²â +""" +class Detection_S: + def __init__(self,device,root): + self.device = device + self.root = root + cfg.merge_from_file("ssd/config/hat-512.yaml") + cfg.freeze() + self.net =build_detection_model(cfg).to(self.device) + self.checkpointer = CheckPointer(self.net, save_dir=cfg.OUTPUT_DIR) + self.ckpt = "../data_MPKFNet/weigth/detection/detection.pth" + self.checkpointer.load(self.ckpt, use_latest=self.ckpt is None) + self.transforms = build_transforms(cfg, is_train=False) + self.threshold = gp.detect_thresh + self.net.eval() + def inference(self,image,imagetime,index,fine_grained): + with torch.no_grad(): + class_names = VOCDataset.class_names + rootpath = os.path.join(self.root, imagetime) + if not os.path.exists(rootpath): + os.mkdir(rootpath) + if not os.path.exists(rootpath + "/" + "Detection" + "/"): + os.mkdir(rootpath + "/" + "Detection" + "/") + image_or = image + height, width = image.shape[:2] + # t1 = time.time() + image = self.transforms(image)[0].unsqueeze(0) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("Detection data deal is ",(t2-t1)*1000) + result = self.net(image.to(self.device))[0] + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("Detection inference is ",(t3-t2)*1000) + result = result.to(torch.device("cpu")) + result = result.resize((width, height)).numpy() + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Detection get result is ", (t5 - t3) * 1000) + boxes, labels, scores = result['boxes'], result['labels'], result['scores'] + indices_score = (scores > self.threshold) + indices_label_left = labels <4 + indices_label_right = labels >2 + indices = [] + for i in range(len(indices_score)): + indices.append(indices_score[i] and indices_label_left[i] and indices_label_right[i]) + boxes = boxes[indices] + labels = labels[indices] + scores = scores[indices] + for i in range(len(boxes)): + if boxes[i][0]<0: + boxes[i][0] = 0 + if boxes[i][1]<0: + boxes[i][1] = 0 + if boxes[i][2]<0: + boxes[i][2] = 0 + if boxes[i][3]<0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 99999 + boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores) + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("Detection final is ", (t4 - t3) * 1000) + #numb = 2 + #fine_grained.inference(image_or,boxes,labels,scores) + # for box in boxes: + # img1 = image_or.copy()[int(box[1]):int(box[3]), int(box[0]):int(box[2]), :] + # cv2.imwrite(rootpath + "/" + "Detection" + "/"+"{}.jpg".format(numb), img1) + # numb+=1 + #drawn_image = draw_boxes(image_or, boxes_fine, labels_fine, scores_fine).astype(np.uint8) + xml_outputpath = rootpath + "/" + "Detection"+"/" + index+".xml" + make_xml(str(index),image_or.shape[0],image_or.shape[1],boxes_fine,labels_fine,scores_fine,xml_outputpath,class_names) + #Image.fromarray(drawn_image).save(xml_outputpath.replace(".xml",".jpg")) + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Detection save is ", (t5 - t4) * 1000) + def inference_Red(self,image,ImagePath,fine_grained): + with torch.no_grad(): + class_names = VOCDataset.class_names + image_or = image + height, width = image.shape[:2] + # t1 = time.time() + image = self.transforms(image)[0].unsqueeze(0) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("data deal is ",(t2-t1)*1000) + result = self.net(image.to(self.device))[0] + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("inference is ",(t3-t2)*1000) + result = result.to(torch.device("cpu")) + result = result.resize((width, height)).numpy() + boxes, labels, scores = result['boxes'], result['labels'], result['scores'] + indices_score = (scores > self.threshold) + indices_label_left = labels <4 + indices_label_right = labels >2 + indices = [] + for i in range(len(indices_score)): + indices.append(indices_score[i] and indices_label_left[i] and indices_label_right[i]) + boxes = boxes[indices] + for i in range(len(boxes)): + if boxes[i][0]<0: + boxes[i][0] = 0 + if boxes[i][1]<0: + boxes[i][1] = 0 + if boxes[i][2]<0: + boxes[i][2] = 0 + if boxes[i][3]<0: + boxes[i][3] = 0 + + labels = labels[indices] + scores = scores[indices] + for i in range(len(labels)): + labels[i] = 99999 + boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores) + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("final is ", (t4 - t3) * 1000) + #numb = 2 + #fine_grained.inference(image_or,boxes,labels,scores) + # for box in boxes: + # img1 = image_or.copy()[int(box[1]):int(box[3]), int(box[0]):int(box[2]), :] + # cv2.imwrite(rootpath + "/" + "Detection" + "/"+"{}.jpg".format(numb), img1) + # numb+=1 + #drawn_image = draw_boxes(image_or, boxes_fine, labels_fine, scores_fine).astype(np.uint8) + xml_outputpath = ImagePath.replace("/ftp/", "/ftp_Result/").replace(".JPG", ".xml").replace(".jpg",".xml") + make_xml(str(ImagePath),image_or.shape[0],image_or.shape[1],boxes_fine,labels_fine,scores_fine,xml_outputpath) + #Image.fromarray(drawn_image).save(xml_outputpath.replace(".xml",".jpg")) + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("save is ", (t5 - t4) * 1000) + + def check_object(self, image): + flag = False + with torch.no_grad(): + height, width = image.shape[:2] + img_temp = image + # t1 = time.time() + image = self.transforms(image)[0].unsqueeze(0) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("check datadeal is ",(t2-t1)*1000) + result = self.net(image.to(self.device))[0] + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("check inference is ", (t3 - t2) * 1000) + result = result.to(torch.device("cpu")) + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("check result deal is ", (t4 - t3) * 1000) + result = result.resize((width, height)).numpy() + + boxes, labels, scores = result['boxes'], result['labels'], result['scores'] + indices_score = (scores > self.threshold) + indices_label_left = labels <4 + indices_label_right = labels >2 + indices = [] + for i in range(len(indices_score)): + indices.append(indices_score[i] and indices_label_left[i] and indices_label_right[i]) + labels = labels[indices] + boxes = boxes[indices] + scores=scores[indices] + if 3 in labels: + flag = True + # if gp.DebugPrint_flag: + # print("boxes = ", boxes) + # print("check flag is ", flag) + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("check final is ", (t5 - t4) * 1000) + return flag, labels, boxes, scores +class Detection_Y5: + def __init__(self,device,root,detect_thresh): + self.device = device + self.root = root + self.img_size = 2176#640 + self.conf_thres = detect_thresh + self.iou_thres = 0.4 + self.stride = 1 + # self.weights = "/data/Hatcher/data/Detection_weigth/BASE_PYH_SJH-Bird-1-45328-2160-s-base9/weights/best.pt" + self.weights = gp.DetWeight + # self.device = select_device(self.device) + model = attempt_load(self.weights, device=self.device) + model.to(self.device).eval() + model.half() + self.zwq = True + self.model = model + self.names = model.module.names if hasattr( + model, 'module') else model.names + def preprocess(self, img): + + img0 = img.copy() + #img = cv2.resize(img, (1024, 768)) + img = letterbox(img, new_shape=self.img_size, stride=self.stride)[0] + img = img[:, :, ::-1].transpose(2, 0, 1) + img = np.ascontiguousarray(img) + img = torch.from_numpy(img).to(self.device) + img = img.half() # ¡ã????¨¨ + img /= 255.0 # ¨ª???1¨¦¨°??¡¥ + if img.ndimension() == 3: + img = img.unsqueeze(0) + + return img0, img + def AIlabel(self,imagename): + with torch.no_grad(): + tqdm.write(imagename + " is doing!") + image = cv2.imread(imagename) + image_or = image + img_detect = cv2.resize(image, (1024, 768)) + # t1 = time.time() + image_scale,image = self.preprocess(img_detect) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("Detection data deal is ",(t2-t1)*1000) + pred = self.model(image, augment=False)[0] + pred = pred.float() + pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("Detection inference is ",(t3-t2)*1000) + boxes = [] + scores = [] + labels = [] + for det in pred: + if det is not None and len(det): + det[:, :4] = scale_coords( + image.shape[2:], det[:, :4], image_scale.shape).round() + boxes.append(det[:, :4]) + scores.append(det[:, 4]) + labels.append((det[:, -1])) + boxes = boxes[0] + scores = scores[0] + labels = labels[0] + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Detection get result is ", (t5 - t3) * 1000) + if len(labels) > 0: + ratio_x = (image_or.shape[1] / 1024.0) + ratio_y = (image_or.shape[0] / 768.0) + for i in range(len(boxes)): + boxes[i][0]=boxes[i][0] * ratio_x + boxes[i][2]=boxes[i][2] * ratio_x + boxes[i][1] = boxes[i][1] * ratio_y + boxes[i][3] = boxes[i][3] * ratio_y + if boxes[i][0]<0: + boxes[i][0] = 0 + if boxes[i][1]<0: + boxes[i][1] = 0 + if boxes[i][2]<0: + boxes[i][2] = 0 + if boxes[i][3]<0: + boxes[i][3] = 0 + # for i in range(len(labels)): + # labels[i] = "bird" + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("Detection final is ", (t4 - t3) * 1000) + xml_outputpath = imagename.replace("imagesAILabel","LabelXML").replace(".jpg",".xml") + make_xml(imagename,image_or.shape[0],image_or.shape[1],boxes,labels,scores,xml_outputpath) + shutil.copy(imagename, imagename.replace("imagesAILabel", "YesResult")) + else: + shutil.copy(imagename, imagename.replace("imagesAILabel", "NoResult")) + def AIlabelFine(self, imagename, fine_grained): + with torch.no_grad(): + tqdm.write(imagename + " is doing!") + try: + image = cv2.imread(imagename) + except: + os.remove(imagename) + return + if not type(image): + print("skip") + return + image_or = image + try: + img_detect = cv2.resize(image, (image.shape[1], image.shape[0])) + except: + shutil.copy(imagename, imagename.replace("imagesAILabel", "BrokenImage")) + return + image_scale, image = self.preprocess(img_detect) + pred = self.model(image, augment=False)[0] + pred = pred.float() + pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) + boxes = [] + scores = [] + labels = [] + for det in pred: + if det is not None and len(det): + det[:, :4] = scale_coords( + image.shape[2:], det[:, :4], image_scale.shape).round() + boxes.append(det[:, :4]) + scores.append(det[:, 4]) + labels.append((det[:, -1])) + boxes = boxes[0] + scores = scores[0] + labels = labels[0] + # if len(labels) > 0: + ratio_x = 1#(image_or.shape[1] / 1024.0) + ratio_y = 1#(image_or.shape[0] / 768.0) + for i in range(len(boxes)): + boxes[i][0] = boxes[i][0] * ratio_x + boxes[i][2] = boxes[i][2] * ratio_x + boxes[i][1] = boxes[i][1] * ratio_y + boxes[i][3] = boxes[i][3] * ratio_y + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][3] < 0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 0 + if self.zwq: + boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores, 8) + else: + boxes_fine = boxes + labels_fine = labels + scores_fine = scores + xml_outputpath = imagename.replace("imagesAILabel", "Annotations").replace(".jpg", ".xml") + make_xml(imagename, image_or.shape[0], image_or.shape[1], boxes_fine, labels_fine, scores_fine, xml_outputpath) + shutil.copy(imagename, imagename.replace("imagesAILabel", "JPEGImages")) + # else: + # shutil.copy(imagename, imagename.replace("imagesAILabel", "NoResult")) + def inference(self, image, imagetime, index, fine_grained): + with torch.no_grad(): + rootpath = os.path.join(self.root, imagetime) + if not os.path.exists(rootpath): + os.mkdir(rootpath) + if not os.path.exists(rootpath + "/" + "Detection" + "/"): + os.mkdir(rootpath + "/" + "Detection" + "/") + image_or = image + img_detect = cv2.resize(image, (1024, 768)) + image_scale, image = self.preprocess(img_detect) + pred = self.model(image, augment=False)[0] + pred = pred.float() + pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) + boxes = [] + scores = [] + labels = [] + for det in pred: + if det is not None and len(det): + det[:, :4] = scale_coords( + image.shape[2:], det[:, :4], image_scale.shape).round() + boxes.append(det[:, :4]) + scores.append(det[:, 4]) + labels.append((det[:, -1])) + boxes = boxes[0] + scores = scores[0] + labels = labels[0] + if len(labels) > 0: + indices_label_left = labels < 10 + indices_label_right = labels < 10 + indices = [] + for i in range(len(indices_label_left)): + indices.append(indices_label_left[i] and indices_label_right[i]) + boxes = boxes[indices] + labels = labels[indices] + scores = scores[indices] # ÒòΪĪÃûÆæÃî¶àÁËÒ»¸ölistά¶È£¬ËùÒÔ¼ÓÁËÕâ¸ö0 + if len(labels) > 0: + boxes = boxes[0] + labels = labels[0] + scores = scores[0] + ratio_x = (3840.0 / 1024.0) + ratio_y = (2160.0 / 768.0) + for i in range(len(boxes)): + boxes[i][0] = boxes[i][0] * ratio_x + boxes[i][2] = boxes[i][2] * ratio_x + boxes[i][1] = boxes[i][1] * ratio_y + boxes[i][3] = boxes[i][3] * ratio_y + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][3] < 0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 99999 + boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores) + else: + boxes_fine, labels_fine, scores_fine = [],[],[] + if gp.DebugPrint_flag: + print("Detection is nothong") + xml_outputpath = rootpath + "/" + "Detection"+"/" + index+".xml" + make_xml(str(index),image_or.shape[0],image_or.shape[1],boxes_fine,labels_fine,scores_fine,xml_outputpath) + def inference_Red(self,image,ImagePath,fine_grained): + with torch.no_grad(): + image_or = image + height, width = image.shape[:2] + img_detect = cv2.resize(image, (1024, 768)) + # t1 = time.time() + image_scale, image = self.preprocess(img_detect) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("Detection data deal is ", (t2 - t1) * 1000) + pred = self.model(image, augment=False)[0] + pred = pred.float() + pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("Detection inference is ", (t3 - t2) * 1000) + boxes = [] + scores = [] + labels = [] + for det in pred: + if det is not None and len(det): + det[:, :4] = scale_coords( + image.shape[2:], det[:, :4], image_scale.shape).round() + boxes.append(det[:, :4]) + scores.append(det[:, 4]) + labels.append((det[:, -1])) + boxes = boxes[0] + scores = scores[0] + labels = labels[0] + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Detection get result is ", (t5 - t3) * 1000) + # print(labels) + if len(labels) > 0 : + indices_label_left = labels < 1 + indices_label_right = labels < 1 + indices = [] + for i in range(len(indices_label_left)): + indices.append(indices_label_left[i] and indices_label_right[i]) + boxes = boxes[indices] + labels = labels[indices] + scores = scores[indices] # ÒòΪĪÃûÆæÃî¶àÁËÒ»¸ölistά¶È£¬ËùÒÔ¼ÓÁËÕâ¸ö0 + if len(labels) > 0: + boxes = boxes[0] + labels = labels[0] + scores = scores[0] + ratio_x = (width / 1024.0) + ratio_y = (height / 768.0) + for i in range(len(boxes)): + boxes[i][0] = boxes[i][0] * ratio_x + boxes[i][2] = boxes[i][2] * ratio_x + boxes[i][1] = boxes[i][1] * ratio_y + boxes[i][3] = boxes[i][3] * ratio_y + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][0] > 3840: + boxes[i][0] = 3839 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][1] > 2160: + boxes[i][1] = 2159 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][2] > 3840: + boxes[i][2] = 3839 + if boxes[i][3] < 0: + boxes[i][3] = 0 + if boxes[i][3] > 2160: + boxes[i][3] = 2159 + for i in range(len(labels)): + labels[i] = 99999 + boxes_fine, labels_fine, scores_fine = fine_grained.inference(image_or, boxes, labels, scores) + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("Detection final is ", (t4 - t3) * 1000) + # t6 = time.time() + xml_outputpath = ImagePath.replace("/ftp/", "/ftp_Result/").replace(".JPG", ".xml").replace(".jpg", ".xml") + make_xml(str(ImagePath), image_or.shape[0], image_or.shape[1], boxes_fine, labels_fine, scores_fine, xml_outputpath) + # Image.fromarray(drawn_image).save(xml_outputpath.replace(".xml",".jpg")) + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Detection save is ", (t5 - t6) * 1000) + else: + boxes_fine, labels_fine, scores_fine = [], [], [] + if gp.DebugPrint_flag: + print("Detection is nothong") + + + def check_object(self,img_o): + flag = False + with torch.no_grad(): + # path = '/data/Hatcher/ouput1/0001_20210414151147/RawImage/0099.jpg' + # img = cv2.imread(path) + # img = cv2.resize() + height, width = img_o.shape[:2] + img = cv2.resize(img_o,(1024,768)) + # t1 = time.time() + image_scale, image = self.preprocess(img) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("Check data deal is ", (t2 - t1) * 1000) + pred = self.model(image, augment=False)[0] + pred = pred.float() + pred = non_max_suppression(pred, self.conf_thres, self.iou_thres) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("Check inference is ", (t3 - t2) * 1000) + boxes = [] + scores = [] + labels = [] + for det in pred: + if det is not None and len(det): + det[:, :4] = scale_coords( + image.shape[2:], det[:, :4], image_scale.shape).round() + boxes.append(det[:, :4]) + scores.append(det[:, 4]) + labels.append((det[:, -1])) + boxes = boxes[0] + scores = scores[0] + labels = labels[0] + # t5 = time.time() + # if gp.DebugPrint_flag: + # print("Check get result is ", (t5 - t3) * 1000) + if len(labels) > 0: + # indices_label_left = labels < 1 + # indices_label_right = labels < 1 + # indices = [] + # for i in range(len(indices_label_left)): + # indices.append(indices_label_left[i] and indices_label_right[i]) + # boxes = boxes[indices] + # print(type(labels)) + # print(labels) + # print(type(indices)) + # print(indices) + + labels = labels + scores = scores # ÒòΪĪÃûÆæÃî¶àÁËÒ»¸ölistά¶È£¬ËùÒÔ¼ÓÁËÕâ¸ö0 + + if len(labels) > 0: + if len(boxes.shape) == 3: + boxes = boxes[0] + labels = labels[0] + scores = scores[0] + ratio_x = (width / 1024.0) + ratio_y = (height / 768.0) + for i in range(len(boxes)): + #boxes = boxes.numpy() + boxes[i][0] = boxes[i][0] * ratio_x + boxes[i][2] = boxes[i][2] * ratio_x + boxes[i][1] = boxes[i][1] * ratio_y + boxes[i][3] = boxes[i][3] * ratio_y + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][0] > 3840: + boxes[i][0] = 3839 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][1] > 2160: + boxes[i][1] = 2159 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][2] > 3840: + boxes[i][2] = 3839 + if boxes[i][3] < 0: + boxes[i][3] = 0 + if boxes[i][3] > 2160: + boxes[i][3] = 2159 + else: + pass + if 0 in labels: + flag = True + if gp.DebugPrint_flag: + print("boxes = ", boxes) + print("check flag is ", flag) + return flag, labels, boxes, scores +""" +ϸÁ£¶Èʶ±ð +""" +class args_temp(): + dataset = 'HCData' + backbone = 'resnet50' + batch_size = 1 + num_workers = 8 + version = 'val' + resize_resolution = 512 + crop_resolution = 448 + save_suffix = None + swap_num = [7, 7] +class Fine_grained_T: + def __init__(self, device): + self.device = device + self.WeightPath = gp.FineWeight + self.net = timm.create_model("convnext_base_384_in22ft1k", num_classes=gp.FineClassNum, pretrained=False).to(device) # Multi_transform_image().to(device) + model_dict = self.net.state_dict() + pretrained_dict = torch.load(self.WeightPath) + pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} + model_dict.update(pretrained_dict) + self.net.load_state_dict(pretrained_dict) + self.transformers = load_data_transformers(600, 384, [7, 7]) + print("load model weight is ok") + self.net.train(False) + self.softmax = nn.Softmax() + self.gp_Species = torch.zeros(8).cuda(device) + if gp.DebugPrint_flag: + print("load model weight is ok") + + + def inference(self, img, imagelist, labellist, scorelist, multiimagenum): + with torch.no_grad(): + img_deal = [] + labelIndexForFusionResult = 0 + imaIndexIfSuit = [0 for i in range(len(imagelist))] + for i, box in enumerate(imagelist): + if box[0] < 0: + box[0] = 0 + if box[1] < 0: + box[1] = 0 + if box[2] < 0: + box[2] = 0 + if box[3] < 0: + box[3] = 0 + Img = img.copy()[int(box[1]):int(box[3]), int(box[0]):int(box[2]), :] + #if gp.DebugPrint_flag: + #print(box) + #print(Img) + #if (int(box[3])-int(box[1])>gp.fine_thresh) and (int(box[2])-int(box[0])>gp.fine_thresh): + if ((int(box[3]) - int(box[1])) * (int(box[2]) - int(box[0]))) > gp.fine_thresh1 : + Img = Image.fromarray(cv2.cvtColor(Img, cv2.COLOR_BGR2RGB)) + Img = self.transformers['test_totensor'](Img) + Img = Img.unsqueeze(0) + img_deal.append(Img) + imaIndexIfSuit[i] =1 + else: + pass + iter_nums = int(len(img_deal)/multiimagenum) + single_imagedealnums = int(len(img_deal)%multiimagenum) + for iter_num in range(iter_nums): + tqdm.write("start {} iter".format(str(iter_num))) + # t1 = time.time() + Img = torch.cat((img_deal[0*iter_num], img_deal[1*iter_num], img_deal[2*iter_num], img_deal[3*iter_num], img_deal[4*iter_num], img_deal[5*iter_num], img_deal[6*iter_num], img_deal[7*iter_num]), 0) + inputs = Variable(Img.cuda()) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("iter{} fine data deal is ".format(str(iter_num)), (t2 - t1) * 1000) + outputs = self.net(inputs) + outputs = self.softmax(outputs) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("iter{} fine inference is ".format(str(iter_num)), (t3 - t2) * 1000) + #outputs[0] = self.softmax(outputs[0]) + #Species = torch.zeros(multiimagenum).cuda() + Species = self.gp_Species + # t4_1 = time.time() + # if gp.DebugPrint_flag: + # print("iter{} fine data final1 is ".format(str(iter_num)), (t4_1 - t3) * 1000) + for outnum in range(multiimagenum): + top3_val, top3_pos = torch.topk(outputs[outnum],1) + # t4_temp2 = time.time() + if top3_val < gp.Fine_thresh: + Species[outnum] = 0 + else: + Species[outnum] = top3_pos + # t4_temp3 = time.time() + # tqdm.write("iter{} fine data temp3 is ".format(str(iter_num)), (t4_temp3 - t4_temp2) * 1000) + # t4_2 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("iter{} fine data final2 is ".format(str(iter_num)), (t4_2 - t4_1) * 1000) + for j in range(multiimagenum): + for m in range(len(imaIndexIfSuit)): + if imaIndexIfSuit[labelIndexForFusionResult] == 1: #clam this boxes has been deal with fine grained + labellist[labelIndexForFusionResult] = Species[j] + labelIndexForFusionResult += 1 + break + else: + labelIndexForFusionResult += 1 + # t4_3 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("iter{} fine data final3 is ".format(str(iter_num)), (t4_3 - t4_2) * 1000) + #labellist[iter_num*multiimagenum:iter_num*multiimagenum+multiimagenum] = Species + # t4 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("iter{} fine data final is ".format(str(iter_num)), (t4 - t3) * 1000) + # t4 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("start {} single_imagedealnums".format(str(single_imagedealnums))) + # tqdm.write("single_imagedealnums is ",single_imagedealnums) + Img = None + if single_imagedealnums == 0: + pass + elif single_imagedealnums == 1: + Img = img_deal[(iter_nums) * multiimagenum] + else: + #Img = torch.cat((img_deal[0*iter_num],img_deal[1*iter_num],img_deal[2*iter_num],img_deal[3*iter_num],img_deal[4*iter_num],img_deal[5*iter_num],img_deal[6*iter_num],img_deal[7*iter_num]),0) + # tF1 = time.time() + singleimage = [] + for tempm in range(single_imagedealnums): + singleimage.append(img_deal[(iter_nums) * multiimagenum+tempm]) + Img = torch.cat(singleimage, 0) + # Img = torch.cat((img_deal[(iter_nums) * multiimagenum], img_deal[(iter_nums) * multiimagenum+1]), 0) + # for single_imagedealnum in range(single_imagedealnums-2): + # Img = torch.cat((Img,img_deal[(iter_nums) * multiimagenum+1+single_imagedealnum+1]),0) + # tF2 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("single_imagedealnumsv fine data deal cat is ", (tF2 - tF1) * 1000) + # t5 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("single_imagedealnumsv fine data deal is ", (t5 - t4) * 1000) + if not (Img == None): + # tsfCU1 = time.time() + inputs = Variable(Img.cuda()) + # tsfCU2 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("single_imagedealnumsv tocuda is ", (tsfCU2 - tsfCU1) * 1000) + outputs = self.net(inputs) + outputs = self.softmax(outputs) + # t6 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write("single_imagedealnums fine inference is ", (t6 - t5) * 1000) + Species = self.gp_Species + #Species = torch.zeros(single_imagedealnums).cuda() + for outnum in range(single_imagedealnums): + top3_val, top3_pos = torch.topk(outputs[outnum], 1) + #print("top3_val==========", top3_val) + t4_temp2 = time.time() + if top3_val < gp.Fine_thresh: + Species[outnum] = 0 + else: + Species[outnum] = top3_pos + # t4_temp3 = time.time() + # print("single_imagedealnums fine data temp3 is ", (t4_temp3 - t4_temp2) * 1000) + for j in range(single_imagedealnums): + for m in range(len(imaIndexIfSuit)): + if imaIndexIfSuit[labelIndexForFusionResult] == 1: # clam this boxes has been deal with fine grained + labellist[labelIndexForFusionResult] = Species[j] + labelIndexForFusionResult += 1 + break + else: + labelIndexForFusionResult += 1 + + #labellist[len(labellist)-single_imagedealnums:] = Species + # t7 = time.time() + # if gp.DebugPrint_flag: + # tqdm.write(" fine data final is ", (t7 - t6) * 1000) + return imagelist, labellist, scorelist + +class Fine_grained: + def __init__(self, device, root): + self.device = device + self.root = root + self.DclPreWeightPath = '../data_MPKFNet/test/3.pth' + # parser = argparse.ArgumentParser(description='dcl parameters') + # parser.add_argument('--data', dest='dataset', default='HCData', type=str) + # parser.add_argument('--backbone', dest='backbone', default='resnet50', type=str) + # parser.add_argument('--b', dest='batch_size', default=1, type=int) + # parser.add_argument('--nw', dest='num_workers', default=8, type=int) + # parser.add_argument('--ver', dest='version', default='val', type=str) + # parser.add_argument('--size', dest='resize_resolution', default=512, type=int) + # parser.add_argument('--crop', dest='crop_resolution', default=448, type=int) + # parser.add_argument('--ss', dest='save_suffix', default=None, type=str) + # parser.add_argument('--acc_report', dest='acc_report', action='store_true') + # parser.add_argument('--swap_num', default=[7, 7], nargs=2, metavar=('swap1', 'swap2'), type=int, help='specify a range') + self.args = args_temp() + self.Config = LoadConfig(self.args, 's') + self.transformers = load_data_transformers(self.args.resize_resolution, self.args.crop_resolution, self.args.swap_num) + self.net = MainModel(self.Config).to(device) + model_dict = self.net.state_dict() + pretrained_dict = torch.load(self.DclPreWeightPath) + model_dict.update(pretrained_dict) + self.net.load_state_dict(model_dict) + if gp.DebugPrint_flag: + print("load model weight is ok") + self.net.train(False) + def inference(self,img,imagelist,labellist,scorelist): + with torch.no_grad(): + for i, box in enumerate(imagelist): + Img = img.copy()[int(box[1]):int(box[3]), int(box[0]):int(box[2]), :] + if (int(box[3])-int(box[1]) > 100) and (int(box[2])-int(box[0]) > 100): + t1 = time.time() + Img = Image.fromarray(cv2.cvtColor(Img, cv2.COLOR_BGR2RGB)) + Img = self.transformers['test_totensor'](Img) + Img = Img.unsqueeze(0) + inputs = Variable(Img.cuda()) + # t2 = time.time() + # if gp.DebugPrint_flag: + # print("fine data deal is ", (t2 - t1) * 1000) + outputs = self.net(inputs) + # t3 = time.time() + # if gp.DebugPrint_flag: + # print("fine inference is ", (t3 - t2) * 1000) + top3_val, top3_pos = torch.topk(outputs[0], 3) # topk·µ»ØµÄÊÇÒ»¸öÔª×飬µÚÒ»¸öÔªËØÊÇÿһÐÐ×î´óµÄÈý¸öÖµ£¨Ä¬ÈÏÊǰ´ÐÐÈ¡×î´óÖµ£©£¬µÚ¶þ¸öÔªËØÊÇÿһÐÐ×î´óµÄÖµµÄÅÅÐò + Species = top3_pos.cpu().numpy()[0][0] + ConfidenceLevel = top3_val.cpu().numpy()[0][0] + ConfidenceLevel = ConfidenceLevel/26.0 + if ConfidenceLevel > 1: + ConfidenceLevel = 1.0 * random.uniform(0, 1) + # if gp.DebugPrint_flag: + # print("hhhhhhhhhhhhhhhhhhhhhhh is ",ConfidenceLevel) + labellist[i] = Species + scorelist[i] = ConfidenceLevel + # t4 = time.time() + # if gp.DebugPrint_flag: + # print("fine data final is ", (t4 - t3) * 1000) + return imagelist, labellist, scorelist +class Check_start (threading.Thread): + def __init__(self, threadID, name, img, DetectionClass): + threading.Thread.__init__(self) + self.threadID = threadID + self.name = name + self.img = img + self.DetectionClass = DetectionClass + def run(self): + if gp.DebugPrint_flag: + tqdm.write(self.name + " is start") + gp.is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(self.img) + + if gp.is_ex_bird: + if gp.DebugPrint_flag: + tqdm.write(gp.is_ex_bird) + gp.image_time = gp.Camera_device +time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) + if gp.DebugPrint_flag: + tqdm.write(self.name + " is finish") +class save_sigle_image(threading.Thread): + def __init__(self, img): + threading.Thread.__init__(self) + self.img = img + def run(self): + cv2.imwrite( + "../data_MPKFNet/RTSP2/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), + self.img) +class Check_start_fordataselect (threading.Thread): + def __init__(self, threadID, name, img, DetectionClass, fine_grained): + threading.Thread.__init__(self) + self.threadID = threadID + self.name = name + self.img = img + self.DetectionClass = DetectionClass + self.fine_grained = fine_grained + def run(self): + if gp.DebugPrint_flag: + print(self.name + " is start") + is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(self.img) + image_or = self.img.copy() + if is_ex_bird: + for i in range(len(boxes)): + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][3] < 0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 99999 + boxes_fine, labels_fine, scores_fine = self.fine_grained.inference(self.img, boxes, labels, scores) + for i in range(len(scores)): + xyxy = boxes_fine[i] + conf = scores_fine[i] + cls = labels_fine[i] + print(int(cls)) + label = str(gp.BHG_chineseName[int(cls)]) + print(label) + #label = f'{int(cls)} {conf:.2f}' + palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1) + colors = [int((p * (cls ** 2 - cls + 1)) % 255) for p in palette] + self.img = plot_one_box(xyxy, self.img, label=label, color=colors, line_thickness=2) + #cv2.imshow("AI-ECO",self.img) + #cv2.waitKey(0) + cv2.imwrite("../data_MPKFNet/RTSP/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), image_or) + cv2.imwrite("../data_MPKFNet/RTSP/result/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), self.img) + if gp.DebugPrint_flag: + print(self.name + " is finish") +class shishi(): + def __init__(self, name, DetectionClass, fine_grained): + self.threadID = 0 + self.name = name + self.DetectionClass = DetectionClass + self.fine_grained = fine_grained + + + def go_go(self, img, num_image, num_detection): + spiec_number = [0 for i in range(len(gp.BHG_chineseName))] + img_show = img.copy() + boxes_fine = [] + labels_fine = [] + if (isinstance(img_show, np.ndarray)): # ?D??¨º?¡¤?OpenCV¨ª???¨¤¨¤D¨ª + img_show = Image.fromarray(cv2.cvtColor(img_show, cv2.COLOR_BGR2RGB)) + draw = ImageDraw.Draw(img_show) + height_or, width_or = img.shape[:2] + if gp.DebugPrint_flag: + print("image size is ", height_or, width_or) + if(num_detection%2==0): + if gp.DebugPrint_flag: + print(self.name + " is start") + # ts1 = time.time() + is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(img) + # ts2 = time.time() + # if gp.DebugPrint_flag: + # print("shishi time detect1 deal is ", (ts2 - ts1) * 1000) + if is_ex_bird: + for i in range(len(boxes)): + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][3] < 0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 0#gp.birdIndex + # ts3 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect2 deal is ", (ts3 - ts2) * 1000) + boxes_fine, labels_fine, scores_fine = self.fine_grained.inference(img, boxes, labels, scores, 8) + # ts4 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect3 deal is ", (ts4 - ts3) * 1000) + # tcpu1 = time.time() + boxes_fine = boxes_fine.to('cpu') + labels_fine = labels_fine.to('cpu') + # tcpu2 = time.time() + # if gp.DebugPrint_flag: + # print("to cpu timeis ", (tcpu2 - tcpu1) * 1000) + gp.boxes_fine = boxes_fine + gp.labels_fine = labels_fine + else: + print("don't deal {}".format(str(num_detection))) + boxes_fine = gp.boxes_fine + labels_fine = gp.labels_fine + for i in range(len(boxes_fine)): + # tprint1 = time.time() + xyxy = boxes_fine[i] + cls = labels_fine[i] + # tprint2 = time.time() + # if gp.DebugPrint_flag: + # print("tprint1 is ", (tprint2 - tprint1) * 1000) + # tcls1 = time.time() + b = (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < 15000) + # a =(xyxy.item()[3] - xyxy.item()[1]) * (xyxy.item()[2] - xyxy.item()[0]) + # tcls2 = time.time() + # if gp.DebugPrint_flag: + # print("tcls1 is ", (tcls2 - tcls1) * 1000) + if cls == 0 or (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < gp.fine_thresh2): + #if cls == gp.birdIndex or (torch.sub(torch.mul(torch.sub(xyxy[3], xyxy[1]), torch.sub(xyxy[2], xyxy[0])),gp.fine_thresh2) < 0): + label = None + else: + # tcls3 = time.time() + label = gp.BHG_chineseName[int(cls)] + spiec_number[int(cls)] += 1 + # tcls4 = time.time() + # if gp.DebugPrint_flag: + # print("tcls2 is ", (tcls4 - tcls3) * 1000) + # tprint3 = time.time() + # if gp.DebugPrint_flag: + # print("tprint2 is ", (tprint3 - tprint2) * 1000) + #label = f'{int(cls)} {conf:.2f}' + palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1) + colors = gp.color_box#tuple(int((p * (4 ** 2 - 4 + 1)) % 220) for p in palette) + # tprint4 = time.time() + # if gp.DebugPrint_flag: + # print("tprint3 is ", (tprint4 - tprint3) * 1000) + draw = plot_one_box(xyxy, draw, height_or,width_or,label=label, color=colors, line_thickness=2) + # tpChin1 = time.time() + if num_image > gp.showThresh : + gp.num_count_old = len(boxes_fine) + gp.spiec_number_old = spiec_number + num_image = 0 + # tpChin2 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin1 is ", (tpChin2 - tpChin1) * 1000) + #if width_or == 2560: + draw = cv2AddChineseText(draw, "ʶ±ð×ÜÊý: {}Ö»".format(str(gp.num_count_old)), (50*gp.radioShowX, 1100*gp.radioShowY), textColor=gp.color_show, textSize=50) + # tpChin3 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin2 is ", (tpChin3 - tpChin2) * 1000) + draw = cv2AddChineseText(draw, "·ÖÀàʶ±ð:", (50*gp.radioShowX, 1150*gp.radioShowY), textColor=gp.color_show, textSize=50) + # tpChin4 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin3 is ", (tpChin4 - tpChin3) * 1000) + for i in range(1, len(spiec_number)): + if i < 5: + draw = cv2AddChineseText(draw, "{}:{}Ö»".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), (300*gp.radioShowX + (i-1) * 280*gp.radioShowX, 1150*gp.radioShowY), textColor=gp.color_show, textSize=50) + else: + draw = cv2AddChineseText(draw, "{}:{}Ö»".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), (50*gp.radioShowX + (i-5) * 280*gp.radioShowX, 1200*gp.radioShowY), textColor=gp.color_show, textSize=50) + img_show = cv2.cvtColor(np.asarray(img_show), cv2.COLOR_RGB2BGR) + gp.img_show = img_show + # tpChin2 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin is ", (tpChin2 - tpChin1) * 1000) + #cv2.waitKey(0) + # cv2.imwrite("../data_MPKFNet/RTSP/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), + # image_or) + # cv2.imwrite( + # "../data_MPKFNet/RTSP/result/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), + # self.img) + if gp.DebugPrint_flag: + print(self.name + " is finish") + num_image += 1 + print(num_image) + return img_show, num_image +class RealDeal(): + def __init__(self, name, DetectionClass, fine_grained): + self.threadID = 0 + self.name = name + self.DetectionClass = DetectionClass + self.fine_grained = fine_grained + + + def realtimerestart(self, img, num_image, num_detection, SortRestart): + spiec_number = [0 for i in range(len(gp.BHG_chineseName))] + img_show = img.copy() + boxes_fine = [] + labels_fine = [] + if (isinstance(img_show, np.ndarray)): # ?D??¨º?¡¤?OpenCV¨ª???¨¤¨¤D¨ª + img_show = Image.fromarray(cv2.cvtColor(img_show, cv2.COLOR_BGR2RGB)) + draw = ImageDraw.Draw(img_show) + height_or, width_or = img.shape[:2] + # if gp.DebugPrint_flag: + # print("image size is ",height_or,width_or) + # if gp.DebugPrint_flag: + # print(self.name + " is start") + # ts1 = time.time() + is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(img) + # ts2 = time.time() + # if gp.DebugPrint_flag: + # print("shishi time detect1 deal is ", (ts2 - ts1) * 1000) + if is_ex_bird: + for i in range(len(boxes)): + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][3] < 0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 0#gp.birdIndex + # ts3 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect2 deal is ", (ts3 - ts2) * 1000) + boxes_fine, labels_fine, scores_fine = self.fine_grained.inference(img, boxes, labels, scores,8) + # ts4 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect3 deal is ", (ts4 - ts3) * 1000) + # tcpu1 = time.time() + boxes_fine = boxes_fine.to('cpu') + labels_fine = labels_fine.to('cpu') + # tcpu2 = time.time() + # if gp.DebugPrint_flag: + # print("to cpu timeis ", (tcpu2 - tcpu1) * 1000) + gp.boxes_fine = boxes_fine + gp.labels_fine = labels_fine + #input = [x1,y1,x2,y2,kong,label] + temp_sort = [i + 100 for i in range(len(labels_fine))] + DetFine = np.column_stack((boxes_fine, temp_sort, labels_fine)) + boxes_fine, indexmaxtemp, newObjectNum = SortRestart.update(DetFine) # boxes_fine ÊÇ n*6µÄÊý×飬nÊÇÄ¿±êµÄÊýÁ¿£¬¶øÇÒÐòºÅÊǵ¹ÐòµÄ£¬×îСµÄÐòºÅÊÇ1 + if indexmaxtemp > gp.IndexMax: + gp.IndexMax = indexmaxtemp + #boxes_fine = boxes_fine[0] + #output = [x1,y1,x2,y2,label,index] + gp.Finerestartboxes.append(boxes_fine) + # for i in range(len(boxes_fine)): + # xyxy = boxes_fine[i][:4] + # cls = boxes_fine[i][4] + # index = boxes_fine[i][5] + # label = None + # palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1) + # colors = gp.color_box #tuple(int((p * (4 ** 2 - 4 + 1)) % 220) for p in palette) + # draw = plot_one_box(xyxy, draw, height_or,width_or,label=label, Index= index, color=colors, line_thickness=int(3*gp.radioShowtext)) + # if num_image > gp.showThresh : + # gp.num_count_old = len(boxes_fine) + # gp.spiec_number_old = spiec_number + # num_image = 0 + # #if width_or == 2560:识别总数分类识别 + # draw = cv2AddChineseText(draw, "识别总数: {}只".format(str(gp.num_count_old)), + # (50 * gp.radioShowX, 1100 * gp.radioShowY), + # textColor=gp.color_show, + # textSize=int(50* gp.radioShowtext)) + # tpChin3 = time.time() + # + # draw = cv2AddChineseText(draw, "分类识别:", (50 * gp.radioShowX, 1150 * gp.radioShowY), textColor=gp.color_show, + # textSize=int(50* gp.radioShowtext)) + # tpChin4 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin3 is ", (tpChin4 - tpChin3) * 1000) + # for i in range(1, len(spiec_number)): + # if i < 5: + # draw = cv2AddChineseText(draw, "{}:{}只»".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), + # (300 * gp.radioShowX + (i - 1) * 280 * gp.radioShowX, 1150 * gp.radioShowY), + # textColor=gp.color_show, + # textSize=int(50* gp.radioShowtext)) + # else: + # draw = cv2AddChineseText(draw, "{}:{}只".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), + # (50 * gp.radioShowX + (i - 5) * 280 * gp.radioShowX, 1200 * gp.radioShowY), + # textColor=gp.color_show, + # textSize=int(50* gp.radioShowtext)) + img_show = cv2.cvtColor(np.asarray(img_show), cv2.COLOR_RGB2BGR) + gp.img_show = img_show + tpChin2 = time.time() + if gp.DebugPrint_flag: + print(self.name + " is finish") + num_image += 1 + return img_show, num_image + + + def realtime(self, img, num_image, num_detection, SortRestart): + spiec_number = [0 for i in range(len(gp.BHG_chineseName))] + img_show = img.copy() + boxes_fine = [] + labels_fine = [] + if (isinstance(img_show, np.ndarray)): # ?D??¨º?¡¤?OpenCV¨ª???¨¤¨¤D¨ª + img_show = Image.fromarray(cv2.cvtColor(img_show, cv2.COLOR_BGR2RGB)) + draw = ImageDraw.Draw(img_show) + height_or, width_or = img.shape[:2] + if gp.DebugPrint_flag: + print("image size is ", height_or, width_or) + if gp.DebugPrint_flag: + print(self.name + " is start") + # ts1 = time.time() + is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(img) + # ts2 = time.time() + # if gp.DebugPrint_flag: + # print("shishi time detect1 deal is ", (ts2 - ts1) * 1000) + if is_ex_bird : + # print("Ä¿±ê¼ì²âµÄ¸öÊý ", len(boxes)) + for i in range(len(boxes)): + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][3] < 0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 0#gp.birdIndex + # ts3 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect2 deal is ", (ts3 - ts2) * 1000) + # ts4 = time.time() + # if gp.DebugPrint_flag: + # print("shish time detect3 deal is ", (ts4 - ts3) * 1000) + # tcpu1 = time.time() + boxes_fine = boxes.to('cpu') + labels_fine = labels.to('cpu') + # tcpu2 = time.time() + # if gp.DebugPrint_flag: + # print("to cpu timeis ", (tcpu2 - tcpu1) * 1000) + #############################Ä¿±ê×·×Ù£¬½«×·×ÙºóµÄ½á¹û·ÖΪ»÷ÖкÍδ»÷ÖÐÁ½²¿·Ö£¬Ç°ÕßÖ±½Ó´ÓÈ«¾Ö±äÁ¿SortLabel_IndexÖлñÈ¡label£¬ºóÕßÐèÒªÖØÐ½øÐÐϸÁ£¶Èʶ±ð£¬×îºó½«Á½Õß½øÐÐÆ´½Ó + #Êä³öΪboxes_fine [x1,y1,x2,y2,label,Index] + temp_sort = [i + 100 for i in range(len(labels_fine))] + DetFine = np.column_stack((boxes_fine, temp_sort, labels_fine)) + boxes_fine, indexmaxtemp, newObjectNum = SortRestart.update(DetFine) + IndexList = boxes_fine[:, -1].tolist() #½«indexÁÐÈ¡³öÀ´£¬Åжϵ±Ç°Ö¡¼ì²âµ½Á˶àÉÙÄ¿±ê + # newObjectNum = 0 + # if indexmaxtemp > gp.IndexMax: + # newObjectNum = indexmaxtemp - gp.IndexMax + # gp.IndexMax = indexmaxtemp + # print(indexmaxtemp,newObjectNum) + if (len(gp.SortLabel_Index) == 0): + if (len(boxes_fine)!=0): + boxes_fine_unmatched = [] # ÓÃÀ´´æ·Åµ±Ç°Ö¡Ã»Óл÷ÖеÄÄ¿±ê [xyxy, label,Index] + for c in IndexList: + boxes_fine_unmatched.append(boxes_fine[IndexList.index(c),:]) # δƥÅäµÄÄ¿±ê£¬ÐèÒª½øÒ»²½½øÐÐϸÁ£¶Èʶ±ð,ÓÃindexË÷Òýµ½ÊÇÄĸöÄ¿±ê£¬²¢½«¸ÃÄ¿±êµÄÊý¾Ý¶¼appendµ½unmatchÖÐ + # ¶Ô¼¯ÖÐÆ¥ÅäµÄÄ¿±ê£¬½«labelÌæ»»ÎªSortLabel_IndexÖеÄlabel£¬ÐèÒªÕë¶Ôindex½øÐÐË÷Òý + boxes_fine_unmatched = np.array(boxes_fine_unmatched) + # boxes_fine_matched ÓÃÓÚ×îºóÆ´½Ó [xyxy,label,index] + #####½øÐÐϸÁ£¶Èʶ±ð + boxes = boxes_fine_unmatched[:, 0:4] + labels = boxes_fine_unmatched[:, 4] + index_fine_unF = boxes_fine_unmatched[:, 5] + boxes_fine_unF, labels_fine_unF, index_fine_unF = self.fine_grained.inference(img, boxes, labels, index_fine_unF, 8) + # print(labels_fine_unF) + # ¸ñʽ [[xyxy]] [label1,label2...] [index1,index2...] + # ÏȶÔмì²âµÄÄ¿±ê½øÐмì²é£¬ÊÇ·ñÒѾ­´ïµ½5´ÎÒÔÉÏʶ±ð + ###¶ÔϸÁ£¶Èʶ±ð½á¹û½øÐкó´¦Àí + boxes_fine_unmatched[:, 4] = labels_fine_unF + boxes_fine_unmatched_temp = [] + for i in range(len(labels_fine_unF)): + if (len(gp.SortLabel_Indexpre)==0 ): # ˵Ã÷preÖÐûÓÐÄ¿±ê£¬Ôò¿ÉÒÔÖ±½Ó½«µ±Ç°µÄÄ¿±ê¼Ó½øÀ´ + temp_a = np.array([labels_fine_unF[i], index_fine_unF[i], 1]) + gp.SortLabel_Indexpre = np.expand_dims(np.append(gp.SortLabel_Indexpre, temp_a, axis=0), axis=0) + else: # ˵Ã÷±äÁ¿ÖÐÒѾ­ÓÐÄ¿±ê£¬ÐèÒª¶Ôÿ¸öÄ¿±êµÄ´ÎÊý½øÐмì²â + temp_a = np.array([labels_fine_unF[i], index_fine_unF[i], 1]) + temp_index = index_fine_unF[i] # µ±Ç°Ä¿±êµÄindex + index_list = gp.SortLabel_Indexpre[:, 1].tolist() # ÓÃÀ´Çó½âindex=nÔÚÊý×éÖеÄά¶ÈÐÅÏ¢£¬µÚ¼¸ÐÐ + if temp_index in gp.SortLabel_Indexpre[:, 1]: # ˵Ã÷δ¼ì²âµÄÄ¿±êÔÚpreÈ«¾ÖÖУ¬ÐèÒª½øÒ»²½¼ì²âÊÇ·ñ¼ì²â´ÎÊý³¬¹ýãÐÖµ´ÎÊý + # print("ϸÁ£¶Èʶ±ð´ÎÊý", gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)], gp.FineCountThresh) + if (gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)] >= gp.FineCountThresh): # ÔÚpreÈ«¾Ö±äÁ¿ÖУ¬µ±Ç°indexµÄÄ¿±ê£¬³öÏֵĴ˴¦ÒѾ­³¬¹ýãÐÖµ£¬ÔòÖ±½Ó½«¸ÃindexºÍ¶ÔÓ¦µÄlabel£¬appendµ½label_indexÈ«¾Ö±äÁ¿ÖУ¬²¢¸üе½µ±Ç°¼ì²â½á¹ûÖУ¬²¢½«¸ÃindexÔÚpreÖÐɾ³ýµô + index_dontthresh = [] + if (len(gp.SortLabel_Index.shape) == 1): # мì²â³öÒ»¸öÄ¿±êµÄʱºò£¬ÐèÒª¶ÔÈ«¾Ö±äÁ¿SortLabel_Index½øÐг¤¶È¼ì²â£¬Èç¹ûÔ­ÏÈÀïÃæÃ»ÓУ¬Ôò²»¶Ôa´¦Àí£¬Óеϰ£¬ÐèÒª¶Ôa½øÐÐÌí¼Óά¶È´¦Àí + a = np.array([labels_fine_unF[i], index_fine_unF[i]]) + #print("a ======", a) + #print("gp.SortLabel_Index ===", gp.SortLabel_Index) + # if a[1] in gp.SortLabel_Index[:,1]: #˵Ã÷indexÒѾ­ÔÚÀïÃæÁË + gp.SortLabel_Index = np.expand_dims( np.append(gp.SortLabel_Index, a, axis=0), axis=0) + #print("gp.SortLabel_Indexed ===", gp.SortLabel_Index) + gp.SortLabel_Indexpre = np.delete(gp.SortLabel_Indexpre,[index_list.index(temp_index)], axis=0) + # gp.SortLabel_Indexpre[index_list.index(temp_index),1] = 0 + else: + a = np.expand_dims(np.array([labels_fine_unF[i], index_fine_unF[i]]), axis=0) + #print("a ======", a) + #print("gp.SortLabel_Index ===", gp.SortLabel_Index) + # if a[1] in gp.SortLabel_Index[:,1]: #˵Ã÷indexÒѾ­ÔÚÀïÃæÁË + gp.SortLabel_Index = np.concatenate((gp.SortLabel_Index, a), axis=0) + #print("gp.SortLabel_Indexed ===", gp.SortLabel_Index) + gp.SortLabel_Indexpre = np.delete(gp.SortLabel_Indexpre, [index_list.index(temp_index)], axis=0) + #gp.SortLabel_Indexpre[index_list.index(temp_index), 1] = 0 + else: # ÔÚpreÈ«¾Ö±äÁ¿ÖУ¬µ±Ç°indexµÄÄ¿±ê£¬³öÏֵĴ˴¦Î´³¬¹ýãÐÖµ + gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)] += 1 + # boxes_fine_unmatched = np.delete(boxes_fine_unmatched, [boxes_fine_unmatched[:, -1].tolist().index(temp_index)], + # axis=0) # ½«µ±Ç°Ä¿±êÐÅÏ¢´Óunmatched Êý×éÖÐɾ³ýµô + boxes_fine_unmatched_temp = boxes_fine_unmatched + + boxes_fine_unmatched = np.delete(boxes_fine_unmatched, [ boxes_fine_unmatched[:, -1].tolist().index(temp_index)], axis=0) + boxes_fine_unmatched_temp[ boxes_fine_unmatched_temp[:, -1].tolist().index(temp_index), 4] = 0 + else: # ²»ÔÚpreÖУ¬Ö±½Ó½«µ±Ç°µÄÄ¿±êappendµ½preÈ«¾Ö±äÁ¿ÖÐ + gp.SortLabel_Indexpre = np.concatenate((gp.SortLabel_Indexpre, np.expand_dims(temp_a, axis=0)), axis=0) + # boxes_fine_unmatched = np.column_stack((boxes_fine_unF,labels_fine_unF)) #½«ÐÂʶ±ðµÄϸÁ£¶È½á¹ûºÍ±ß¿òÈںϵ½Ò»Æð£¬ºÍÔ­ÏȵĸñʽһÖ + # boxes_fine_unmatched = np.column_stack((boxes_fine_unmatched,index_fine_unF)) + boxes_fine = boxes_fine_unmatched + gp.SortLabel_Index = boxes_fine[:, 4:] # ¸üÐÂÈ«¾Ö±äÁ¿ÖеÄÐÅÏ¢ + #######ÐÞ¸Äbug£¬ÔÚ¾ö²ß¹ý³ÌÖУ¬Òª°Ñ±ß¿òÏÔʾ³öÀ´ + if len(boxes_fine_unmatched_temp) != 0: + boxes_fine = boxes_fine_unmatched_temp + else: + if [True for c in IndexList if c not in gp.SortLabel_Index[:, -1]]:#˵Ã÷ÓÐмì²â³öÀ´µÄ£¬ÐèÒª½øÐÐϸÁ£¶Èʶ±ð£¬²¢½«Ð´¦ÀíµÄ½á¹ûºÍindexÆ¥ÅäÒ»Æð¸üе½SortLabel_IndexÈ«¾Ö±äÁ¿ÀïÃæ + boxes_fine_unmatched = [] #ÓÃÀ´´æ·Åµ±Ç°Ö¡Ã»Óл÷ÖеÄÄ¿±ê [xyxy, label,Index] + boxes_fine_matched = [] #ÓÃÀ´´æ·Åµ±Ç°Ö¡»÷ÖеÄÄ¿±ê [xyxy,label,index] + for c in IndexList: + if c not in gp.SortLabel_Index[:, -1]: + boxes_fine_unmatched.append(boxes_fine[IndexList.index(c), :]) #δƥÅäµÄÄ¿±ê£¬ÐèÒª½øÒ»²½½øÐÐϸÁ£¶Èʶ±ð,ÓÃindexË÷Òýµ½ÊÇÄĸöÄ¿±ê£¬²¢½«¸ÃÄ¿±êµÄÊý¾Ý¶¼appendµ½unmatchÖÐ + else: + boxes_fine_matched.append(boxes_fine[IndexList.index(c), :]) #»÷ÖÐÆ¥ÅäµÄÄ¿±ê + #¶Ô¼¯ÖÐÆ¥ÅäµÄÄ¿±ê£¬½«labelÌæ»»ÎªSortLabel_IndexÖеÄlabel£¬ÐèÒªÕë¶Ôindex½øÐÐË÷Òý + boxes_fine_unmatched = np.array(boxes_fine_unmatched) + boxes_fine_matched = np.array(boxes_fine_matched) + for match_i in range(boxes_fine_matched.shape[0]): + SortLabel_Indextemp = gp.SortLabel_Index[:, 1].tolist() + if gp.DebugPrint_flag: + print(SortLabel_Indextemp) + boxes_fine_matched[match_i][4] = gp.SortLabel_Index[SortLabel_Indextemp.index(boxes_fine_matched[match_i][5]), 0] + #boxes_fine_matched ÓÃÓÚ×îºóÆ´½Ó [xyxy,label,index] + #####½øÐÐϸÁ£¶Èʶ±ð + boxes = boxes_fine_unmatched[:, 0:4] + labels = boxes_fine_unmatched[:, 4] + index_fine_unF = boxes_fine_unmatched[:, 5] + boxes_fine_unF, labels_fine_unF, index_fine_unF = self.fine_grained.inference(img, boxes, labels, index_fine_unF, 8) #¸ñʽ [[xyxy]] [label1,label2...] [index1,index2...] + #ÏȶÔмì²âµÄÄ¿±ê½øÐмì²é£¬ÊÇ·ñÒѾ­´ïµ½5´ÎÒÔÉÏʶ±ð + ###¶ÔϸÁ£¶Èʶ±ð½á¹û½øÐкó´¦Àí + boxes_fine_unmatched[:, 4] = labels_fine_unF + boxes_fine_unmatched_temp = [] + for i in range(len(labels_fine_unF)): + if (len(gp.SortLabel_Indexpre) == 0): #˵Ã÷preÖÐûÓÐÄ¿±ê£¬Ôò¿ÉÒÔÖ±½Ó½«µ±Ç°µÄÄ¿±ê¼Ó½øÀ´ + temp_a = np.array([labels_fine_unF[i], index_fine_unF[i], 1]) + gp.SortLabel_Indexpre = np.expand_dims(np.append(gp.SortLabel_Indexpre, temp_a, axis=0), axis=0) + else: #˵Ã÷±äÁ¿ÖÐÒѾ­ÓÐÄ¿±ê£¬ÐèÒª¶Ôÿ¸öÄ¿±êµÄ´ÎÊý½øÐмì²â + temp_a = np.array([labels_fine_unF[i], index_fine_unF[i], 1]) + temp_index = index_fine_unF[i] #µ±Ç°Ä¿±êµÄindex + index_list = gp.SortLabel_Indexpre[:, 1].tolist() #ÓÃÀ´Çó½âindex=nÔÚÊý×éÖеÄά¶ÈÐÅÏ¢£¬µÚ¼¸ÐÐ + if temp_index in gp.SortLabel_Indexpre[:, 1]: #˵Ã÷δ¼ì²âµÄÄ¿±êÔÚpreÈ«¾ÖÖУ¬ÐèÒª½øÒ»²½¼ì²âÊÇ·ñ¼ì²â´ÎÊý³¬¹ýãÐÖµ´ÎÊý + print("ϸÁ£¶Èʶ±ð´ÎÊý", gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)], gp.FineCountThresh) + if (gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)] >= gp.FineCountThresh ): #ÔÚpreÈ«¾Ö±äÁ¿ÖУ¬µ±Ç°indexµÄÄ¿±ê£¬³öÏֵĴ˴¦ÒѾ­³¬¹ýãÐÖµ£¬ÔòÖ±½Ó½«¸ÃindexºÍ¶ÔÓ¦µÄlabel£¬appendµ½label_indexÈ«¾Ö±äÁ¿ÖУ¬²¢¸üе½µ±Ç°¼ì²â½á¹ûÖУ¬²¢½«¸ÃindexÔÚpreÖÐɾ³ýµô + if (len(gp.SortLabel_Index) == 0): # мì²â³öÒ»¸öÄ¿±êµÄʱºò£¬ÐèÒª¶ÔÈ«¾Ö±äÁ¿SortLabel_Index½øÐг¤¶È¼ì²â£¬Èç¹ûÔ­ÏÈÀïÃæÃ»ÓУ¬Ôò²»¶Ôa´¦Àí£¬Óеϰ£¬ÐèÒª¶Ôa½øÐÐÌí¼Óά¶È´¦Àí + a = np.array([labels_fine_unF[i], index_fine_unF[i]]) + print("a ======", a) + print("gp.SortLabel_Index ===", gp.SortLabel_Index) + # if a[1] in gp.SortLabel_Index[:,1]: #˵Ã÷indexÒѾ­ÔÚÀïÃæÁË + gp.SortLabel_Index = np.expand_dims(np.concatenate((gp.SortLabel_Index, a), axis=0), axis=0) + print("gp.SortLabel_Indexed ===", gp.SortLabel_Index) + gp.SortLabel_Indexpre = np.delete(gp.SortLabel_Indexpre, [index_list.index(temp_index)], axis=0) + else: + a = np.expand_dims(np.array([labels_fine_unF[i], index_fine_unF[i]]), axis=0) + print("a ======", a) + print("gp.SortLabel_Index ===", gp.SortLabel_Index) + # if a[1] in gp.SortLabel_Index[:,1]: #˵Ã÷indexÒѾ­ÔÚÀïÃæÁË + gp.SortLabel_Index = np.concatenate((gp.SortLabel_Index, a), axis=0) + print("gp.SortLabel_Indexed ===", gp.SortLabel_Index) + gp.SortLabel_Indexpre = np.delete(gp.SortLabel_Indexpre, [index_list.index(temp_index)], axis=0) + + else: + boxes_fine_unmatched_temp = boxes_fine_unmatched + gp.SortLabel_Indexpre[:, -1][index_list.index(temp_index)] += 1 + boxes_fine_unmatched = np.delete(boxes_fine_unmatched, [boxes_fine_unmatched[:, -1].tolist().index(temp_index)], axis=0) #½«µ±Ç°Ä¿±êÐÅÏ¢´Óunmatched Êý×éÖÐɾ³ýµô + boxes_fine_unmatched_temp[boxes_fine_unmatched_temp[:, -1].tolist().index(temp_index), 4] = 0 + else: #²»ÔÚpreÖУ¬Ö±½Ó½«µ±Ç°µÄÄ¿±êappendµ½preÈ«¾Ö±äÁ¿ÖÐ + gp.SortLabel_Indexpre = np.concatenate((gp.SortLabel_Indexpre, np.expand_dims(temp_a, axis=0)), axis=0) + boxes_fine_unmatched = np.delete(boxes_fine_unmatched, [boxes_fine_unmatched[:, -1].tolist().index(temp_index)], axis=0) # ½«µ±Ç°Ä¿±êÐÅÏ¢´Óunmatched Êý×éÖÐɾ³ýµô + + # boxes_fine_unmatched = np.column_stack((boxes_fine_unF,labels_fine_unF)) #½«ÐÂʶ±ðµÄϸÁ£¶È½á¹ûºÍ±ß¿òÈںϵ½Ò»Æð£¬ºÍÔ­ÏȵĸñʽһÖ + # boxes_fine_unmatched = np.column_stack((boxes_fine_unmatched,index_fine_unF)) + if (len(boxes_fine_matched) == 0): + boxes_fine = boxes_fine_unmatched + elif (len(boxes_fine_unmatched) == 0): + boxes_fine = boxes_fine_matched + else: + boxes_fine = np.concatenate((boxes_fine_matched, boxes_fine_unmatched)) + gp.SortLabel_Index = boxes_fine[:, 4:] #¸üÐÂÈ«¾Ö±äÁ¿ÖеÄÐÅÏ¢ + #######ÐÞ¸Äbug£¬ÔÚ¾ö²ß¹ý³ÌÖУ¬Òª°Ñ±ß¿òÏÔʾ³öÀ´ + if len(boxes_fine_unmatched_temp) != 0: + if (len(boxes_fine_matched) == 0): + boxes_fine = boxes_fine_unmatched_temp + else: + boxes_fine = np.concatenate((boxes_fine_matched, boxes_fine_unmatched_temp)) + else: + for match_i in range(boxes_fine.shape[0]): + if gp.DebugPrint_flag: + print("gp.SortLabel_Index[:,1].tolist() = ", gp.SortLabel_Index[:, 1].tolist()) + print("boxes_fine[match_i][5] = ", boxes_fine[match_i][5]) + SortLabel_Indextemp = gp.SortLabel_Index[:, 1].tolist() + boxes_fine[match_i][4] = gp.SortLabel_Index[SortLabel_Indextemp.index(boxes_fine[match_i][5]), 0] + ################################# + classs_index = [1 for i in range(len(gp.BHG_chineseName))] # ¿ª±ÙÒ»¸ölist£¬³¤¶ÈºÍÄ¿±êÊýÁ¿Ò»Ö£¬Ã¿¸öÀïÃæ±£´æµÄÊÇclassµÄË÷Òý + for i in range(len(boxes_fine)): + # tprint1 = time.time() + xyxy = boxes_fine[i][:4] + cls = boxes_fine[i][4] + index = boxes_fine[i][5] + classs_index_show = classs_index[int(cls)] + classs_index[int(cls)] += 1 + # tprint2 = time.time() + # if gp.DebugPrint_flag: + # print("tprint1 is ", (tprint2 - tprint1) * 1000) + # tcls1 = time.time() + b = (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < 15000) + #a =(xyxy.item()[3] - xyxy.item()[1]) * (xyxy.item()[2] - xyxy.item()[0]) + # tcls2 = time.time() + # if gp.DebugPrint_flag: + # print("tcls1 is ", (tcls2 - tcls1) * 1000) + if cls == 0 or (((int(xyxy[3]) - int(xyxy[1])) * (int(xyxy[2]) - int(xyxy[0]))) < gp.fine_thresh2): + #if cls == gp.birdIndex or (torch.sub(torch.mul(torch.sub(xyxy[3], xyxy[1]), torch.sub(xyxy[2], xyxy[0])),gp.fine_thresh2) < 0): + label = gp.NoneLabel + else: + # tcls3 = time.time() + label = gp.BHG_chineseName[int(cls)] + #label = "{} No.{}".format(label,str(classs_index_show).zfill(3)) + spiec_number[int(cls)] += 1 + # tcls4 = time.time() + # if gp.DebugPrint_flag: + # print("tcls2 is ", (tcls4 - tcls3) * 1000) + # tprint3 = time.time() + # if gp.DebugPrint_flag: + # print("tprint2 is ", (tprint3 - tprint2) * 1000) + #label = f'{int(cls)} {conf:.2f}' + palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1) + colors = gp.color_box #tuple(int((p * (4 ** 2 - 4 + 1)) % 220) for p in palette) + # tprint4 = time.time() + # if gp.DebugPrint_flag: + # print("tprint3 is ", (tprint4 - tprint3) * 1000) + draw = plot_one_box(xyxy, draw, height_or, width_or, label=label, Index=index, color=colors, line_thickness=int(1.5 * gp.radioShowtext)) + # tpChin1 = time.time() + if num_image > gp.showThresh: + gp.num_count_old = len(boxes_fine) + gp.spiec_number_old = spiec_number + num_image = 0 + # tpChin2 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin1 is ", (tpChin2 - tpChin1) * 1000) + #if width_or == 2560: + if gp.ShowAllNumFlag: + draw = cv2AddChineseText(draw, "识别总数: {}只".format(str(gp.num_count_old)), (50 * gp.radioShowX, 1100 * gp.radioShowY), textColor=gp.color_show, textSize=int(50 * gp.radioShowtext)) + # tpChin3 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin2 is ", (tpChin3 - tpChin2) * 1000) + draw = cv2AddChineseText(draw, "分类识别:", (50 * gp.radioShowX, 1150 * gp.radioShowY), textColor=gp.color_show, + textSize=int(50 * gp.radioShowtext)) + # tpChin4 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin3 is ", (tpChin4 - tpChin3) * 1000) + for i in range(1, len(spiec_number)): + if i < 5: + draw = cv2AddChineseText(draw, "{}:{}只".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), + (300 * gp.radioShowX + (i - 1) * 280 * gp.radioShowX, 1150 * gp.radioShowY), + textColor=gp.color_show, + textSize=int(50* gp.radioShowtext)) + else: + draw = cv2AddChineseText(draw, "{}:{}只".format(str(gp.BHG_chineseName[i]), str(gp.spiec_number_old[i])), + (50 * gp.radioShowX + (i - 5) * 280 * gp.radioShowX, 1200 * gp.radioShowY), + textColor=gp.color_show, + textSize=int(50* gp.radioShowtext)) + img_show = cv2.cvtColor(np.asarray(img_show), cv2.COLOR_RGB2BGR) + gp.img_show = img_show + # tpChin2 = time.time() + # if gp.DebugPrint_flag: + # print("tpChin is ", (tpChin2 - tpChin1) * 1000) + #cv2.waitKey(0) + # cv2.imwrite("../data_MPKFNet/RTSP/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), + # image_or) + # cv2.imwrite( + # "../data_MPKFNet/RTSP/result/" + "{}.jpg".format(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))), + # self.img) + if gp.DebugPrint_flag: + print(self.name + " is finish") + num_image += 1 + return img_show, num_image + def getrestartresult(self, IndexMax): #Ä¿±ê×·×Ù×î´óµÄË÷Òý + list = [[] for i in range(IndexMax)] #ÓÃÀ´´æ·Å°´ÕÕIndexË÷ÒýµÄ²»Í¬Í¼Æ¬µÄ£¨bbox(x,y,x,y),label£© + for Index in range(1, IndexMax+1): #¶ÔËùÓпÉÄܵÄIndex½øÐбéÀú + for imagei in range(5): #¶ÔÎåÕÅͼƬ½á¹û½øÐбéÀú + a = gp.Finerestartboxes[imagei] + b = gp.Finerestartboxes[imagei][:, 5] + c = np.where(b == Index) + #ÐèÒªÓÅ»¯ + FinerestartboxesindexList = gp.Finerestartboxes[imagei][:, 5].tolist() + if Index in FinerestartboxesindexList: + RawIndex = FinerestartboxesindexList.index(Index) + else: + RawIndex = -1 + # RawIndex = np.where(gp.Finerestartboxes[imagei][:,5] == Index) #»ñÈ¡µ±Ç°Í¼Æ¬ÖУ¬µ±Ç°IndexËù¶ÔÓ¦µÄÐУ¬Ä¿µÄΪÁË»ñµÃ£¬µ±Ç°Í¼Æ¬Öе±Ç°index±àºÅµÄÄ¿±êµÄ£¨bbox(x,y,x,y),label£© + # if (RawIndex[0] == []) | (RawIndex == None): + # RawIndex = -1 + # else: + # RawIndex = RawIndex[0][0] + if RawIndex == -1 : #˵Ã÷ûÓÐÕÒµ½ + continue + else: + list[Index-1].append(gp.Finerestartboxes[imagei][RawIndex,-2:]) #½«£¨bbox(x,y,x,y),label,index£© È¡³öÀ´ + #µ±Ç°Í¼Æ¬±éÀú½áÊø£¬ÒѾ­ÕÒµ½Index¶ÔÓ¦µÄÄ¿±êÐÅÏ¢ + result = [] #ÓÃÀ´´æ·Å×îÖյĽá¹û ½á¹ûΪ¶þά + for Index in range(IndexMax):#£¨bbox(x,y,x,y),label,index£©*IndexMax + temp = np.array(list[Index]) #»ñÈ¡Index¶ÔÓ¦µÄ¶þάnumpy£¬ÔÚ²»Í¬Í¼Æ¬ÀïÃæµÄÄ¿±êÐÅÏ¢£¨bbox(x,y,x,y),label,index£© + print(type(temp)) + print(temp) + temp1 = temp.mean(axis=0) #¶Ô£¨bbox(x,y,x,y),label,index£©È¡Æ½¾ùÖµ£¬µ«ÊÇlabel²»ÄÜȡƽ¾ùÖµ£¬ÐèÒª¼ÌÐø´¦Àí,È¥µôÁËxyxy + temp2 = temp[:, 0] #È¡³öÀ´labelµÄÒ»ÁÐ + label_max = statistics.mode(temp2) #Çó³öÀ´³öÏÖlabel×î¶àµÄ½á¹û + temp1[0] = label_max #½«label_max Ìæ»»µ½Ô­ÏȵĽá¹ûÖÐ + result.append(temp1) + return np.array(result) + def systemPre(self, img, numPre): + height_or, width_or = img.shape[:2] + print("image size is ", height_or, width_or) + is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(img) + if is_ex_bird: + for i in range(len(boxes)): + if boxes[i][0] < 0: + boxes[i][0] = 0 + if boxes[i][1] < 0: + boxes[i][1] = 0 + if boxes[i][2] < 0: + boxes[i][2] = 0 + if boxes[i][3] < 0: + boxes[i][3] = 0 + for i in range(len(labels)): + labels[i] = 0 # gp.birdIndex + boxes_fine, labels_fine, scores_fine = self.fine_grained.inference(img, boxes, labels, scores, 8) + print("System preheating {} is ok".format(str(numPre))) + + +class Density_mul (threading.Thread): + def __init__(self, threadID, name, imagetime, DensityClass): + threading.Thread.__init__(self) + self.threadID = threadID + self.name = name + self.imagetime = imagetime + self.DensityClass = DensityClass + def run(self): + gp.Density_thread_flag = True + if gp.DebugPrint_flag: + print(self.name +self.imagetime," is starting") + i = 0 + while (i<=29): + # if(len(gp.ImgDealQueue)<=i): + # gp.event.wait() + # if ((i+1)%25==0): #˵Ã÷ÊǵÚ25*nÖ¡,¼ä¸ô1s´¦ÀíÒ»´Î + if gp.DebugPrint_flag: + print("Density is1 ", len(gp.ImgDealQueue), " ", i) + print("Density is waiting") + if (len(gp.ImgDealQueue) <= i): + gp.eventDensity.wait() + if gp.DebugPrint_flag: + print("Density is2 ", len(gp.ImgDealQueue), " ", i) + print("Density is not waiting") + self.DensityClass.inference(gp.ImgDealQueue[i],self.imagetime,str(i).zfill(4)) + gp.eventDensity.clear() + i += 1 + gp.Density_thread_flag = False + gp.is_ex_bird = False + gp.destory_image = True + if gp.DebugPrint_flag: + print(self.name + self.imagetime, " is over") +class Detection_mul (threading.Thread): + def __init__(self, threadID, name, imagetime, DetectionClass, Fine_grainedClass): + threading.Thread.__init__(self) + self.threadID = threadID + self.name = name + self.imagetime = imagetime + self.DetectionClass = DetectionClass + self.Fine_grainedClass = Fine_grainedClass + def run(self): + gp.Detection_thread_flag = True + if gp.DebugPrint_flag: + print(self.name, self.imagetime, " is starting") + i = 0 + while (i<=29): + if gp.DebugPrint_flag: + print("Detection is1 ", len(gp.ImgDealQueue), " ", i) + # if (len(gp.ImgDealQueue) <= i): + # gp.event.wait() + # if ((i+1)%25==0): #˵Ã÷ÊǵÚ25*nÖ¡,¼ä¸ô1s´¦ÀíÒ»´Î + print("Detection is waiting") + if (len(gp.ImgDealQueue) <= i): + gp.eventDetection.wait() + if gp.DebugPrint_flag: + print("Detection is2 ", len(gp.ImgDealQueue), " ", i) + print("Detection is not waiting") + self.DetectionClass.inference(gp.ImgDealQueue[i], self.imagetime, str(i).zfill(4), self.Fine_grainedClass) + gp.eventDetection.clear() + i += 1 + gp.Detection_thread_flag = False + gp.is_ex_bird = False + gp.destory_image = True + if gp.DebugPrint_flag: + print(self.name, self.imagetime, " is over") +class SaveImage_mul (threading.Thread): + def __init__(self, threadID, name, imagetime, root): + threading.Thread.__init__(self) + self.threadID = threadID + self.name = name + self.imagetime = imagetime + self.root = root + self.rootpath = os.path.join(self.root, self.imagetime) + def run(self): + gp.SaveImage_thread_flag = True + if not os.path.exists(self.rootpath): + os.mkdir(self.rootpath) + if not os.path.exists(self.rootpath + "/" + "RawImage" + "/"): + os.mkdir(self.rootpath + "/" + "RawImage" + "/") + if gp.DebugPrint_flag: + print(self.name, self.imagetime, " is starting") + i = 0 + while (i<=29): + # if(len(gp.ImgDealQueue)<=i): + # gp.event.wait() + # if ((i+1)%25==0): #˵Ã÷ÊǵÚ25*nÖ¡,¼ä¸ô1s´¦ÀíÒ»´Î + if gp.DebugPrint_flag: + print("Saveimage is1 ", len(gp.ImgDealQueue), " ", i) + print("Saveimage is waiting") + if (len(gp.ImgDealQueue) <= i): + gp.eventSaveimage.wait() + if gp.DebugPrint_flag: + print("Saveimage is2 ", len(gp.ImgDealQueue), " ", i) + print("Saveimage is not waiting") + cv2.imwrite(os.path.join(self.rootpath, "RawImage", "{}.jpg".format(str(i).zfill(4))), gp.ImgDealQueue[i]) + gp.eventSaveimage.clear() + if gp.DebugPrint_flag: + print("Saveimage finish once") + i += 1 + gp.SaveImage_thread_flag = False + gp.is_ex_bird = False + gp.destory_image = True + if gp.DebugPrint_flag: + print(self.name, self.imagetime, " is over") +class ThreadMonitor_mul (threading.Thread): + def __init__(self, threadID, name): + threading.Thread.__init__(self) + self.threadID = threadID + self.name = name + def run(self): + if gp.DebugPrint_flag: + print(self.name, " is starting") + while 1: + # print(gp.Density_thread_flag,gp.Detection_thread_flag,gp.SaveImage_thread_flag) + if (gp.Density_thread_flag) == False and (gp.Detection_thread_flag == False) and (gp.SaveImage_thread_flag == False): #˵Ã÷Èý¸ö½ø³Ì¶¼ÒѾ­½áÊøÁË + gp.ImgDealQueue = [] +class isopenmul (threading.Thread): + def __init__(self, threadID, name, DetectionClass): + threading.Thread.__init__(self) + self.threadID = threadID + self.name = name + self.DetectionClass = DetectionClass + def run(self): + while 1: + # print(gp.Density_thread_flag,gp.Detection_thread_flag,gp.SaveImage_thread_flag) + if (gp.Vedio_thread_flag == False) and (gp.Density_thread_flag == False) and ( + gp.Detection_thread_flag == False) and (gp.SaveImage_thread_flag == False) and ( + gp.is_ex_bird == False) and gp.num_detection > 24: + gp.num_detection = 0 + + if gp.DebugPrint_flag: + print("check is start") + gp.is_ex_bird, labels, boxes, scores = self.DetectionClass.check_object(gp.frame_openmul) + if gp.is_ex_bird: + if gp.DebugPrint_flag: + print(gp.is_ex_bird) + gp.image_time = gp.Camera_device + time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) + if gp.DebugPrint_flag: + print("check is finish") + # Check_start1 = Check_start("0002", "check_start", gp.frame_openmul, self.DetectionClass) + # Check_start1.start() + + +if __name__ == '__main__': + boxes_list = [[0, 0, 49, 49], [0, 0, 100, 100], [0, 0, 100, 100], [0, 0, 49, 49], [0, 0, 100, 100], [0, 0, 49, 49], [0, 0, 100, 100], [0, 0, 100, 100], [0, 0, 100, 100], [0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100],[0,0,100,100]] + label_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + score_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + boxes_list = torch.Tensor(boxes_list) + label_list = torch.Tensor(label_list) + score_list = torch.Tensor(score_list) + path = "/home/aibird/model/data_MPKFNet/testimage/20220324105705.jpg" + image = cv2.imread(path) + Fine_grained1 = Fine_grained_T(gp.devices, "root") + #image = torch.from_numpy(image) + boxes_fine, labels_fine, scores_fine = Fine_grained1.inference(image, boxes_list, label_list, score_list, 8) + print("ok") \ No newline at end of file diff --git a/Y5/models/__pycache__/__init__.cpython-36.pyc b/Y5/models/__pycache__/__init__.cpython-36.pyc old mode 100644 new mode 100755 index 2210b53..c169993 Binary files a/Y5/models/__pycache__/__init__.cpython-36.pyc and b/Y5/models/__pycache__/__init__.cpython-36.pyc differ diff --git a/Y5/models/__pycache__/__init__.cpython-37.pyc b/Y5/models/__pycache__/__init__.cpython-37.pyc new file mode 100755 index 0000000..7cc86e1 Binary files /dev/null and b/Y5/models/__pycache__/__init__.cpython-37.pyc differ diff --git a/Y5/models/__pycache__/__init__.cpython-38.pyc b/Y5/models/__pycache__/__init__.cpython-38.pyc new file mode 100755 index 0000000..3193edf Binary files /dev/null and b/Y5/models/__pycache__/__init__.cpython-38.pyc differ diff --git a/Y5/models/__pycache__/__init__.cpython-39.pyc b/Y5/models/__pycache__/__init__.cpython-39.pyc new file mode 100755 index 0000000..26e3bdc Binary files /dev/null and b/Y5/models/__pycache__/__init__.cpython-39.pyc differ diff --git a/Y5/models/__pycache__/common.cpython-36.pyc b/Y5/models/__pycache__/common.cpython-36.pyc old mode 100644 new mode 100755 index d98635d..2f4de88 Binary files a/Y5/models/__pycache__/common.cpython-36.pyc and b/Y5/models/__pycache__/common.cpython-36.pyc differ diff --git a/Y5/models/__pycache__/common.cpython-37.pyc b/Y5/models/__pycache__/common.cpython-37.pyc new file mode 100755 index 0000000..c3724f4 Binary files /dev/null and b/Y5/models/__pycache__/common.cpython-37.pyc differ diff --git a/Y5/models/__pycache__/common.cpython-38.pyc b/Y5/models/__pycache__/common.cpython-38.pyc new file mode 100755 index 0000000..0fc5a76 Binary files /dev/null and b/Y5/models/__pycache__/common.cpython-38.pyc differ diff --git a/Y5/models/__pycache__/common.cpython-39.pyc b/Y5/models/__pycache__/common.cpython-39.pyc new file mode 100755 index 0000000..e29775d Binary files /dev/null and b/Y5/models/__pycache__/common.cpython-39.pyc differ diff --git a/Y5/models/__pycache__/experimental.cpython-36.pyc b/Y5/models/__pycache__/experimental.cpython-36.pyc old mode 100644 new mode 100755 index 0e64e98..2d1a49c Binary files a/Y5/models/__pycache__/experimental.cpython-36.pyc and b/Y5/models/__pycache__/experimental.cpython-36.pyc differ diff --git a/Y5/models/__pycache__/experimental.cpython-37.pyc b/Y5/models/__pycache__/experimental.cpython-37.pyc new file mode 100755 index 0000000..add642f Binary files /dev/null and b/Y5/models/__pycache__/experimental.cpython-37.pyc differ diff --git a/Y5/models/__pycache__/experimental.cpython-38.pyc b/Y5/models/__pycache__/experimental.cpython-38.pyc new file mode 100755 index 0000000..fed85b9 Binary files /dev/null and b/Y5/models/__pycache__/experimental.cpython-38.pyc differ diff --git a/Y5/models/__pycache__/experimental.cpython-39.pyc b/Y5/models/__pycache__/experimental.cpython-39.pyc new file mode 100755 index 0000000..0ffeebb Binary files /dev/null and b/Y5/models/__pycache__/experimental.cpython-39.pyc differ diff --git a/Y5/models/__pycache__/yolo.cpython-36.pyc b/Y5/models/__pycache__/yolo.cpython-36.pyc old mode 100644 new mode 100755 index 18aee99..bfa4f70 Binary files a/Y5/models/__pycache__/yolo.cpython-36.pyc and b/Y5/models/__pycache__/yolo.cpython-36.pyc differ diff --git a/Y5/models/__pycache__/yolo.cpython-37.pyc b/Y5/models/__pycache__/yolo.cpython-37.pyc new file mode 100755 index 0000000..f7aa26e Binary files /dev/null and b/Y5/models/__pycache__/yolo.cpython-37.pyc differ diff --git a/Y5/models/__pycache__/yolo.cpython-38.pyc b/Y5/models/__pycache__/yolo.cpython-38.pyc new file mode 100755 index 0000000..42f5f26 Binary files /dev/null and b/Y5/models/__pycache__/yolo.cpython-38.pyc differ diff --git a/Y5/models/__pycache__/yolo.cpython-39.pyc b/Y5/models/__pycache__/yolo.cpython-39.pyc new file mode 100755 index 0000000..1698818 Binary files /dev/null and b/Y5/models/__pycache__/yolo.cpython-39.pyc differ diff --git a/Y5/models/common.py b/Y5/models/common.py index 5464691..66467a0 100755 --- a/Y5/models/common.py +++ b/Y5/models/common.py @@ -1,18 +1,31 @@ -# This file contains modules common to various models +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Common modules +""" +import json import math +import platform +import warnings +from collections import OrderedDict, namedtuple +from copy import copy from pathlib import Path -import sys -sys.path.append("..") + +import cv2 import numpy as np +import pandas as pd import requests import torch import torch.nn as nn +import yaml from PIL import Image +from torch.cuda import amp -from Y5.utils.datasets import letterbox -from Y5.utils.general import non_max_suppression, make_divisible, scale_coords, xyxy2xywh -from Y5.utils.plots import color_list, plot_one_box +from utils.dataloaders import exif_transpose, letterbox +from utils.general import (LOGGER, check_requirements, check_suffix, check_version, colorstr, increment_path, + make_divisible, non_max_suppression, scale_coords, xywh2xyxy, xyxy2xywh) +from utils.plots import Annotator, colors, save_one_box +from utils.torch_utils import copy_attr, time_sync def autopad(k, p=None): # kernel, padding @@ -22,15 +35,10 @@ def autopad(k, p=None): # kernel, padding return p -def DWConv(c1, c2, k=1, s=1, act=True): - # Depthwise convolution - return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act) - - class Conv(nn.Module): # Standard convolution def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups - super(Conv, self).__init__() + super().__init__() self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False) self.bn = nn.BatchNorm2d(c2) self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity()) @@ -38,14 +46,62 @@ class Conv(nn.Module): def forward(self, x): return self.act(self.bn(self.conv(x))) - def fuseforward(self, x): + def forward_fuse(self, x): return self.act(self.conv(x)) +class DWConv(Conv): + # Depth-wise convolution class + def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act) + + +class DWConvTranspose2d(nn.ConvTranspose2d): + # Depth-wise transpose convolution class + def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, kernel, stride, padding, padding_out + super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2)) + + +class TransformerLayer(nn.Module): + # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance) + def __init__(self, c, num_heads): + super().__init__() + self.q = nn.Linear(c, c, bias=False) + self.k = nn.Linear(c, c, bias=False) + self.v = nn.Linear(c, c, bias=False) + self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads) + self.fc1 = nn.Linear(c, c, bias=False) + self.fc2 = nn.Linear(c, c, bias=False) + + def forward(self, x): + x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x + x = self.fc2(self.fc1(x)) + x + return x + + +class TransformerBlock(nn.Module): + # Vision Transformer https://arxiv.org/abs/2010.11929 + def __init__(self, c1, c2, num_heads, num_layers): + super().__init__() + self.conv = None + if c1 != c2: + self.conv = Conv(c1, c2) + self.linear = nn.Linear(c2, c2) # learnable position embedding + self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers))) + self.c2 = c2 + + def forward(self, x): + if self.conv is not None: + x = self.conv(x) + b, _, w, h = x.shape + p = x.flatten(2).permute(2, 0, 1) + return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h) + + class Bottleneck(nn.Module): # Standard bottleneck def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion - super(Bottleneck, self).__init__() + super().__init__() c_ = int(c2 * e) # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c_, c2, 3, 1, g=g) @@ -58,41 +114,86 @@ class Bottleneck(nn.Module): class BottleneckCSP(nn.Module): # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion - super(BottleneckCSP, self).__init__() + super().__init__() c_ = int(c2 * e) # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) self.cv4 = Conv(2 * c_, c2, 1, 1) self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) - self.act = nn.LeakyReLU(0.1, inplace=True) - self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) + self.act = nn.SiLU() + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) def forward(self, x): y1 = self.cv3(self.m(self.cv1(x))) y2 = self.cv2(x) - return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1)))) + return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1)))) + + +class CrossConv(nn.Module): + # Cross Convolution Downsample + def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): + # ch_in, ch_out, kernel, stride, groups, expansion, shortcut + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, (1, k), (1, s)) + self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x): + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) class C3(nn.Module): # CSP Bottleneck with 3 convolutions def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion - super(C3, self).__init__() + super().__init__() c_ = int(c2 * e) # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c1, c_, 1, 1) - self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2) - self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) - # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)]) + self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2) + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) def forward(self, x): - return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1)) + return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)) + + +class C3x(C3): + # C3 module with cross-convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n))) + + +class C3TR(C3): + # C3 module with TransformerBlock() + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = TransformerBlock(c_, c_, 4, n) + + +class C3SPP(C3): + # C3 module with SPP() + def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = SPP(c_, c_, k) + + +class C3Ghost(C3): + # C3 module with GhostBottleneck() + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) # hidden channels + self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n))) class SPP(nn.Module): - # Spatial pyramid pooling layer used in YOLOv3-SPP + # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729 def __init__(self, c1, c2, k=(5, 9, 13)): - super(SPP, self).__init__() + super().__init__() c_ = c1 // 2 # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) @@ -100,21 +201,70 @@ class SPP(nn.Module): def forward(self, x): x = self.cv1(x) - return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning + return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) + + +class SPPF(nn.Module): + # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher + def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13)) + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_ * 4, c2, 1, 1) + self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) + + def forward(self, x): + x = self.cv1(x) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning + y1 = self.m(x) + y2 = self.m(y1) + return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1)) class Focus(nn.Module): # Focus wh information into c-space def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups - super(Focus, self).__init__() + super().__init__() self.conv = Conv(c1 * 4, c2, k, s, p, g, act) # self.contract = Contract(gain=2) def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) - return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)) + return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1)) # return self.conv(self.contract(x)) +class GhostConv(nn.Module): + # Ghost Convolution https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups + super().__init__() + c_ = c2 // 2 # hidden channels + self.cv1 = Conv(c1, c_, k, s, None, g, act) + self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) + + def forward(self, x): + y = self.cv1(x) + return torch.cat((y, self.cv2(y)), 1) + + +class GhostBottleneck(nn.Module): + # Ghost Bottleneck https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride + super().__init__() + c_ = c2 // 2 + self.conv = nn.Sequential( + GhostConv(c1, c_, 1, 1), # pw + DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw + GhostConv(c_, c2, 1, 1, act=False)) # pw-linear + self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, + act=False)) if s == 2 else nn.Identity() + + def forward(self, x): + return self.conv(x) + self.shortcut(x) + + class Contract(nn.Module): # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40) def __init__(self, gain=2): @@ -122,11 +272,11 @@ class Contract(nn.Module): self.gain = gain def forward(self, x): - N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain' + b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain' s = self.gain - x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2) + x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2) x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40) - return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40) + return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40) class Expand(nn.Module): @@ -136,170 +286,449 @@ class Expand(nn.Module): self.gain = gain def forward(self, x): - N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain' + b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain' s = self.gain - x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80) + x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80) x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2) - return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160) + return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160) class Concat(nn.Module): # Concatenate a list of tensors along dimension def __init__(self, dimension=1): - super(Concat, self).__init__() + super().__init__() self.d = dimension def forward(self, x): return torch.cat(x, self.d) -class NMS(nn.Module): - # Non-Maximum Suppression (NMS) module - conf = 0.25 # confidence threshold - iou = 0.45 # IoU threshold - classes = None # (optional list) filter by class +class DetectMultiBackend(nn.Module): + # YOLOv5 MultiBackend class for python inference on various backends + def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False): + # Usage: + # PyTorch: weights = *.pt + # TorchScript: *.torchscript + # ONNX Runtime: *.onnx + # ONNX OpenCV DNN: *.onnx with --dnn + # OpenVINO: *.xml + # CoreML: *.mlmodel + # TensorRT: *.engine + # TensorFlow SavedModel: *_saved_model + # TensorFlow GraphDef: *.pb + # TensorFlow Lite: *.tflite + # TensorFlow Edge TPU: *_edgetpu.tflite + from models.experimental import attempt_download, attempt_load # scoped to avoid circular import - def __init__(self): - super(NMS, self).__init__() + super().__init__() + w = str(weights[0] if isinstance(weights, list) else weights) + pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = self.model_type(w) # get backend + w = attempt_download(w) # download if not local + fp16 &= (pt or jit or onnx or engine) and device.type != 'cpu' # FP16 + stride, names = 32, [f'class{i}' for i in range(1000)] # assign defaults + if data: # assign class names (optional) + with open(data, errors='ignore') as f: + names = yaml.safe_load(f)['names'] - def forward(self, x): - return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) + if pt: # PyTorch + model = attempt_load(weights if isinstance(weights, list) else w, device=device) + stride = max(int(model.stride.max()), 32) # model stride + names = model.module.names if hasattr(model, 'module') else model.names # get class names + model.half() if fp16 else model.float() + self.model = model # explicitly assign for to(), cpu(), cuda(), half() + elif jit: # TorchScript + LOGGER.info(f'Loading {w} for TorchScript inference...') + extra_files = {'config.txt': ''} # model metadata + model = torch.jit.load(w, _extra_files=extra_files) + model.half() if fp16 else model.float() + if extra_files['config.txt']: + d = json.loads(extra_files['config.txt']) # extra_files dict + stride, names = int(d['stride']), d['names'] + elif dnn: # ONNX OpenCV DNN + LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...') + check_requirements(('opencv-python>=4.5.4',)) + net = cv2.dnn.readNetFromONNX(w) + elif onnx: # ONNX Runtime + LOGGER.info(f'Loading {w} for ONNX Runtime inference...') + cuda = torch.cuda.is_available() + check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime')) + import onnxruntime + providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider'] + session = onnxruntime.InferenceSession(w, providers=providers) + meta = session.get_modelmeta().custom_metadata_map # metadata + if 'stride' in meta: + stride, names = int(meta['stride']), eval(meta['names']) + elif xml: # OpenVINO + LOGGER.info(f'Loading {w} for OpenVINO inference...') + check_requirements(('openvino',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/ + from openvino.runtime import Core + ie = Core() + if not Path(w).is_file(): # if not *.xml + w = next(Path(w).glob('*.xml')) # get *.xml file from *_openvino_model dir + network = ie.read_model(model=w, weights=Path(w).with_suffix('.bin')) + executable_network = ie.compile_model(model=network, device_name="CPU") + output_layer = next(iter(executable_network.outputs)) + meta = Path(w).with_suffix('.yaml') + if meta.exists(): + stride, names = self._load_metadata(meta) # load metadata + elif engine: # TensorRT + LOGGER.info(f'Loading {w} for TensorRT inference...') + import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download + check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0 + Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr')) + logger = trt.Logger(trt.Logger.INFO) + with open(w, 'rb') as f, trt.Runtime(logger) as runtime: + model = runtime.deserialize_cuda_engine(f.read()) + bindings = OrderedDict() + fp16 = False # default updated below + for index in range(model.num_bindings): + name = model.get_binding_name(index) + dtype = trt.nptype(model.get_binding_dtype(index)) + shape = tuple(model.get_binding_shape(index)) + data = torch.from_numpy(np.empty(shape, dtype=np.dtype(dtype))).to(device) + bindings[name] = Binding(name, dtype, shape, data, int(data.data_ptr())) + if model.binding_is_input(index) and dtype == np.float16: + fp16 = True + binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items()) + context = model.create_execution_context() + batch_size = bindings['images'].shape[0] + elif coreml: # CoreML + LOGGER.info(f'Loading {w} for CoreML inference...') + import coremltools as ct + model = ct.models.MLModel(w) + else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU) + if saved_model: # SavedModel + LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...') + import tensorflow as tf + keras = False # assume TF1 saved_model + model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w) + elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt + LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...') + import tensorflow as tf + + def wrap_frozen_graph(gd, inputs, outputs): + x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped + ge = x.graph.as_graph_element + return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs)) + + gd = tf.Graph().as_graph_def() # graph_def + with open(w, 'rb') as f: + gd.ParseFromString(f.read()) + frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs="Identity:0") + elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python + try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu + from tflite_runtime.interpreter import Interpreter, load_delegate + except ImportError: + import tensorflow as tf + Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate, + if edgetpu: # Edge TPU https://coral.ai/software/#edgetpu-runtime + LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...') + delegate = { + 'Linux': 'libedgetpu.so.1', + 'Darwin': 'libedgetpu.1.dylib', + 'Windows': 'edgetpu.dll'}[platform.system()] + interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)]) + else: # Lite + LOGGER.info(f'Loading {w} for TensorFlow Lite inference...') + interpreter = Interpreter(model_path=w) # load TFLite model + interpreter.allocate_tensors() # allocate + input_details = interpreter.get_input_details() # inputs + output_details = interpreter.get_output_details() # outputs + elif tfjs: + raise Exception('ERROR: YOLOv5 TF.js inference is not supported') + self.__dict__.update(locals()) # assign all variables to self + + def forward(self, im, augment=False, visualize=False, val=False): + # YOLOv5 MultiBackend inference + b, ch, h, w = im.shape # batch, channel, height, width + if self.pt: # PyTorch + y = self.model(im, augment=augment, visualize=visualize)[0] + elif self.jit: # TorchScript + y = self.model(im)[0] + elif self.dnn: # ONNX OpenCV DNN + im = im.cpu().numpy() # torch to numpy + self.net.setInput(im) + y = self.net.forward() + elif self.onnx: # ONNX Runtime + im = im.cpu().numpy() # torch to numpy + y = self.session.run([self.session.get_outputs()[0].name], {self.session.get_inputs()[0].name: im})[0] + elif self.xml: # OpenVINO + im = im.cpu().numpy() # FP32 + y = self.executable_network([im])[self.output_layer] + elif self.engine: # TensorRT + assert im.shape == self.bindings['images'].shape, (im.shape, self.bindings['images'].shape) + self.binding_addrs['images'] = int(im.data_ptr()) + self.context.execute_v2(list(self.binding_addrs.values())) + y = self.bindings['output'].data + elif self.coreml: # CoreML + im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3) + im = Image.fromarray((im[0] * 255).astype('uint8')) + # im = im.resize((192, 320), Image.ANTIALIAS) + y = self.model.predict({'image': im}) # coordinates are xywh normalized + if 'confidence' in y: + box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels + conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float) + y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1) + else: + k = 'var_' + str(sorted(int(k.replace('var_', '')) for k in y)[-1]) # output key + y = y[k] # output + else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU) + im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3) + if self.saved_model: # SavedModel + y = (self.model(im, training=False) if self.keras else self.model(im)).numpy() + elif self.pb: # GraphDef + y = self.frozen_func(x=self.tf.constant(im)).numpy() + else: # Lite or Edge TPU + input, output = self.input_details[0], self.output_details[0] + int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model + if int8: + scale, zero_point = input['quantization'] + im = (im / scale + zero_point).astype(np.uint8) # de-scale + self.interpreter.set_tensor(input['index'], im) + self.interpreter.invoke() + y = self.interpreter.get_tensor(output['index']) + if int8: + scale, zero_point = output['quantization'] + y = (y.astype(np.float32) - zero_point) * scale # re-scale + y[..., :4] *= [w, h, w, h] # xywh normalized to pixels + + if isinstance(y, np.ndarray): + y = torch.tensor(y, device=self.device) + return (y, []) if val else y + + def warmup(self, imgsz=(1, 3, 640, 640)): + # Warmup model by running inference once + warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb + if any(warmup_types) and self.device.type != 'cpu': + im = torch.zeros(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input + for _ in range(2 if self.jit else 1): # + self.forward(im) # warmup + + @staticmethod + def model_type(p='path/to/model.pt'): + # Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx + from export import export_formats + suffixes = list(export_formats().Suffix) + ['.xml'] # export suffixes + check_suffix(p, suffixes) # checks + p = Path(p).name # eliminate trailing separators + pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, xml2 = (s in p for s in suffixes) + xml |= xml2 # *_openvino_model or *.xml + tflite &= not edgetpu # *.tflite + return pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs + + @staticmethod + def _load_metadata(f='path/to/meta.yaml'): + # Load metadata from meta.yaml if it exists + with open(f, errors='ignore') as f: + d = yaml.safe_load(f) + return d['stride'], d['names'] # assign stride, names -class autoShape(nn.Module): - # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS - img_size = 640 # inference size (pixels) +class AutoShape(nn.Module): + # YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS conf = 0.25 # NMS confidence threshold iou = 0.45 # NMS IoU threshold - classes = None # (optional list) filter by class + agnostic = False # NMS class-agnostic + multi_label = False # NMS multiple labels per box + classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs + max_det = 1000 # maximum number of detections per image + amp = False # Automatic Mixed Precision (AMP) inference - def __init__(self, model): - super(autoShape, self).__init__() + def __init__(self, model, verbose=True): + super().__init__() + if verbose: + LOGGER.info('Adding AutoShape... ') + copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=()) # copy attributes + self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance + self.pt = not self.dmb or model.pt # PyTorch model self.model = model.eval() - def autoshape(self): - print('autoShape already enabled, skipping... ') # model already converted to model.autoshape() + def _apply(self, fn): + # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers + self = super()._apply(fn) + if self.pt: + m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect() + m.stride = fn(m.stride) + m.grid = list(map(fn, m.grid)) + if isinstance(m.anchor_grid, list): + m.anchor_grid = list(map(fn, m.anchor_grid)) return self + @torch.no_grad() def forward(self, imgs, size=640, augment=False, profile=False): - # Inference from various sources. For height=720, width=1280, RGB images example inputs are: - # filename: imgs = 'data/samples/zidane.jpg' - # URI: = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg' - # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(720,1280,3) - # PIL: = Image.open('image.jpg') # HWC x(720,1280,3) - # numpy: = np.zeros((720,1280,3)) # HWC - # torch: = torch.zeros(16,3,720,1280) # BCHW + # Inference from various sources. For height=640, width=1280, RGB images example inputs are: + # file: imgs = 'data/images/zidane.jpg' # str or PosixPath + # URI: = 'https://ultralytics.com/images/zidane.jpg' + # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3) + # PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3) + # numpy: = np.zeros((640,1280,3)) # HWC + # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values) # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images - p = next(self.model.parameters()) # for device and type + t = [time_sync()] + p = next(self.model.parameters()) if self.pt else torch.zeros(1, device=self.model.device) # for device, type + autocast = self.amp and (p.device.type != 'cpu') # Automatic Mixed Precision (AMP) inference if isinstance(imgs, torch.Tensor): # torch - return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference + with amp.autocast(autocast): + return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference # Pre-process - n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images + n, imgs = (len(imgs), list(imgs)) if isinstance(imgs, (list, tuple)) else (1, [imgs]) # number, list of images shape0, shape1, files = [], [], [] # image and inference shapes, filenames for i, im in enumerate(imgs): - if isinstance(im, str): # filename or uri - im, f = Image.open(requests.get(im, stream=True).raw if im.startswith('http') else im), im # open - im.filename = f # for uri - files.append(Path(im.filename).with_suffix('.jpg').name if isinstance(im, Image.Image) else f'image{i}.jpg') - im = np.array(im) # to numpy + f = f'image{i}' # filename + if isinstance(im, (str, Path)): # filename or uri + im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im + im = np.asarray(exif_transpose(im)) + elif isinstance(im, Image.Image): # PIL Image + im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f + files.append(Path(f).with_suffix('.jpg').name) if im.shape[0] < 5: # image in CHW im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1) - im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input + im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3) # enforce 3ch input s = im.shape[:2] # HWC shape0.append(s) # image shape g = (size / max(s)) # gain shape1.append([y * g for y in s]) - imgs[i] = im # update - shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape - x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad - x = np.stack(x, 0) if n > 1 else x[0][None] # stack - x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW - x = torch.from_numpy(x).to(p.device).type_as(p) / 255. # uint8 to fp16/32 + imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update + shape1 = [make_divisible(x, self.stride) if self.pt else size for x in np.array(shape1).max(0)] # inf shape + x = [letterbox(im, shape1, auto=False)[0] for im in imgs] # pad + x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHW + x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32 + t.append(time_sync()) - # Inference - with torch.no_grad(): - y = self.model(x, augment, profile)[0] # forward - y = non_max_suppression(y, conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) # NMS + with amp.autocast(autocast): + # Inference + y = self.model(x, augment, profile) # forward + t.append(time_sync()) - # Post-process - for i in range(n): - scale_coords(shape1, y[i][:, :4], shape0[i]) + # Post-process + y = non_max_suppression(y if self.dmb else y[0], + self.conf, + self.iou, + self.classes, + self.agnostic, + self.multi_label, + max_det=self.max_det) # NMS + for i in range(n): + scale_coords(shape1, y[i][:, :4], shape0[i]) - return Detections(imgs, y, files, self.names) + t.append(time_sync()) + return Detections(imgs, y, files, t, self.names, x.shape) class Detections: - # detections class for YOLOv5 inference results - def __init__(self, imgs, pred, files, names=None): - super(Detections, self).__init__() + # YOLOv5 detections class for inference results + def __init__(self, imgs, pred, files, times=(0, 0, 0, 0), names=None, shape=None): + super().__init__() d = pred[0].device # device - gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs] # normalizations + gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in imgs] # normalizations self.imgs = imgs # list of images as numpy arrays self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls) self.names = names # class names self.files = files # image filenames + self.times = times # profiling times self.xyxy = pred # xyxy pixels self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized - self.n = len(self.pred) + self.n = len(self.pred) # number of images (batch size) + self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms) + self.s = shape # inference BCHW shape - def display(self, pprint=False, show=False, save=False, render=False, save_dir=''): - colors = color_list() - for i, (img, pred) in enumerate(zip(self.imgs, self.pred)): - str = f'image {i + 1}/{len(self.pred)}: {img.shape[0]}x{img.shape[1]} ' - if pred is not None: + def display(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')): + crops = [] + for i, (im, pred) in enumerate(zip(self.imgs, self.pred)): + s = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string + if pred.shape[0]: for c in pred[:, -1].unique(): n = (pred[:, -1] == c).sum() # detections per class - str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string - if show or save or render: - for *box, conf, cls in pred: # xyxy, confidence, class + s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string + if show or save or render or crop: + annotator = Annotator(im, example=str(self.names)) + for *box, conf, cls in reversed(pred): # xyxy, confidence, class label = f'{self.names[int(cls)]} {conf:.2f}' - plot_one_box(box, img, label=label, color=colors[int(cls) % 10]) - img = Image.fromarray(img.astype(np.uint8)) if isinstance(img, np.ndarray) else img # from np + if crop: + file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None + crops.append({ + 'box': box, + 'conf': conf, + 'cls': cls, + 'label': label, + 'im': save_one_box(box, im, file=file, save=save)}) + else: # all others + annotator.box_label(box, label if labels else '', color=colors(cls)) + im = annotator.im + else: + s += '(no detections)' + + im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np if pprint: - print(str.rstrip(', ')) + print(s.rstrip(', ')) if show: - img.show(self.files[i]) # show + im.show(self.files[i]) # show if save: - f = Path(save_dir) / self.files[i] - img.save(f) # save - print(f"{'Saving' * (i == 0)} {f},", end='' if i < self.n - 1 else ' done.\n') + f = self.files[i] + im.save(save_dir / f) # save + if i == self.n - 1: + LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}") if render: - self.imgs[i] = np.asarray(img) + self.imgs[i] = np.asarray(im) + if crop: + if save: + LOGGER.info(f'Saved results to {save_dir}\n') + return crops def print(self): self.display(pprint=True) # print results + print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' % self.t) - def show(self): - self.display(show=True) # show results + def show(self, labels=True): + self.display(show=True, labels=labels) # show results - def save(self, save_dir='results/'): - Path(save_dir).mkdir(exist_ok=True) - self.display(save=True, save_dir=save_dir) # save results + def save(self, labels=True, save_dir='runs/detect/exp'): + save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir + self.display(save=True, labels=labels, save_dir=save_dir) # save results - def render(self): - self.display(render=True) # render results + def crop(self, save=True, save_dir='runs/detect/exp'): + save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) if save else None + return self.display(crop=True, save=save, save_dir=save_dir) # crop results + + def render(self, labels=True): + self.display(render=True, labels=labels) # render results return self.imgs - def __len__(self): - return self.n + def pandas(self): + # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0]) + new = copy(self) # return copy + ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns + cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns + for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]): + a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update + setattr(new, k, [pd.DataFrame(x, columns=c) for x in a]) + return new def tolist(self): # return a list of Detections objects, i.e. 'for result in results.tolist():' - x = [Detections([self.imgs[i]], [self.pred[i]], self.names) for i in range(self.n)] - for d in x: - for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']: - setattr(d, k, getattr(d, k)[0]) # pop out of list + r = range(self.n) # iterable + x = [Detections([self.imgs[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r] + # for d in x: + # for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']: + # setattr(d, k, getattr(d, k)[0]) # pop out of list return x + def __len__(self): + return self.n # override len(results) + + def __str__(self): + self.print() # override print(results) + return '' + class Classify(nn.Module): # Classification head, i.e. x(b,c1,20,20) to x(b,c2) def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups - super(Classify, self).__init__() + super().__init__() self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1) self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1) self.flat = nn.Flatten() diff --git a/Y5/models/experimental.py b/Y5/models/experimental.py index a818590..db8e5b8 100755 --- a/Y5/models/experimental.py +++ b/Y5/models/experimental.py @@ -1,36 +1,25 @@ -# This file contains experimental modules +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Experimental modules +""" +import math import numpy as np import torch import torch.nn as nn - -from Y5.models.common import Conv, DWConv -from Y5.utils.google_utils import attempt_download - - -class CrossConv(nn.Module): - # Cross Convolution Downsample - def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): - # ch_in, ch_out, kernel, stride, groups, expansion, shortcut - super(CrossConv, self).__init__() - c_ = int(c2 * e) # hidden channels - self.cv1 = Conv(c1, c_, (1, k), (1, s)) - self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) - self.add = shortcut and c1 == c2 - - def forward(self, x): - return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) +from models.common import Conv +from utils.downloads import attempt_download class Sum(nn.Module): # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 def __init__(self, n, weight=False): # n: number of inputs - super(Sum, self).__init__() + super().__init__() self.weight = weight # apply weights boolean self.iter = range(n - 1) # iter object if weight: - self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights + self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights def forward(self, x): y = x[0] # no weight @@ -44,92 +33,72 @@ class Sum(nn.Module): return y -class GhostConv(nn.Module): - # Ghost Convolution https://github.com/huawei-noah/ghostnet - def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups - super(GhostConv, self).__init__() - c_ = c2 // 2 # hidden channels - self.cv1 = Conv(c1, c_, k, s, None, g, act) - self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) - - def forward(self, x): - y = self.cv1(x) - return torch.cat([y, self.cv2(y)], 1) - - -class GhostBottleneck(nn.Module): - # Ghost Bottleneck https://github.com/huawei-noah/ghostnet - def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride - super(GhostBottleneck, self).__init__() - c_ = c2 // 2 - self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw - DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw - GhostConv(c_, c2, 1, 1, act=False)) # pw-linear - self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), - Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() - - def forward(self, x): - return self.conv(x) + self.shortcut(x) - - class MixConv2d(nn.Module): - # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595 - def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): - super(MixConv2d, self).__init__() - groups = len(k) + # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595 + def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy + super().__init__() + n = len(k) # number of convolutions if equal_ch: # equal c_ per group - i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices - c_ = [(i == g).sum() for g in range(groups)] # intermediate channels + i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices + c_ = [(i == g).sum() for g in range(n)] # intermediate channels else: # equal weight.numel() per group - b = [c2] + [0] * groups - a = np.eye(groups + 1, groups, k=-1) + b = [c2] + [0] * n + a = np.eye(n + 1, n, k=-1) a -= np.roll(a, 1, axis=1) a *= np.array(k) ** 2 a[0] = 1 c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b - self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)]) + self.m = nn.ModuleList([ + nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)]) self.bn = nn.BatchNorm2d(c2) - self.act = nn.LeakyReLU(0.1, inplace=True) + self.act = nn.SiLU() def forward(self, x): - return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) + return self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) class Ensemble(nn.ModuleList): # Ensemble of models def __init__(self): - super(Ensemble, self).__init__() + super().__init__() - def forward(self, x, augment=False): - y = [] - for module in self: - y.append(module(x, augment)[0]) + def forward(self, x, augment=False, profile=False, visualize=False): + y = [module(x, augment, profile, visualize)[0] for module in self] # y = torch.stack(y).max(0)[0] # max ensemble # y = torch.stack(y).mean(0) # mean ensemble y = torch.cat(y, 1) # nms ensemble return y, None # inference, train output -def attempt_load(weights, map_location=None): +def attempt_load(weights, device=None, inplace=True, fuse=True): # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a + from models.yolo import Detect, Model + model = Ensemble() for w in weights if isinstance(weights, list) else [weights]: - attempt_download(w) - ckpt = torch.load(w, map_location=map_location) # load - model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model + ckpt = torch.load(attempt_download(w), map_location='cpu') # load + ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model + model.append(ckpt.fuse().eval() if fuse else ckpt.eval()) # fused or un-fused model in eval mode # Compatibility updates for m in model.modules(): - if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]: - m.inplace = True # pytorch 1.7.0 compatibility - elif type(m) is Conv: - m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility + t = type(m) + if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model): + m.inplace = inplace # torch 1.7.0 compatibility + if t is Detect and not isinstance(m.anchor_grid, list): + delattr(m, 'anchor_grid') + setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl) + elif t is Conv: + m._non_persistent_buffers_set = set() # torch 1.6.0 compatibility + elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'): + m.recompute_scale_factor = None # torch 1.11.0 compatibility if len(model) == 1: return model[-1] # return model - else: - print('Ensemble created with %s\n' % weights) - for k in ['names', 'stride']: - setattr(model, k, getattr(model[-1], k)) - return model # return ensemble + print(f'Ensemble created with {weights}\n') + for k in 'names', 'nc', 'yaml': + setattr(model, k, getattr(model[0], k)) + model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride + assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}' + return model # return ensemble diff --git a/Y5/models/hub/anchors.yaml b/Y5/models/hub/anchors.yaml index a07a4dc..e4d7beb 100755 --- a/Y5/models/hub/anchors.yaml +++ b/Y5/models/hub/anchors.yaml @@ -1,58 +1,59 @@ -# Default YOLOv5 anchors for COCO data +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Default anchors for COCO data # P5 ------------------------------------------------------------------------------------------------------------------- # P5-640: anchors_p5_640: - - [ 10,13, 16,30, 33,23 ] # P3/8 - - [ 30,61, 62,45, 59,119 ] # P4/16 - - [ 116,90, 156,198, 373,326 ] # P5/32 + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 # P6 ------------------------------------------------------------------------------------------------------------------- # P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387 anchors_p6_640: - - [ 9,11, 21,19, 17,41 ] # P3/8 - - [ 43,32, 39,70, 86,64 ] # P4/16 - - [ 65,131, 134,130, 120,265 ] # P5/32 - - [ 282,180, 247,354, 512,387 ] # P6/64 + - [9,11, 21,19, 17,41] # P3/8 + - [43,32, 39,70, 86,64] # P4/16 + - [65,131, 134,130, 120,265] # P5/32 + - [282,180, 247,354, 512,387] # P6/64 # P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792 anchors_p6_1280: - - [ 19,27, 44,40, 38,94 ] # P3/8 - - [ 96,68, 86,152, 180,137 ] # P4/16 - - [ 140,301, 303,264, 238,542 ] # P5/32 - - [ 436,615, 739,380, 925,792 ] # P6/64 + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 # P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187 anchors_p6_1920: - - [ 28,41, 67,59, 57,141 ] # P3/8 - - [ 144,103, 129,227, 270,205 ] # P4/16 - - [ 209,452, 455,396, 358,812 ] # P5/32 - - [ 653,922, 1109,570, 1387,1187 ] # P6/64 + - [28,41, 67,59, 57,141] # P3/8 + - [144,103, 129,227, 270,205] # P4/16 + - [209,452, 455,396, 358,812] # P5/32 + - [653,922, 1109,570, 1387,1187] # P6/64 # P7 ------------------------------------------------------------------------------------------------------------------- # P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372 anchors_p7_640: - - [ 11,11, 13,30, 29,20 ] # P3/8 - - [ 30,46, 61,38, 39,92 ] # P4/16 - - [ 78,80, 146,66, 79,163 ] # P5/32 - - [ 149,150, 321,143, 157,303 ] # P6/64 - - [ 257,402, 359,290, 524,372 ] # P7/128 + - [11,11, 13,30, 29,20] # P3/8 + - [30,46, 61,38, 39,92] # P4/16 + - [78,80, 146,66, 79,163] # P5/32 + - [149,150, 321,143, 157,303] # P6/64 + - [257,402, 359,290, 524,372] # P7/128 # P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818 anchors_p7_1280: - - [ 19,22, 54,36, 32,77 ] # P3/8 - - [ 70,83, 138,71, 75,173 ] # P4/16 - - [ 165,159, 148,334, 375,151 ] # P5/32 - - [ 334,317, 251,626, 499,474 ] # P6/64 - - [ 750,326, 534,814, 1079,818 ] # P7/128 + - [19,22, 54,36, 32,77] # P3/8 + - [70,83, 138,71, 75,173] # P4/16 + - [165,159, 148,334, 375,151] # P5/32 + - [334,317, 251,626, 499,474] # P6/64 + - [750,326, 534,814, 1079,818] # P7/128 # P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227 anchors_p7_1920: - - [ 29,34, 81,55, 47,115 ] # P3/8 - - [ 105,124, 207,107, 113,259 ] # P4/16 - - [ 247,238, 222,500, 563,227 ] # P5/32 - - [ 501,476, 376,939, 749,711 ] # P6/64 - - [ 1126,489, 801,1222, 1618,1227 ] # P7/128 + - [29,34, 81,55, 47,115] # P3/8 + - [105,124, 207,107, 113,259] # P4/16 + - [247,238, 222,500, 563,227] # P5/32 + - [501,476, 376,939, 749,711] # P6/64 + - [1126,489, 801,1222, 1618,1227] # P7/128 diff --git a/Y5/models/hub/yolov3-spp.yaml b/Y5/models/hub/yolov3-spp.yaml index 38dcc44..c669821 100755 --- a/Y5/models/hub/yolov3-spp.yaml +++ b/Y5/models/hub/yolov3-spp.yaml @@ -1,9 +1,9 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.0 # model depth multiple width_multiple: 1.0 # layer channel multiple - -# anchors anchors: - [10,13, 16,30, 33,23] # P3/8 - [30,61, 62,45, 59,119] # P4/16 diff --git a/Y5/models/hub/yolov3-tiny.yaml b/Y5/models/hub/yolov3-tiny.yaml index ff7638c..b28b443 100755 --- a/Y5/models/hub/yolov3-tiny.yaml +++ b/Y5/models/hub/yolov3-tiny.yaml @@ -1,9 +1,9 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.0 # model depth multiple width_multiple: 1.0 # layer channel multiple - -# anchors anchors: - [10,14, 23,27, 37,58] # P4/16 - [81,82, 135,169, 344,319] # P5/32 diff --git a/Y5/models/hub/yolov3.yaml b/Y5/models/hub/yolov3.yaml index f2e7613..d1ef912 100755 --- a/Y5/models/hub/yolov3.yaml +++ b/Y5/models/hub/yolov3.yaml @@ -1,9 +1,9 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.0 # model depth multiple width_multiple: 1.0 # layer channel multiple - -# anchors anchors: - [10,13, 16,30, 33,23] # P3/8 - [30,61, 62,45, 59,119] # P4/16 @@ -28,7 +28,7 @@ backbone: # YOLOv3 head head: [[-1, 1, Bottleneck, [1024, False]], - [-1, 1, Conv, [512, [1, 1]]], + [-1, 1, Conv, [512, 1, 1]], [-1, 1, Conv, [1024, 3, 1]], [-1, 1, Conv, [512, 1, 1]], [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) diff --git a/Y5/models/hub/yolov5-bifpn.yaml b/Y5/models/hub/yolov5-bifpn.yaml new file mode 100755 index 0000000..504815f --- /dev/null +++ b/Y5/models/hub/yolov5-bifpn.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 BiFPN head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14, 6], 1, Concat, [1]], # cat P4 <--- BiFPN change + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5/models/hub/yolov5-fpn.yaml b/Y5/models/hub/yolov5-fpn.yaml index e772bff..a23e9c6 100755 --- a/Y5/models/hub/yolov5-fpn.yaml +++ b/Y5/models/hub/yolov5-fpn.yaml @@ -1,42 +1,42 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.0 # model depth multiple width_multiple: 1.0 # layer channel multiple - -# anchors anchors: - [10,13, 16,30, 33,23] # P3/8 - [30,61, 62,45, 59,119] # P4/16 - [116,90, 156,198, 373,326] # P5/32 -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 - [-1, 3, Bottleneck, [128]], + [-1, 3, C3, [128]], [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 - [-1, 9, BottleneckCSP, [256]], + [-1, 6, C3, [256]], [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 - [-1, 9, BottleneckCSP, [512]], + [-1, 9, C3, [512]], [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 - [-1, 1, SPP, [1024, [5, 9, 13]]], - [-1, 6, BottleneckCSP, [1024]], # 9 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 ] -# YOLOv5 FPN head +# YOLOv5 v6.0 FPN head head: - [[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large) + [[-1, 3, C3, [1024, False]], # 10 (P5/32-large) [-1, 1, nn.Upsample, [None, 2, 'nearest']], [[-1, 6], 1, Concat, [1]], # cat backbone P4 [-1, 1, Conv, [512, 1, 1]], - [-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium) + [-1, 3, C3, [512, False]], # 14 (P4/16-medium) [-1, 1, nn.Upsample, [None, 2, 'nearest']], [[-1, 4], 1, Concat, [1]], # cat backbone P3 [-1, 1, Conv, [256, 1, 1]], - [-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small) + [-1, 3, C3, [256, False]], # 18 (P3/8-small) [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) ] diff --git a/Y5/models/hub/yolov5-p2.yaml b/Y5/models/hub/yolov5-p2.yaml index 0633a90..554117d 100755 --- a/Y5/models/hub/yolov5-p2.yaml +++ b/Y5/models/hub/yolov5-p2.yaml @@ -1,54 +1,54 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.0 # model depth multiple width_multiple: 1.0 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer -# anchors -anchors: 3 - -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 - [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 - [ -1, 3, C3, [ 128 ] ], - [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 - [ -1, 9, C3, [ 256 ] ], - [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 - [ -1, 9, C3, [ 512 ] ], - [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32 - [ -1, 1, SPP, [ 1024, [ 5, 9, 13 ] ] ], - [ -1, 3, C3, [ 1024, False ] ], # 9 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 ] -# YOLOv5 head +# YOLOv5 v6.0 head with (P2, P3, P4, P5) outputs head: - [ [ -1, 1, Conv, [ 512, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 - [ -1, 3, C3, [ 512, False ] ], # 13 + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 - [ -1, 1, Conv, [ 256, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 - [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small) + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) - [ -1, 1, Conv, [ 128, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 2 ], 1, Concat, [ 1 ] ], # cat backbone P2 - [ -1, 1, C3, [ 128, False ] ], # 21 (P2/4-xsmall) + [-1, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 2], 1, Concat, [1]], # cat backbone P2 + [-1, 1, C3, [128, False]], # 21 (P2/4-xsmall) - [ -1, 1, Conv, [ 128, 3, 2 ] ], - [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P3 - [ -1, 3, C3, [ 256, False ] ], # 24 (P3/8-small) + [-1, 1, Conv, [128, 3, 2]], + [[-1, 18], 1, Concat, [1]], # cat head P3 + [-1, 3, C3, [256, False]], # 24 (P3/8-small) - [ -1, 1, Conv, [ 256, 3, 2 ] ], - [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4 - [ -1, 3, C3, [ 512, False ] ], # 27 (P4/16-medium) + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 27 (P4/16-medium) - [ -1, 1, Conv, [ 512, 3, 2 ] ], - [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat head P5 - [ -1, 3, C3, [ 1024, False ] ], # 30 (P5/32-large) + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 30 (P5/32-large) - [ [ 24, 27, 30 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5) + [[21, 24, 27, 30], 1, Detect, [nc, anchors]], # Detect(P2, P3, P4, P5) ] diff --git a/Y5/models/hub/yolov5-p34.yaml b/Y5/models/hub/yolov5-p34.yaml new file mode 100755 index 0000000..dbf0f85 --- /dev/null +++ b/Y5/models/hub/yolov5-p34.yaml @@ -0,0 +1,41 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [ [ -1, 1, Conv, [ 64, 6, 2, 2 ] ], # 0-P1/2 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 + [ -1, 3, C3, [ 128 ] ], + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 + [ -1, 6, C3, [ 256 ] ], + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 + [ -1, 9, C3, [ 512 ] ], + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32 + [ -1, 3, C3, [ 1024 ] ], + [ -1, 1, SPPF, [ 1024, 5 ] ], # 9 + ] + +# YOLOv5 v6.0 head with (P3, P4) outputs +head: + [ [ -1, 1, Conv, [ 512, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 + [ -1, 3, C3, [ 512, False ] ], # 13 + + [ -1, 1, Conv, [ 256, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 + [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small) + + [ -1, 1, Conv, [ 256, 3, 2 ] ], + [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4 + [ -1, 3, C3, [ 512, False ] ], # 20 (P4/16-medium) + + [ [ 17, 20 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4) + ] diff --git a/Y5/models/hub/yolov5-p6.yaml b/Y5/models/hub/yolov5-p6.yaml index 3728a11..a17202f 100755 --- a/Y5/models/hub/yolov5-p6.yaml +++ b/Y5/models/hub/yolov5-p6.yaml @@ -1,56 +1,56 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.0 # model depth multiple width_multiple: 1.0 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer -# anchors -anchors: 3 - -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 - [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 - [ -1, 3, C3, [ 128 ] ], - [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 - [ -1, 9, C3, [ 256 ] ], - [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 - [ -1, 9, C3, [ 512 ] ], - [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 - [ -1, 3, C3, [ 768 ] ], - [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 - [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], - [ -1, 3, C3, [ 1024, False ] ], # 11 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 ] -# YOLOv5 head +# YOLOv5 v6.0 head with (P3, P4, P5, P6) outputs head: - [ [ -1, 1, Conv, [ 768, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 - [ -1, 3, C3, [ 768, False ] ], # 15 + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 - [ -1, 1, Conv, [ 512, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 - [ -1, 3, C3, [ 512, False ] ], # 19 + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 - [ -1, 1, Conv, [ 256, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 - [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) - [ -1, 1, Conv, [ 256, 3, 2 ] ], - [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 - [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) - [ -1, 1, Conv, [ 512, 3, 2 ] ], - [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 - [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) - [ -1, 1, Conv, [ 768, 3, 2 ] ], - [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 - [ -1, 3, C3, [ 1024, False ] ], # 32 (P5/64-xlarge) + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) - [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) ] diff --git a/Y5/models/hub/yolov5-p7.yaml b/Y5/models/hub/yolov5-p7.yaml index ca8f849..edd7d13 100755 --- a/Y5/models/hub/yolov5-p7.yaml +++ b/Y5/models/hub/yolov5-p7.yaml @@ -1,67 +1,67 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.0 # model depth multiple width_multiple: 1.0 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer -# anchors -anchors: 3 - -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 - [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 - [ -1, 3, C3, [ 128 ] ], - [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 - [ -1, 9, C3, [ 256 ] ], - [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 - [ -1, 9, C3, [ 512 ] ], - [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 - [ -1, 3, C3, [ 768 ] ], - [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 - [ -1, 3, C3, [ 1024 ] ], - [ -1, 1, Conv, [ 1280, 3, 2 ] ], # 11-P7/128 - [ -1, 1, SPP, [ 1280, [ 3, 5 ] ] ], - [ -1, 3, C3, [ 1280, False ] ], # 13 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, Conv, [1280, 3, 2]], # 11-P7/128 + [-1, 3, C3, [1280]], + [-1, 1, SPPF, [1280, 5]], # 13 ] -# YOLOv5 head +# YOLOv5 v6.0 head with (P3, P4, P5, P6, P7) outputs head: - [ [ -1, 1, Conv, [ 1024, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat backbone P6 - [ -1, 3, C3, [ 1024, False ] ], # 17 + [[-1, 1, Conv, [1024, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 10], 1, Concat, [1]], # cat backbone P6 + [-1, 3, C3, [1024, False]], # 17 - [ -1, 1, Conv, [ 768, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 - [ -1, 3, C3, [ 768, False ] ], # 21 + [-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 21 - [ -1, 1, Conv, [ 512, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 - [ -1, 3, C3, [ 512, False ] ], # 25 + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 25 - [ -1, 1, Conv, [ 256, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 - [ -1, 3, C3, [ 256, False ] ], # 29 (P3/8-small) + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 29 (P3/8-small) - [ -1, 1, Conv, [ 256, 3, 2 ] ], - [ [ -1, 26 ], 1, Concat, [ 1 ] ], # cat head P4 - [ -1, 3, C3, [ 512, False ] ], # 32 (P4/16-medium) + [-1, 1, Conv, [256, 3, 2]], + [[-1, 26], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 32 (P4/16-medium) - [ -1, 1, Conv, [ 512, 3, 2 ] ], - [ [ -1, 22 ], 1, Concat, [ 1 ] ], # cat head P5 - [ -1, 3, C3, [ 768, False ] ], # 35 (P5/32-large) + [-1, 1, Conv, [512, 3, 2]], + [[-1, 22], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 35 (P5/32-large) - [ -1, 1, Conv, [ 768, 3, 2 ] ], - [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P6 - [ -1, 3, C3, [ 1024, False ] ], # 38 (P6/64-xlarge) + [-1, 1, Conv, [768, 3, 2]], + [[-1, 18], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 38 (P6/64-xlarge) - [ -1, 1, Conv, [ 1024, 3, 2 ] ], - [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P7 - [ -1, 3, C3, [ 1280, False ] ], # 41 (P7/128-xxlarge) + [-1, 1, Conv, [1024, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P7 + [-1, 3, C3, [1280, False]], # 41 (P7/128-xxlarge) - [ [ 29, 32, 35, 38, 41 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6, P7) + [[29, 32, 35, 38, 41], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6, P7) ] diff --git a/Y5/models/hub/yolov5-panet.yaml b/Y5/models/hub/yolov5-panet.yaml index 340f95a..ccfbf90 100755 --- a/Y5/models/hub/yolov5-panet.yaml +++ b/Y5/models/hub/yolov5-panet.yaml @@ -1,48 +1,48 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.0 # model depth multiple width_multiple: 1.0 # layer channel multiple - -# anchors anchors: - [10,13, 16,30, 33,23] # P3/8 - [30,61, 62,45, 59,119] # P4/16 - [116,90, 156,198, 373,326] # P5/32 -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 - [-1, 3, BottleneckCSP, [128]], + [-1, 3, C3, [128]], [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 - [-1, 9, BottleneckCSP, [256]], + [-1, 6, C3, [256]], [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 - [-1, 9, BottleneckCSP, [512]], + [-1, 9, C3, [512]], [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 - [-1, 1, SPP, [1024, [5, 9, 13]]], - [-1, 3, BottleneckCSP, [1024, False]], # 9 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 ] -# YOLOv5 PANet head +# YOLOv5 v6.0 PANet head head: [[-1, 1, Conv, [512, 1, 1]], [-1, 1, nn.Upsample, [None, 2, 'nearest']], [[-1, 6], 1, Concat, [1]], # cat backbone P4 - [-1, 3, BottleneckCSP, [512, False]], # 13 + [-1, 3, C3, [512, False]], # 13 [-1, 1, Conv, [256, 1, 1]], [-1, 1, nn.Upsample, [None, 2, 'nearest']], [[-1, 4], 1, Concat, [1]], # cat backbone P3 - [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small) + [-1, 3, C3, [256, False]], # 17 (P3/8-small) [-1, 1, Conv, [256, 3, 2]], [[-1, 14], 1, Concat, [1]], # cat head P4 - [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium) + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) [-1, 1, Conv, [512, 3, 2]], [[-1, 10], 1, Concat, [1]], # cat head P5 - [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large) + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) ] diff --git a/Y5/models/hub/yolov5l6.yaml b/Y5/models/hub/yolov5l6.yaml index 11298b0..632c2cb 100755 --- a/Y5/models/hub/yolov5l6.yaml +++ b/Y5/models/hub/yolov5l6.yaml @@ -1,60 +1,60 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.0 # model depth multiple width_multiple: 1.0 # layer channel multiple - -# anchors anchors: - - [ 19,27, 44,40, 38,94 ] # P3/8 - - [ 96,68, 86,152, 180,137 ] # P4/16 - - [ 140,301, 303,264, 238,542 ] # P5/32 - - [ 436,615, 739,380, 925,792 ] # P6/64 + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 - [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 - [ -1, 3, C3, [ 128 ] ], - [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 - [ -1, 9, C3, [ 256 ] ], - [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 - [ -1, 9, C3, [ 512 ] ], - [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 - [ -1, 3, C3, [ 768 ] ], - [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 - [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], - [ -1, 3, C3, [ 1024, False ] ], # 11 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 ] -# YOLOv5 head +# YOLOv5 v6.0 head head: - [ [ -1, 1, Conv, [ 768, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 - [ -1, 3, C3, [ 768, False ] ], # 15 + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 - [ -1, 1, Conv, [ 512, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 - [ -1, 3, C3, [ 512, False ] ], # 19 + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 - [ -1, 1, Conv, [ 256, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 - [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) - [ -1, 1, Conv, [ 256, 3, 2 ] ], - [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 - [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) - [ -1, 1, Conv, [ 512, 3, 2 ] ], - [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 - [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) - [ -1, 1, Conv, [ 768, 3, 2 ] ], - [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 - [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) - [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) ] diff --git a/Y5/models/hub/yolov5m6.yaml b/Y5/models/hub/yolov5m6.yaml index 48afc86..ecc53fd 100755 --- a/Y5/models/hub/yolov5m6.yaml +++ b/Y5/models/hub/yolov5m6.yaml @@ -1,60 +1,60 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 0.67 # model depth multiple width_multiple: 0.75 # layer channel multiple - -# anchors anchors: - - [ 19,27, 44,40, 38,94 ] # P3/8 - - [ 96,68, 86,152, 180,137 ] # P4/16 - - [ 140,301, 303,264, 238,542 ] # P5/32 - - [ 436,615, 739,380, 925,792 ] # P6/64 + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 - [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 - [ -1, 3, C3, [ 128 ] ], - [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 - [ -1, 9, C3, [ 256 ] ], - [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 - [ -1, 9, C3, [ 512 ] ], - [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 - [ -1, 3, C3, [ 768 ] ], - [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 - [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], - [ -1, 3, C3, [ 1024, False ] ], # 11 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 ] -# YOLOv5 head +# YOLOv5 v6.0 head head: - [ [ -1, 1, Conv, [ 768, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 - [ -1, 3, C3, [ 768, False ] ], # 15 + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 - [ -1, 1, Conv, [ 512, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 - [ -1, 3, C3, [ 512, False ] ], # 19 + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 - [ -1, 1, Conv, [ 256, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 - [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) - [ -1, 1, Conv, [ 256, 3, 2 ] ], - [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 - [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) - [ -1, 1, Conv, [ 512, 3, 2 ] ], - [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 - [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) - [ -1, 1, Conv, [ 768, 3, 2 ] ], - [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 - [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) - [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) ] diff --git a/Y5/models/hub/yolov5n6.yaml b/Y5/models/hub/yolov5n6.yaml new file mode 100755 index 0000000..0c0c71d --- /dev/null +++ b/Y5/models/hub/yolov5n6.yaml @@ -0,0 +1,60 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.25 # layer channel multiple +anchors: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5/models/hub/yolov5s-ghost.yaml b/Y5/models/hub/yolov5s-ghost.yaml new file mode 100755 index 0000000..ff9519c --- /dev/null +++ b/Y5/models/hub/yolov5s-ghost.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, GhostConv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3Ghost, [128]], + [-1, 1, GhostConv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3Ghost, [256]], + [-1, 1, GhostConv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3Ghost, [512]], + [-1, 1, GhostConv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3Ghost, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, GhostConv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3Ghost, [512, False]], # 13 + + [-1, 1, GhostConv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3Ghost, [256, False]], # 17 (P3/8-small) + + [-1, 1, GhostConv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3Ghost, [512, False]], # 20 (P4/16-medium) + + [-1, 1, GhostConv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3Ghost, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5/models/hub/yolov5s-transformer.yaml b/Y5/models/hub/yolov5s-transformer.yaml new file mode 100755 index 0000000..100d7c4 --- /dev/null +++ b/Y5/models/hub/yolov5s-transformer.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3TR, [1024]], # 9 <--- C3TR() Transformer module + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5/models/hub/yolov5s6.yaml b/Y5/models/hub/yolov5s6.yaml index 1df577a..a28fb55 100755 --- a/Y5/models/hub/yolov5s6.yaml +++ b/Y5/models/hub/yolov5s6.yaml @@ -1,60 +1,60 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 0.33 # model depth multiple width_multiple: 0.50 # layer channel multiple - -# anchors anchors: - - [ 19,27, 44,40, 38,94 ] # P3/8 - - [ 96,68, 86,152, 180,137 ] # P4/16 - - [ 140,301, 303,264, 238,542 ] # P5/32 - - [ 436,615, 739,380, 925,792 ] # P6/64 + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 - [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 - [ -1, 3, C3, [ 128 ] ], - [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 - [ -1, 9, C3, [ 256 ] ], - [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 - [ -1, 9, C3, [ 512 ] ], - [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 - [ -1, 3, C3, [ 768 ] ], - [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 - [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], - [ -1, 3, C3, [ 1024, False ] ], # 11 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 ] -# YOLOv5 head +# YOLOv5 v6.0 head head: - [ [ -1, 1, Conv, [ 768, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 - [ -1, 3, C3, [ 768, False ] ], # 15 + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 - [ -1, 1, Conv, [ 512, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 - [ -1, 3, C3, [ 512, False ] ], # 19 + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 - [ -1, 1, Conv, [ 256, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 - [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) - [ -1, 1, Conv, [ 256, 3, 2 ] ], - [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 - [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) - [ -1, 1, Conv, [ 512, 3, 2 ] ], - [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 - [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) - [ -1, 1, Conv, [ 768, 3, 2 ] ], - [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 - [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) - [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) ] diff --git a/Y5/models/hub/yolov5x6.yaml b/Y5/models/hub/yolov5x6.yaml index 5ebc021..ba795c4 100755 --- a/Y5/models/hub/yolov5x6.yaml +++ b/Y5/models/hub/yolov5x6.yaml @@ -1,60 +1,60 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.33 # model depth multiple width_multiple: 1.25 # layer channel multiple - -# anchors anchors: - - [ 19,27, 44,40, 38,94 ] # P3/8 - - [ 96,68, 86,152, 180,137 ] # P4/16 - - [ 140,301, 303,264, 238,542 ] # P5/32 - - [ 436,615, 739,380, 925,792 ] # P6/64 + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 - [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 - [ -1, 3, C3, [ 128 ] ], - [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 - [ -1, 9, C3, [ 256 ] ], - [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 - [ -1, 9, C3, [ 512 ] ], - [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 - [ -1, 3, C3, [ 768 ] ], - [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 - [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], - [ -1, 3, C3, [ 1024, False ] ], # 11 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 ] -# YOLOv5 head +# YOLOv5 v6.0 head head: - [ [ -1, 1, Conv, [ 768, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 - [ -1, 3, C3, [ 768, False ] ], # 15 + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 - [ -1, 1, Conv, [ 512, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 - [ -1, 3, C3, [ 512, False ] ], # 19 + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 - [ -1, 1, Conv, [ 256, 1, 1 ] ], - [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], - [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 - [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) - [ -1, 1, Conv, [ 256, 3, 2 ] ], - [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 - [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) - [ -1, 1, Conv, [ 512, 3, 2 ] ], - [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 - [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) - [ -1, 1, Conv, [ 768, 3, 2 ] ], - [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 - [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) - [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) ] diff --git a/Y5/models/tf.py b/Y5/models/tf.py new file mode 100755 index 0000000..b0d98cc --- /dev/null +++ b/Y5/models/tf.py @@ -0,0 +1,574 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +TensorFlow, Keras and TFLite versions of YOLOv5 +Authored by https://github.com/zldrobit in PR https://github.com/ultralytics/yolov5/pull/1127 + +Usage: + $ python models/tf.py --weights yolov5s.pt + +Export: + $ python path/to/export.py --weights yolov5s.pt --include saved_model pb tflite tfjs +""" + +import argparse +import sys +from copy import deepcopy +from pathlib import Path + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +# ROOT = ROOT.relative_to(Path.cwd()) # relative + +import numpy as np +import tensorflow as tf +import torch +import torch.nn as nn +from tensorflow import keras + +from models.common import (C3, SPP, SPPF, Bottleneck, BottleneckCSP, C3x, Concat, Conv, CrossConv, DWConv, + DWConvTranspose2d, Focus, autopad) +from models.experimental import MixConv2d, attempt_load +from models.yolo import Detect +from utils.activations import SiLU +from utils.general import LOGGER, make_divisible, print_args + + +class TFBN(keras.layers.Layer): + # TensorFlow BatchNormalization wrapper + def __init__(self, w=None): + super().__init__() + self.bn = keras.layers.BatchNormalization( + beta_initializer=keras.initializers.Constant(w.bias.numpy()), + gamma_initializer=keras.initializers.Constant(w.weight.numpy()), + moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()), + moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()), + epsilon=w.eps) + + def call(self, inputs): + return self.bn(inputs) + + +class TFPad(keras.layers.Layer): + # Pad inputs in spatial dimensions 1 and 2 + def __init__(self, pad): + super().__init__() + if isinstance(pad, int): + self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]]) + else: # tuple/list + self.pad = tf.constant([[0, 0], [pad[0], pad[0]], [pad[1], pad[1]], [0, 0]]) + + def call(self, inputs): + return tf.pad(inputs, self.pad, mode='constant', constant_values=0) + + +class TFConv(keras.layers.Layer): + # Standard convolution + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None): + # ch_in, ch_out, weights, kernel, stride, padding, groups + super().__init__() + assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument" + # TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding) + # see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch + conv = keras.layers.Conv2D( + filters=c2, + kernel_size=k, + strides=s, + padding='SAME' if s == 1 else 'VALID', + use_bias=not hasattr(w, 'bn'), + kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()), + bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy())) + self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv]) + self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity + self.act = activations(w.act) if act else tf.identity + + def call(self, inputs): + return self.act(self.bn(self.conv(inputs))) + + +class TFDWConv(keras.layers.Layer): + # Depthwise convolution + def __init__(self, c1, c2, k=1, s=1, p=None, act=True, w=None): + # ch_in, ch_out, weights, kernel, stride, padding, groups + super().__init__() + assert c2 % c1 == 0, f'TFDWConv() output={c2} must be a multiple of input={c1} channels' + conv = keras.layers.DepthwiseConv2D( + kernel_size=k, + depth_multiplier=c2 // c1, + strides=s, + padding='SAME' if s == 1 else 'VALID', + use_bias=not hasattr(w, 'bn'), + depthwise_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()), + bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy())) + self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv]) + self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity + self.act = activations(w.act) if act else tf.identity + + def call(self, inputs): + return self.act(self.bn(self.conv(inputs))) + + +class TFDWConvTranspose2d(keras.layers.Layer): + # Depthwise ConvTranspose2d + def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0, w=None): + # ch_in, ch_out, weights, kernel, stride, padding, groups + super().__init__() + assert c1 == c2, f'TFDWConv() output={c2} must be equal to input={c1} channels' + assert k == 4 and p1 == 1, 'TFDWConv() only valid for k=4 and p1=1' + weight, bias = w.weight.permute(2, 3, 1, 0).numpy(), w.bias.numpy() + self.c1 = c1 + self.conv = [ + keras.layers.Conv2DTranspose(filters=1, + kernel_size=k, + strides=s, + padding='VALID', + output_padding=p2, + use_bias=True, + kernel_initializer=keras.initializers.Constant(weight[..., i:i + 1]), + bias_initializer=keras.initializers.Constant(bias[i])) for i in range(c1)] + + def call(self, inputs): + return tf.concat([m(x) for m, x in zip(self.conv, tf.split(inputs, self.c1, 3))], 3)[:, 1:-1, 1:-1] + + +class TFFocus(keras.layers.Layer): + # Focus wh information into c-space + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None): + # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv) + + def call(self, inputs): # x(b,w,h,c) -> y(b,w/2,h/2,4c) + # inputs = inputs / 255 # normalize 0-255 to 0-1 + inputs = [inputs[:, ::2, ::2, :], inputs[:, 1::2, ::2, :], inputs[:, ::2, 1::2, :], inputs[:, 1::2, 1::2, :]] + return self.conv(tf.concat(inputs, 3)) + + +class TFBottleneck(keras.layers.Layer): + # Standard bottleneck + def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None): # ch_in, ch_out, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2) + self.add = shortcut and c1 == c2 + + def call(self, inputs): + return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs)) + + +class TFCrossConv(keras.layers.Layer): + # Cross Convolution + def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False, w=None): + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, (1, k), (1, s), w=w.cv1) + self.cv2 = TFConv(c_, c2, (k, 1), (s, 1), g=g, w=w.cv2) + self.add = shortcut and c1 == c2 + + def call(self, inputs): + return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs)) + + +class TFConv2d(keras.layers.Layer): + # Substitution for PyTorch nn.Conv2D + def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None): + super().__init__() + assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument" + self.conv = keras.layers.Conv2D(filters=c2, + kernel_size=k, + strides=s, + padding='VALID', + use_bias=bias, + kernel_initializer=keras.initializers.Constant( + w.weight.permute(2, 3, 1, 0).numpy()), + bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None) + + def call(self, inputs): + return self.conv(inputs) + + +class TFBottleneckCSP(keras.layers.Layer): + # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None): + # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2) + self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3) + self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4) + self.bn = TFBN(w.bn) + self.act = lambda x: keras.activations.swish(x) + self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)]) + + def call(self, inputs): + y1 = self.cv3(self.m(self.cv1(inputs))) + y2 = self.cv2(inputs) + return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3)))) + + +class TFC3(keras.layers.Layer): + # CSP Bottleneck with 3 convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None): + # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2) + self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3) + self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)]) + + def call(self, inputs): + return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3)) + + +class TFC3x(keras.layers.Layer): + # 3 module with cross-convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None): + # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2) + self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3) + self.m = keras.Sequential([ + TFCrossConv(c_, c_, k=3, s=1, g=g, e=1.0, shortcut=shortcut, w=w.m[j]) for j in range(n)]) + + def call(self, inputs): + return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3)) + + +class TFSPP(keras.layers.Layer): + # Spatial pyramid pooling layer used in YOLOv3-SPP + def __init__(self, c1, c2, k=(5, 9, 13), w=None): + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2) + self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding='SAME') for x in k] + + def call(self, inputs): + x = self.cv1(inputs) + return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3)) + + +class TFSPPF(keras.layers.Layer): + # Spatial pyramid pooling-Fast layer + def __init__(self, c1, c2, k=5, w=None): + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2) + self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding='SAME') + + def call(self, inputs): + x = self.cv1(inputs) + y1 = self.m(x) + y2 = self.m(y1) + return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3)) + + +class TFDetect(keras.layers.Layer): + # TF YOLOv5 Detect layer + def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None): # detection layer + super().__init__() + self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32) + self.nc = nc # number of classes + self.no = nc + 5 # number of outputs per anchor + self.nl = len(anchors) # number of detection layers + self.na = len(anchors[0]) // 2 # number of anchors + self.grid = [tf.zeros(1)] * self.nl # init grid + self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32) + self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]), [self.nl, 1, -1, 1, 2]) + self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)] + self.training = False # set to False after building model + self.imgsz = imgsz + for i in range(self.nl): + ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i] + self.grid[i] = self._make_grid(nx, ny) + + def call(self, inputs): + z = [] # inference output + x = [] + for i in range(self.nl): + x.append(self.m[i](inputs[i])) + # x(bs,20,20,255) to x(bs,3,20,20,85) + ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i] + x[i] = tf.reshape(x[i], [-1, ny * nx, self.na, self.no]) + + if not self.training: # inference + y = tf.sigmoid(x[i]) + grid = tf.transpose(self.grid[i], [0, 2, 1, 3]) - 0.5 + anchor_grid = tf.transpose(self.anchor_grid[i], [0, 2, 1, 3]) * 4 + xy = (y[..., 0:2] * 2 + grid) * self.stride[i] # xy + wh = y[..., 2:4] ** 2 * anchor_grid + # Normalize xywh to 0-1 to reduce calibration error + xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32) + wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32) + y = tf.concat([xy, wh, y[..., 4:]], -1) + z.append(tf.reshape(y, [-1, self.na * ny * nx, self.no])) + + return tf.transpose(x, [0, 2, 1, 3]) if self.training else (tf.concat(z, 1), x) + + @staticmethod + def _make_grid(nx=20, ny=20): + # yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) + # return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() + xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny)) + return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32) + + +class TFUpsample(keras.layers.Layer): + # TF version of torch.nn.Upsample() + def __init__(self, size, scale_factor, mode, w=None): # warning: all arguments needed including 'w' + super().__init__() + assert scale_factor == 2, "scale_factor must be 2" + self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * 2, x.shape[2] * 2), method=mode) + # self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode) + # with default arguments: align_corners=False, half_pixel_centers=False + # self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x, + # size=(x.shape[1] * 2, x.shape[2] * 2)) + + def call(self, inputs): + return self.upsample(inputs) + + +class TFConcat(keras.layers.Layer): + # TF version of torch.concat() + def __init__(self, dimension=1, w=None): + super().__init__() + assert dimension == 1, "convert only NCHW to NHWC concat" + self.d = 3 + + def call(self, inputs): + return tf.concat(inputs, self.d) + + +def parse_model(d, ch, model, imgsz): # model_dict, input_channels(3) + LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") + anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] + na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors + no = na * (nc + 5) # number of outputs = anchors * (classes + 5) + + layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out + for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args + m_str = m + m = eval(m) if isinstance(m, str) else m # eval strings + for j, a in enumerate(args): + try: + args[j] = eval(a) if isinstance(a, str) else a # eval strings + except NameError: + pass + + n = max(round(n * gd), 1) if n > 1 else n # depth gain + if m in [ + nn.Conv2d, Conv, DWConv, DWConvTranspose2d, Bottleneck, SPP, SPPF, MixConv2d, Focus, CrossConv, + BottleneckCSP, C3, C3x]: + c1, c2 = ch[f], args[0] + c2 = make_divisible(c2 * gw, 8) if c2 != no else c2 + + args = [c1, c2, *args[1:]] + if m in [BottleneckCSP, C3, C3x]: + args.insert(2, n) + n = 1 + elif m is nn.BatchNorm2d: + args = [ch[f]] + elif m is Concat: + c2 = sum(ch[-1 if x == -1 else x + 1] for x in f) + elif m is Detect: + args.append([ch[x + 1] for x in f]) + if isinstance(args[1], int): # number of anchors + args[1] = [list(range(args[1] * 2))] * len(f) + args.append(imgsz) + else: + c2 = ch[f] + + tf_m = eval('TF' + m_str.replace('nn.', '')) + m_ = keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)]) if n > 1 \ + else tf_m(*args, w=model.model[i]) # module + + torch_m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module + t = str(m)[8:-2].replace('__main__.', '') # module type + np = sum(x.numel() for x in torch_m_.parameters()) # number params + m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params + LOGGER.info(f'{i:>3}{str(f):>18}{str(n):>3}{np:>10} {t:<40}{str(args):<30}') # print + save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist + layers.append(m_) + ch.append(c2) + return keras.Sequential(layers), sorted(save) + + +class TFModel: + # TF YOLOv5 model + def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, model=None, imgsz=(640, 640)): # model, channels, classes + super().__init__() + if isinstance(cfg, dict): + self.yaml = cfg # model dict + else: # is *.yaml + import yaml # for torch hub + self.yaml_file = Path(cfg).name + with open(cfg) as f: + self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict + + # Define model + if nc and nc != self.yaml['nc']: + LOGGER.info(f"Overriding {cfg} nc={self.yaml['nc']} with nc={nc}") + self.yaml['nc'] = nc # override yaml value + self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz) + + def predict(self, + inputs, + tf_nms=False, + agnostic_nms=False, + topk_per_class=100, + topk_all=100, + iou_thres=0.45, + conf_thres=0.25): + y = [] # outputs + x = inputs + for m in self.model.layers: + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + + x = m(x) # run + y.append(x if m.i in self.savelist else None) # save output + + # Add TensorFlow NMS + if tf_nms: + boxes = self._xywh2xyxy(x[0][..., :4]) + probs = x[0][:, :, 4:5] + classes = x[0][:, :, 5:] + scores = probs * classes + if agnostic_nms: + nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres) + else: + boxes = tf.expand_dims(boxes, 2) + nms = tf.image.combined_non_max_suppression(boxes, + scores, + topk_per_class, + topk_all, + iou_thres, + conf_thres, + clip_boxes=False) + return nms, x[1] + return x[0] # output only first tensor [1,6300,85] = [xywh, conf, class0, class1, ...] + # x = x[0][0] # [x(1,6300,85), ...] to x(6300,85) + # xywh = x[..., :4] # x(6300,4) boxes + # conf = x[..., 4:5] # x(6300,1) confidences + # cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes + # return tf.concat([conf, cls, xywh], 1) + + @staticmethod + def _xywh2xyxy(xywh): + # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1) + return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1) + + +class AgnosticNMS(keras.layers.Layer): + # TF Agnostic NMS + def call(self, input, topk_all, iou_thres, conf_thres): + # wrap map_fn to avoid TypeSpec related error https://stackoverflow.com/a/65809989/3036450 + return tf.map_fn(lambda x: self._nms(x, topk_all, iou_thres, conf_thres), + input, + fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32), + name='agnostic_nms') + + @staticmethod + def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnostic NMS + boxes, classes, scores = x + class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32) + scores_inp = tf.reduce_max(scores, -1) + selected_inds = tf.image.non_max_suppression(boxes, + scores_inp, + max_output_size=topk_all, + iou_threshold=iou_thres, + score_threshold=conf_thres) + selected_boxes = tf.gather(boxes, selected_inds) + padded_boxes = tf.pad(selected_boxes, + paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]], + mode="CONSTANT", + constant_values=0.0) + selected_scores = tf.gather(scores_inp, selected_inds) + padded_scores = tf.pad(selected_scores, + paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]], + mode="CONSTANT", + constant_values=-1.0) + selected_classes = tf.gather(class_inds, selected_inds) + padded_classes = tf.pad(selected_classes, + paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]], + mode="CONSTANT", + constant_values=-1.0) + valid_detections = tf.shape(selected_inds)[0] + return padded_boxes, padded_scores, padded_classes, valid_detections + + +def activations(act=nn.SiLU): + # Returns TF activation from input PyTorch activation + if isinstance(act, nn.LeakyReLU): + return lambda x: keras.activations.relu(x, alpha=0.1) + elif isinstance(act, nn.Hardswish): + return lambda x: x * tf.nn.relu6(x + 3) * 0.166666667 + elif isinstance(act, (nn.SiLU, SiLU)): + return lambda x: keras.activations.swish(x) + else: + raise Exception(f'no matching TensorFlow activation found for PyTorch activation {act}') + + +def representative_dataset_gen(dataset, ncalib=100): + # Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays + for n, (path, img, im0s, vid_cap, string) in enumerate(dataset): + im = np.transpose(img, [1, 2, 0]) + im = np.expand_dims(im, axis=0).astype(np.float32) + im /= 255 + yield [im] + if n >= ncalib: + break + + +def run( + weights=ROOT / 'yolov5s.pt', # weights path + imgsz=(640, 640), # inference size h,w + batch_size=1, # batch size + dynamic=False, # dynamic batch size +): + # PyTorch model + im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image + model = attempt_load(weights, device=torch.device('cpu'), inplace=True, fuse=False) + _ = model(im) # inference + model.info() + + # TensorFlow model + im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image + tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz) + _ = tf_model.predict(im) # inference + + # Keras model + im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size) + keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im)) + keras_model.summary() + + LOGGER.info('PyTorch, TensorFlow and Keras models successfully verified.\nUse export.py for TF model export.') + + +def parse_opt(): + parser = argparse.ArgumentParser() + parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path') + parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w') + parser.add_argument('--batch-size', type=int, default=1, help='batch size') + parser.add_argument('--dynamic', action='store_true', help='dynamic batch size') + opt = parser.parse_args() + opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand + print_args(vars(opt)) + return opt + + +def main(opt): + run(**vars(opt)) + + +if __name__ == "__main__": + opt = parse_opt() + main(opt) diff --git a/Y5/models/yolo.py b/Y5/models/yolo.py index 8117cb4..02660e6 100755 --- a/Y5/models/yolo.py +++ b/Y5/models/yolo.py @@ -1,203 +1,256 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +YOLO-specific modules + +Usage: + $ python path/to/models/yolo.py --cfg yolov5s.yaml +""" + import argparse -import logging +import os +import platform import sys from copy import deepcopy +from pathlib import Path -sys.path.append('./') # to run '$ python *.py' files in subdirectories -logger = logging.getLogger(__name__) +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +if platform.system() != 'Windows': + ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative -from Y5.models.common import * -from Y5.models.experimental import * -from Y5.utils.autoanchor import check_anchor_order -from Y5.utils.general import make_divisible, check_file, set_logging -from Y5.utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \ - select_device, copy_attr +from models.common import * +from models.experimental import * +from utils.autoanchor import check_anchor_order +from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args +from utils.plots import feature_visualization +from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device, + time_sync) try: - import thop # for FLOPS computation + import thop # for FLOPs computation except ImportError: thop = None class Detect(nn.Module): stride = None # strides computed during build - export = False # onnx export + onnx_dynamic = False # ONNX export parameter + export = False # export mode - def __init__(self, nc=80, anchors=(), ch=()): # detection layer - super(Detect, self).__init__() + def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer + super().__init__() self.nc = nc # number of classes self.no = nc + 5 # number of outputs per anchor self.nl = len(anchors) # number of detection layers self.na = len(anchors[0]) // 2 # number of anchors self.grid = [torch.zeros(1)] * self.nl # init grid - a = torch.tensor(anchors).float().view(self.nl, -1, 2) - self.register_buffer('anchors', a) # shape(nl,na,2) - self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) + self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid + self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2) self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv + self.inplace = inplace # use in-place ops (e.g. slice assignment) def forward(self, x): - # x = x.copy() # for profiling z = [] # inference output - self.training |= self.export for i in range(self.nl): x[i] = self.m[i](x[i]) # conv bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() if not self.training: # inference - if self.grid[i].shape[2:4] != x[i].shape[2:4]: - self.grid[i] = self._make_grid(nx, ny).to(x[i].device) + if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]: + self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i) y = x[i].sigmoid() - y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy - y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh + if self.inplace: + y[..., 0:2] = (y[..., 0:2] * 2 + self.grid[i]) * self.stride[i] # xy + y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh + else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953 + xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0 + xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy + wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh + y = torch.cat((xy, wh, conf), 4) z.append(y.view(bs, -1, self.no)) - return x if self.training else (torch.cat(z, 1), x) + return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x) - @staticmethod - def _make_grid(nx=20, ny=20): - yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) - return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() + def _make_grid(self, nx=20, ny=20, i=0): + d = self.anchors[i].device + t = self.anchors[i].dtype + shape = 1, self.na, ny, nx, 2 # grid shape + y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t) + if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility + yv, xv = torch.meshgrid(y, x, indexing='ij') + else: + yv, xv = torch.meshgrid(y, x) + grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5 + anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape) + return grid, anchor_grid class Model(nn.Module): + # YOLOv5 model def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes - super(Model, self).__init__() + super().__init__() if isinstance(cfg, dict): self.yaml = cfg # model dict else: # is *.yaml import yaml # for torch hub self.yaml_file = Path(cfg).name - with open(cfg) as f: - self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict + with open(cfg, encoding='ascii', errors='ignore') as f: + self.yaml = yaml.safe_load(f) # model dict # Define model ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels if nc and nc != self.yaml['nc']: - logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") + LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") self.yaml['nc'] = nc # override yaml value if anchors: - logger.info(f'Overriding model.yaml anchors with anchors={anchors}') + LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}') self.yaml['anchors'] = round(anchors) # override yaml value self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist self.names = [str(i) for i in range(self.yaml['nc'])] # default names - # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))]) + self.inplace = self.yaml.get('inplace', True) # Build strides, anchors m = self.model[-1] # Detect() if isinstance(m, Detect): s = 256 # 2x min stride + m.inplace = self.inplace m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward + check_anchor_order(m) # must be in pixel-space (not grid-space) m.anchors /= m.stride.view(-1, 1, 1) - check_anchor_order(m) self.stride = m.stride self._initialize_biases() # only run once - # print('Strides: %s' % m.stride.tolist()) # Init weights, biases initialize_weights(self) self.info() - logger.info('') + LOGGER.info('') - def forward(self, x, augment=False, profile=False): + def forward(self, x, augment=False, profile=False, visualize=False): if augment: - img_size = x.shape[-2:] # height, width - s = [1, 0.83, 0.67] # scales - f = [None, 3, None] # flips (2-ud, 3-lr) - y = [] # outputs - for si, fi in zip(s, f): - xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) - yi = self.forward_once(xi)[0] # forward - # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save - yi[..., :4] /= si # de-scale - if fi == 2: - yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud - elif fi == 3: - yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr - y.append(yi) - return torch.cat(y, 1), None # augmented inference, train - else: - return self.forward_once(x, profile) # single-scale inference, train + return self._forward_augment(x) # augmented inference, None + return self._forward_once(x, profile, visualize) # single-scale inference, train - def forward_once(self, x, profile=False): + def _forward_augment(self, x): + img_size = x.shape[-2:] # height, width + s = [1, 0.83, 0.67] # scales + f = [None, 3, None] # flips (2-ud, 3-lr) + y = [] # outputs + for si, fi in zip(s, f): + xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) + yi = self._forward_once(xi)[0] # forward + # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save + yi = self._descale_pred(yi, fi, si, img_size) + y.append(yi) + y = self._clip_augmented(y) # clip augmented tails + return torch.cat(y, 1), None # augmented inference, train + + def _forward_once(self, x, profile=False, visualize=False): y, dt = [], [] # outputs for m in self.model: if m.f != -1: # if not from previous layer x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers - if profile: - o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS - t = time_synchronized() - for _ in range(10): - _ = m(x) - dt.append((time_synchronized() - t) * 100) - print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type)) - + self._profile_one_layer(m, x, dt) x = m(x) # run y.append(x if m.i in self.save else None) # save output - - if profile: - print('%.1fms total' % sum(dt)) + if visualize: + feature_visualization(x, m.type, m.i, save_dir=visualize) return x + def _descale_pred(self, p, flips, scale, img_size): + # de-scale predictions following augmented inference (inverse operation) + if self.inplace: + p[..., :4] /= scale # de-scale + if flips == 2: + p[..., 1] = img_size[0] - p[..., 1] # de-flip ud + elif flips == 3: + p[..., 0] = img_size[1] - p[..., 0] # de-flip lr + else: + x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale + if flips == 2: + y = img_size[0] - y # de-flip ud + elif flips == 3: + x = img_size[1] - x # de-flip lr + p = torch.cat((x, y, wh, p[..., 4:]), -1) + return p + + def _clip_augmented(self, y): + # Clip YOLOv5 augmented inference tails + nl = self.model[-1].nl # number of detection layers (P3-P5) + g = sum(4 ** x for x in range(nl)) # grid points + e = 1 # exclude layer count + i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices + y[0] = y[0][:, :-i] # large + i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices + y[-1] = y[-1][:, i:] # small + return y + + def _profile_one_layer(self, m, x, dt): + c = isinstance(m, Detect) # is final layer, copy input as inplace fix + o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs + t = time_sync() + for _ in range(10): + m(x.copy() if c else x) + dt.append((time_sync() - t) * 100) + if m == self.model[0]: + LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module") + LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}') + if c: + LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total") + def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency # https://arxiv.org/abs/1708.02002 section 3.3 # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. m = self.model[-1] # Detect() module for mi, s in zip(m.m, m.stride): # from - b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) - b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) - b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls + b = mi.bias.view(m.na, -1).detach() # conv.bias(255) to (3,85) + b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) + b[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) def _print_biases(self): m = self.model[-1] # Detect() module for mi in m.m: # from b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) - print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())) + LOGGER.info( + ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())) # def _print_weights(self): # for m in self.model.modules(): # if type(m) is Bottleneck: - # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights + # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers - #print('Fusing layers... ') + LOGGER.info('Fusing layers... ') for m in self.model.modules(): - if type(m) is Conv and hasattr(m, 'bn'): + if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'): m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv delattr(m, 'bn') # remove batchnorm - m.forward = m.fuseforward # update forward + m.forward = m.forward_fuse # update forward self.info() return self - def nms(self, mode=True): # add or remove NMS module - present = type(self.model[-1]) is NMS # last layer is NMS - if mode and not present: - print('Adding NMS... ') - m = NMS() # module - m.f = -1 # from - m.i = self.model[-1].i + 1 # index - self.model.add_module(name='%s' % m.i, module=m) # add - self.eval() - elif not mode and present: - print('Removing NMS... ') - self.model = self.model[:-1] # remove - return self - - def autoshape(self): # add autoShape module - print('Adding autoShape... ') - m = autoShape(self) # wrap model - copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes - return m - def info(self, verbose=False, img_size=640): # print model information model_info(self, verbose, img_size) + def _apply(self, fn): + # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers + self = super()._apply(fn) + m = self.model[-1] # Detect() + if isinstance(m, Detect): + m.stride = fn(m.stride) + m.grid = list(map(fn, m.grid)) + if isinstance(m.anchor_grid, list): + m.anchor_grid = list(map(fn, m.anchor_grid)) + return self + def parse_model(d, ch): # model_dict, input_channels(3) - logger.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments')) + LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors no = na * (nc + 5) # number of outputs = anchors * (classes + 5) @@ -208,24 +261,24 @@ def parse_model(d, ch): # model_dict, input_channels(3) for j, a in enumerate(args): try: args[j] = eval(a) if isinstance(a, str) else a # eval strings - except: + except NameError: pass - n = max(round(n * gd), 1) if n > 1 else n # depth gain - if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, - C3]: + n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain + if m in (Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, + BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x): c1, c2 = ch[f], args[0] if c2 != no: # if not output c2 = make_divisible(c2 * gw, 8) args = [c1, c2, *args[1:]] - if m in [BottleneckCSP, C3]: + if m in [BottleneckCSP, C3, C3TR, C3Ghost, C3x]: args.insert(2, n) # number of repeats n = 1 elif m is nn.BatchNorm2d: args = [ch[f]] elif m is Concat: - c2 = sum([ch[x] for x in f]) + c2 = sum(ch[x] for x in f) elif m is Detect: args.append([ch[x] for x in f]) if isinstance(args[1], int): # number of anchors @@ -237,11 +290,11 @@ def parse_model(d, ch): # model_dict, input_channels(3) else: c2 = ch[f] - m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module + m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module t = str(m)[8:-2].replace('__main__.', '') # module type - np = sum([x.numel() for x in m_.parameters()]) # number params + np = sum(x.numel() for x in m_.parameters()) # number params m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params - logger.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print + LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist layers.append(m_) if i == 0: @@ -253,23 +306,33 @@ def parse_model(d, ch): # model_dict, input_channels(3) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') + parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs') parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--profile', action='store_true', help='profile model speed') + parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer') + parser.add_argument('--test', action='store_true', help='test all yolo*.yaml') opt = parser.parse_args() - opt.cfg = check_file(opt.cfg) # check file - set_logging() + opt.cfg = check_yaml(opt.cfg) # check YAML + print_args(vars(opt)) device = select_device(opt.device) # Create model + im = torch.rand(opt.batch_size, 3, 640, 640).to(device) model = Model(opt.cfg).to(device) - model.train() - # Profile - # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device) - # y = model(img, profile=True) + # Options + if opt.line_profile: # profile layer by layer + _ = model(im, profile=True) - # Tensorboard - # from torch.utils.tensorboard import SummaryWriter - # tb_writer = SummaryWriter() - # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/") - # tb_writer.add_graph(model.model, img) # add model to tensorboard - # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard + elif opt.profile: # profile forward-backward + results = profile(input=im, ops=[model], n=3) + + elif opt.test: # test all models + for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'): + try: + _ = Model(cfg) + except Exception as e: + print(f'Error in {cfg}: {e}') + + else: # report fused model summary + model.fuse() diff --git a/Y5/models/yolov5l.yaml b/Y5/models/yolov5l.yaml index 71ebf86..ce8a5de 100755 --- a/Y5/models/yolov5l.yaml +++ b/Y5/models/yolov5l.yaml @@ -1,30 +1,30 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.0 # model depth multiple width_multiple: 1.0 # layer channel multiple - -# anchors anchors: - [10,13, 16,30, 33,23] # P3/8 - [30,61, 62,45, 59,119] # P4/16 - [116,90, 156,198, 373,326] # P5/32 -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 [-1, 3, C3, [128]], [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 - [-1, 9, C3, [256]], + [-1, 6, C3, [256]], [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 [-1, 9, C3, [512]], [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 - [-1, 1, SPP, [1024, [5, 9, 13]]], - [-1, 3, C3, [1024, False]], # 9 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 ] -# YOLOv5 head +# YOLOv5 v6.0 head head: [[-1, 1, Conv, [512, 1, 1]], [-1, 1, nn.Upsample, [None, 2, 'nearest']], diff --git a/Y5/models/yolov5m.yaml b/Y5/models/yolov5m.yaml index 3c749c9..ad13ab3 100755 --- a/Y5/models/yolov5m.yaml +++ b/Y5/models/yolov5m.yaml @@ -1,30 +1,30 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 0.67 # model depth multiple width_multiple: 0.75 # layer channel multiple - -# anchors anchors: - [10,13, 16,30, 33,23] # P3/8 - [30,61, 62,45, 59,119] # P4/16 - [116,90, 156,198, 373,326] # P5/32 -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 [-1, 3, C3, [128]], [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 - [-1, 9, C3, [256]], + [-1, 6, C3, [256]], [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 [-1, 9, C3, [512]], [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 - [-1, 1, SPP, [1024, [5, 9, 13]]], - [-1, 3, C3, [1024, False]], # 9 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 ] -# YOLOv5 head +# YOLOv5 v6.0 head head: [[-1, 1, Conv, [512, 1, 1]], [-1, 1, nn.Upsample, [None, 2, 'nearest']], diff --git a/Y5/models/yolov5n.yaml b/Y5/models/yolov5n.yaml new file mode 100755 index 0000000..8a28a40 --- /dev/null +++ b/Y5/models/yolov5n.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.25 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5/models/yolov5s.yaml b/Y5/models/yolov5s.yaml index aca669d..f35beab 100755 --- a/Y5/models/yolov5s.yaml +++ b/Y5/models/yolov5s.yaml @@ -1,30 +1,30 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 0.33 # model depth multiple width_multiple: 0.50 # layer channel multiple - -# anchors anchors: - [10,13, 16,30, 33,23] # P3/8 - [30,61, 62,45, 59,119] # P4/16 - [116,90, 156,198, 373,326] # P5/32 -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 [-1, 3, C3, [128]], [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 - [-1, 9, C3, [256]], + [-1, 6, C3, [256]], [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 [-1, 9, C3, [512]], [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 - [-1, 1, SPP, [1024, [5, 9, 13]]], - [-1, 3, C3, [1024, False]], # 9 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 ] -# YOLOv5 head +# YOLOv5 v6.0 head head: [[-1, 1, Conv, [512, 1, 1]], [-1, 1, nn.Upsample, [None, 2, 'nearest']], diff --git a/Y5/models/yolov5x.yaml b/Y5/models/yolov5x.yaml index d3babdf..f617a02 100755 --- a/Y5/models/yolov5x.yaml +++ b/Y5/models/yolov5x.yaml @@ -1,30 +1,30 @@ -# parameters +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters nc: 80 # number of classes depth_multiple: 1.33 # model depth multiple width_multiple: 1.25 # layer channel multiple - -# anchors anchors: - [10,13, 16,30, 33,23] # P3/8 - [30,61, 62,45, 59,119] # P4/16 - [116,90, 156,198, 373,326] # P5/32 -# YOLOv5 backbone +# YOLOv5 v6.0 backbone backbone: # [from, number, module, args] - [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 [-1, 3, C3, [128]], [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 - [-1, 9, C3, [256]], + [-1, 6, C3, [256]], [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 [-1, 9, C3, [512]], [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 - [-1, 1, SPP, [1024, [5, 9, 13]]], - [-1, 3, C3, [1024, False]], # 9 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 ] -# YOLOv5 head +# YOLOv5 v6.0 head head: [[-1, 1, Conv, [512, 1, 1]], [-1, 1, nn.Upsample, [None, 2, 'nearest']], diff --git a/Y5/utils/__init__.py b/Y5/utils/__init__.py index e69de29..da53a4d 100755 --- a/Y5/utils/__init__.py +++ b/Y5/utils/__init__.py @@ -0,0 +1,36 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +utils/initialization +""" + + +def notebook_init(verbose=True): + # Check system software and hardware + print('Checking setup...') + + import os + import shutil + + from utils.general import check_requirements, emojis, is_colab + from utils.torch_utils import select_device # imports + + check_requirements(('psutil', 'IPython')) + import psutil + from IPython import display # to display images and clear console output + + if is_colab(): + shutil.rmtree('/content/sample_data', ignore_errors=True) # remove colab /sample_data directory + + # System info + if verbose: + gb = 1 << 30 # bytes to GiB (1024 ** 3) + ram = psutil.virtual_memory().total + total, used, free = shutil.disk_usage("/") + display.clear_output() + s = f'({os.cpu_count()} CPUs, {ram / gb:.1f} GB RAM, {(total - free) / gb:.1f}/{total / gb:.1f} GB disk)' + else: + s = '' + + select_device(newline=False) + print(emojis(f'Setup complete ✅ {s}')) + return display diff --git a/Y5/utils/__pycache__/__init__.cpython-36.pyc b/Y5/utils/__pycache__/__init__.cpython-36.pyc old mode 100644 new mode 100755 index 5a9571d..0d86262 Binary files a/Y5/utils/__pycache__/__init__.cpython-36.pyc and b/Y5/utils/__pycache__/__init__.cpython-36.pyc differ diff --git a/Y5/utils/__pycache__/__init__.cpython-37.pyc b/Y5/utils/__pycache__/__init__.cpython-37.pyc new file mode 100755 index 0000000..aeff774 Binary files /dev/null and b/Y5/utils/__pycache__/__init__.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/__init__.cpython-38.pyc b/Y5/utils/__pycache__/__init__.cpython-38.pyc new file mode 100755 index 0000000..e91bfde Binary files /dev/null and b/Y5/utils/__pycache__/__init__.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/__init__.cpython-39.pyc b/Y5/utils/__pycache__/__init__.cpython-39.pyc new file mode 100755 index 0000000..48a6742 Binary files /dev/null and b/Y5/utils/__pycache__/__init__.cpython-39.pyc differ diff --git a/Y5/utils/__pycache__/augmentations.cpython-36.pyc b/Y5/utils/__pycache__/augmentations.cpython-36.pyc new file mode 100755 index 0000000..3cec5b7 Binary files /dev/null and b/Y5/utils/__pycache__/augmentations.cpython-36.pyc differ diff --git a/Y5/utils/__pycache__/augmentations.cpython-37.pyc b/Y5/utils/__pycache__/augmentations.cpython-37.pyc new file mode 100755 index 0000000..e87d947 Binary files /dev/null and b/Y5/utils/__pycache__/augmentations.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/augmentations.cpython-38.pyc b/Y5/utils/__pycache__/augmentations.cpython-38.pyc new file mode 100755 index 0000000..e5f0368 Binary files /dev/null and b/Y5/utils/__pycache__/augmentations.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/augmentations.cpython-39.pyc b/Y5/utils/__pycache__/augmentations.cpython-39.pyc new file mode 100755 index 0000000..aa08aee Binary files /dev/null and b/Y5/utils/__pycache__/augmentations.cpython-39.pyc differ diff --git a/Y5/utils/__pycache__/autoanchor.cpython-36.pyc b/Y5/utils/__pycache__/autoanchor.cpython-36.pyc old mode 100644 new mode 100755 index e8a9105..222936f Binary files a/Y5/utils/__pycache__/autoanchor.cpython-36.pyc and b/Y5/utils/__pycache__/autoanchor.cpython-36.pyc differ diff --git a/Y5/utils/__pycache__/autoanchor.cpython-37.pyc b/Y5/utils/__pycache__/autoanchor.cpython-37.pyc new file mode 100755 index 0000000..51299a4 Binary files /dev/null and b/Y5/utils/__pycache__/autoanchor.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/autoanchor.cpython-38.pyc b/Y5/utils/__pycache__/autoanchor.cpython-38.pyc new file mode 100755 index 0000000..e5d96db Binary files /dev/null and b/Y5/utils/__pycache__/autoanchor.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/autoanchor.cpython-39.pyc b/Y5/utils/__pycache__/autoanchor.cpython-39.pyc new file mode 100755 index 0000000..f9ae821 Binary files /dev/null and b/Y5/utils/__pycache__/autoanchor.cpython-39.pyc differ diff --git a/Y5/utils/__pycache__/autobatch.cpython-37.pyc b/Y5/utils/__pycache__/autobatch.cpython-37.pyc new file mode 100755 index 0000000..01ee9d8 Binary files /dev/null and b/Y5/utils/__pycache__/autobatch.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/autobatch.cpython-38.pyc b/Y5/utils/__pycache__/autobatch.cpython-38.pyc new file mode 100755 index 0000000..0526e5e Binary files /dev/null and b/Y5/utils/__pycache__/autobatch.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/callbacks.cpython-37.pyc b/Y5/utils/__pycache__/callbacks.cpython-37.pyc new file mode 100755 index 0000000..ac75e6b Binary files /dev/null and b/Y5/utils/__pycache__/callbacks.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/callbacks.cpython-38.pyc b/Y5/utils/__pycache__/callbacks.cpython-38.pyc new file mode 100755 index 0000000..e2e8de1 Binary files /dev/null and b/Y5/utils/__pycache__/callbacks.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/dataloaders.cpython-36.pyc b/Y5/utils/__pycache__/dataloaders.cpython-36.pyc new file mode 100755 index 0000000..3c1e468 Binary files /dev/null and b/Y5/utils/__pycache__/dataloaders.cpython-36.pyc differ diff --git a/Y5/utils/__pycache__/dataloaders.cpython-37.pyc b/Y5/utils/__pycache__/dataloaders.cpython-37.pyc new file mode 100755 index 0000000..c9953d6 Binary files /dev/null and b/Y5/utils/__pycache__/dataloaders.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/dataloaders.cpython-38.pyc b/Y5/utils/__pycache__/dataloaders.cpython-38.pyc new file mode 100755 index 0000000..1b26c47 Binary files /dev/null and b/Y5/utils/__pycache__/dataloaders.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/dataloaders.cpython-39.pyc b/Y5/utils/__pycache__/dataloaders.cpython-39.pyc new file mode 100755 index 0000000..2d4f1d8 Binary files /dev/null and b/Y5/utils/__pycache__/dataloaders.cpython-39.pyc differ diff --git a/Y5/utils/__pycache__/datasets.cpython-36.pyc b/Y5/utils/__pycache__/datasets.cpython-36.pyc deleted file mode 100644 index 1eb93a7..0000000 Binary files a/Y5/utils/__pycache__/datasets.cpython-36.pyc and /dev/null differ diff --git a/Y5/utils/__pycache__/downloads.cpython-36.pyc b/Y5/utils/__pycache__/downloads.cpython-36.pyc new file mode 100755 index 0000000..1232d29 Binary files /dev/null and b/Y5/utils/__pycache__/downloads.cpython-36.pyc differ diff --git a/Y5/utils/__pycache__/downloads.cpython-37.pyc b/Y5/utils/__pycache__/downloads.cpython-37.pyc new file mode 100755 index 0000000..40d7cee Binary files /dev/null and b/Y5/utils/__pycache__/downloads.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/downloads.cpython-38.pyc b/Y5/utils/__pycache__/downloads.cpython-38.pyc new file mode 100755 index 0000000..6e63e19 Binary files /dev/null and b/Y5/utils/__pycache__/downloads.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/downloads.cpython-39.pyc b/Y5/utils/__pycache__/downloads.cpython-39.pyc new file mode 100755 index 0000000..26b4676 Binary files /dev/null and b/Y5/utils/__pycache__/downloads.cpython-39.pyc differ diff --git a/Y5/utils/__pycache__/general.cpython-36.pyc b/Y5/utils/__pycache__/general.cpython-36.pyc old mode 100644 new mode 100755 index 693156a..85079da Binary files a/Y5/utils/__pycache__/general.cpython-36.pyc and b/Y5/utils/__pycache__/general.cpython-36.pyc differ diff --git a/Y5/utils/__pycache__/general.cpython-37.pyc b/Y5/utils/__pycache__/general.cpython-37.pyc new file mode 100755 index 0000000..02a903c Binary files /dev/null and b/Y5/utils/__pycache__/general.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/general.cpython-38.pyc b/Y5/utils/__pycache__/general.cpython-38.pyc new file mode 100755 index 0000000..809820f Binary files /dev/null and b/Y5/utils/__pycache__/general.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/general.cpython-39.pyc b/Y5/utils/__pycache__/general.cpython-39.pyc new file mode 100755 index 0000000..c3b371e Binary files /dev/null and b/Y5/utils/__pycache__/general.cpython-39.pyc differ diff --git a/Y5/utils/__pycache__/loss.cpython-37.pyc b/Y5/utils/__pycache__/loss.cpython-37.pyc new file mode 100755 index 0000000..6cc1535 Binary files /dev/null and b/Y5/utils/__pycache__/loss.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/loss.cpython-38.pyc b/Y5/utils/__pycache__/loss.cpython-38.pyc new file mode 100755 index 0000000..e08c356 Binary files /dev/null and b/Y5/utils/__pycache__/loss.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/metrics.cpython-36.pyc b/Y5/utils/__pycache__/metrics.cpython-36.pyc old mode 100644 new mode 100755 index 3a34296..c225d6a Binary files a/Y5/utils/__pycache__/metrics.cpython-36.pyc and b/Y5/utils/__pycache__/metrics.cpython-36.pyc differ diff --git a/Y5/utils/__pycache__/metrics.cpython-37.pyc b/Y5/utils/__pycache__/metrics.cpython-37.pyc new file mode 100755 index 0000000..d5c4e2e Binary files /dev/null and b/Y5/utils/__pycache__/metrics.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/metrics.cpython-38.pyc b/Y5/utils/__pycache__/metrics.cpython-38.pyc new file mode 100755 index 0000000..bacf717 Binary files /dev/null and b/Y5/utils/__pycache__/metrics.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/metrics.cpython-39.pyc b/Y5/utils/__pycache__/metrics.cpython-39.pyc new file mode 100755 index 0000000..95cb2c6 Binary files /dev/null and b/Y5/utils/__pycache__/metrics.cpython-39.pyc differ diff --git a/Y5/utils/__pycache__/plots.cpython-36.pyc b/Y5/utils/__pycache__/plots.cpython-36.pyc old mode 100644 new mode 100755 index 648456a..e9dd960 Binary files a/Y5/utils/__pycache__/plots.cpython-36.pyc and b/Y5/utils/__pycache__/plots.cpython-36.pyc differ diff --git a/Y5/utils/__pycache__/plots.cpython-37.pyc b/Y5/utils/__pycache__/plots.cpython-37.pyc new file mode 100755 index 0000000..3b0b332 Binary files /dev/null and b/Y5/utils/__pycache__/plots.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/plots.cpython-38.pyc b/Y5/utils/__pycache__/plots.cpython-38.pyc new file mode 100755 index 0000000..f8e5c64 Binary files /dev/null and b/Y5/utils/__pycache__/plots.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/plots.cpython-39.pyc b/Y5/utils/__pycache__/plots.cpython-39.pyc new file mode 100755 index 0000000..1fdb625 Binary files /dev/null and b/Y5/utils/__pycache__/plots.cpython-39.pyc differ diff --git a/Y5/utils/__pycache__/torch_utils.cpython-36.pyc b/Y5/utils/__pycache__/torch_utils.cpython-36.pyc old mode 100644 new mode 100755 index 1b60489..62bfac4 Binary files a/Y5/utils/__pycache__/torch_utils.cpython-36.pyc and b/Y5/utils/__pycache__/torch_utils.cpython-36.pyc differ diff --git a/Y5/utils/__pycache__/torch_utils.cpython-37.pyc b/Y5/utils/__pycache__/torch_utils.cpython-37.pyc new file mode 100755 index 0000000..923b782 Binary files /dev/null and b/Y5/utils/__pycache__/torch_utils.cpython-37.pyc differ diff --git a/Y5/utils/__pycache__/torch_utils.cpython-38.pyc b/Y5/utils/__pycache__/torch_utils.cpython-38.pyc new file mode 100755 index 0000000..1cda605 Binary files /dev/null and b/Y5/utils/__pycache__/torch_utils.cpython-38.pyc differ diff --git a/Y5/utils/__pycache__/torch_utils.cpython-39.pyc b/Y5/utils/__pycache__/torch_utils.cpython-39.pyc new file mode 100755 index 0000000..aac6dff Binary files /dev/null and b/Y5/utils/__pycache__/torch_utils.cpython-39.pyc differ diff --git a/Y5/utils/activations.py b/Y5/utils/activations.py index aa3ddf0..084ce8c 100755 --- a/Y5/utils/activations.py +++ b/Y5/utils/activations.py @@ -1,50 +1,39 @@ -# Activation functions +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Activation functions +""" import torch import torch.nn as nn import torch.nn.functional as F -# SiLU https://arxiv.org/pdf/1606.08415.pdf ---------------------------------------------------------------------------- -class SiLU(nn.Module): # export-friendly version of nn.SiLU() +class SiLU(nn.Module): + # SiLU activation https://arxiv.org/pdf/1606.08415.pdf @staticmethod def forward(x): return x * torch.sigmoid(x) -class Hardswish(nn.Module): # export-friendly version of nn.Hardswish() +class Hardswish(nn.Module): + # Hard-SiLU activation @staticmethod def forward(x): - # return x * F.hardsigmoid(x) # for torchscript and CoreML - return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX + # return x * F.hardsigmoid(x) # for TorchScript and CoreML + return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0 # for TorchScript, CoreML and ONNX -class MemoryEfficientSwish(nn.Module): - class F(torch.autograd.Function): - @staticmethod - def forward(ctx, x): - ctx.save_for_backward(x) - return x * torch.sigmoid(x) - - @staticmethod - def backward(ctx, grad_output): - x = ctx.saved_tensors[0] - sx = torch.sigmoid(x) - return grad_output * (sx * (1 + x * (1 - sx))) - - def forward(self, x): - return self.F.apply(x) - - -# Mish https://github.com/digantamisra98/Mish -------------------------------------------------------------------------- class Mish(nn.Module): + # Mish activation https://github.com/digantamisra98/Mish @staticmethod def forward(x): return x * F.softplus(x).tanh() class MemoryEfficientMish(nn.Module): + # Mish activation memory-efficient class F(torch.autograd.Function): + @staticmethod def forward(ctx, x): ctx.save_for_backward(x) @@ -61,8 +50,8 @@ class MemoryEfficientMish(nn.Module): return self.F.apply(x) -# FReLU https://arxiv.org/abs/2007.11824 ------------------------------------------------------------------------------- class FReLU(nn.Module): + # FReLU activation https://arxiv.org/abs/2007.11824 def __init__(self, c1, k=3): # ch_in, kernel super().__init__() self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) @@ -70,3 +59,45 @@ class FReLU(nn.Module): def forward(self, x): return torch.max(x, self.bn(self.conv(x))) + + +class AconC(nn.Module): + r""" ACON activation (activate or not) + AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter + according to "Activate or Not: Learning Customized Activation" . + """ + + def __init__(self, c1): + super().__init__() + self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.beta = nn.Parameter(torch.ones(1, c1, 1, 1)) + + def forward(self, x): + dpx = (self.p1 - self.p2) * x + return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x + + +class MetaAconC(nn.Module): + r""" ACON activation (activate or not) + MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network + according to "Activate or Not: Learning Customized Activation" . + """ + + def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r + super().__init__() + c2 = max(r, c1 // r) + self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True) + self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True) + # self.bn1 = nn.BatchNorm2d(c2) + # self.bn2 = nn.BatchNorm2d(c1) + + def forward(self, x): + y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True) + # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891 + # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable + beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed + dpx = (self.p1 - self.p2) * x + return dpx * torch.sigmoid(beta * dpx) + self.p2 * x diff --git a/Y5/utils/augmentations.py b/Y5/utils/augmentations.py new file mode 100755 index 0000000..8a2ee41 --- /dev/null +++ b/Y5/utils/augmentations.py @@ -0,0 +1,284 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Image augmentation functions +""" + +import math +import random + +import cv2 +import numpy as np + +from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box +from utils.metrics import bbox_ioa + + +class Albumentations: + # YOLOv5 Albumentations class (optional, only used if package is installed) + def __init__(self): + self.transform = None + try: + import albumentations as A + check_version(A.__version__, '1.0.3', hard=True) # version requirement + + T = [ + A.Blur(p=0.01), + A.MedianBlur(p=0.01), + A.ToGray(p=0.01), + A.CLAHE(p=0.01), + A.RandomBrightnessContrast(p=0.0), + A.RandomGamma(p=0.0), + A.ImageCompression(quality_lower=75, p=0.0)] # transforms + self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels'])) + + LOGGER.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p)) + except ImportError: # package not installed, skip + pass + except Exception as e: + LOGGER.info(colorstr('albumentations: ') + f'{e}') + + def __call__(self, im, labels, p=1.0): + if self.transform and random.random() < p: + new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed + im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])]) + return im, labels + + +def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5): + # HSV color-space augmentation + if hgain or sgain or vgain: + r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains + hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV)) + dtype = im.dtype # uint8 + + x = np.arange(0, 256, dtype=r.dtype) + lut_hue = ((x * r[0]) % 180).astype(dtype) + lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) + lut_val = np.clip(x * r[2], 0, 255).astype(dtype) + + im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) + cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed + + +def hist_equalize(im, clahe=True, bgr=False): + # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255 + yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV) + if clahe: + c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) + yuv[:, :, 0] = c.apply(yuv[:, :, 0]) + else: + yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram + return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB + + +def replicate(im, labels): + # Replicate labels + h, w = im.shape[:2] + boxes = labels[:, 1:].astype(int) + x1, y1, x2, y2 = boxes.T + s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels) + for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices + x1b, y1b, x2b, y2b = boxes[i] + bh, bw = y2b - y1b, x2b - x1b + yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y + x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh] + im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax] + labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0) + + return im, labels + + +def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32): + # Resize and pad image while meeting stride-multiple constraints + shape = im.shape[:2] # current shape [height, width] + if isinstance(new_shape, int): + new_shape = (new_shape, new_shape) + + # Scale ratio (new / old) + r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) + if not scaleup: # only scale down, do not scale up (for better val mAP) + r = min(r, 1.0) + + # Compute padding + ratio = r, r # width, height ratios + new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) + dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding + # if auto: # minimum rectangle + # dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding + # elif scaleFill: # stretch + # dw, dh = 0.0, 0.0 + # new_unpad = (new_shape[1], new_shape[0]) + # ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios + + dw /= 2 # divide padding into 2 sides + dh /= 2 + + if shape[::-1] != new_unpad: # resize + im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR) + top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) + left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) + im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border + return im, ratio, (dw, dh) + + +def random_perspective(im, + targets=(), + segments=(), + degrees=10, + translate=.1, + scale=.1, + shear=10, + perspective=0.0, + border=(0, 0)): + # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10)) + # targets = [cls, xyxy] + + height = im.shape[0] + border[0] * 2 # shape(h,w,c) + width = im.shape[1] + border[1] * 2 + + # Center + C = np.eye(3) + C[0, 2] = -im.shape[1] / 2 # x translation (pixels) + C[1, 2] = -im.shape[0] / 2 # y translation (pixels) + + # Perspective + P = np.eye(3) + P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y) + P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x) + + # Rotation and Scale + R = np.eye(3) + a = random.uniform(-degrees, degrees) + # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations + s = random.uniform(1 - scale, 1 + scale) + # s = 2 ** random.uniform(-scale, scale) + R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s) + + # Shear + S = np.eye(3) + S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg) + S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg) + + # Translation + T = np.eye(3) + T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels) + T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels) + + # Combined rotation matrix + M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT + if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed + if perspective: + im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114)) + else: # affine + im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114)) + + # Visualize + # import matplotlib.pyplot as plt + # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel() + # ax[0].imshow(im[:, :, ::-1]) # base + # ax[1].imshow(im2[:, :, ::-1]) # warped + + # Transform label coordinates + n = len(targets) + if n: + use_segments = any(x.any() for x in segments) + new = np.zeros((n, 4)) + if use_segments: # warp segments + segments = resample_segments(segments) # upsample + for i, segment in enumerate(segments): + xy = np.ones((len(segment), 3)) + xy[:, :2] = segment + xy = xy @ M.T # transform + xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine + + # clip + new[i] = segment2box(xy, width, height) + + else: # warp boxes + xy = np.ones((n * 4, 3)) + xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1 + xy = xy @ M.T # transform + xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine + + # create new boxes + x = xy[:, [0, 2, 4, 6]] + y = xy[:, [1, 3, 5, 7]] + new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T + + # clip + new[:, [0, 2]] = new[:, [0, 2]].clip(0, width) + new[:, [1, 3]] = new[:, [1, 3]].clip(0, height) + + # filter candidates + i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10) + targets = targets[i] + targets[:, 1:5] = new[i] + + return im, targets + + +def copy_paste(im, labels, segments, p=0.5): + # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy) + n = len(segments) + if p and n: + h, w, c = im.shape # height, width, channels + im_new = np.zeros(im.shape, np.uint8) + for j in random.sample(range(n), k=round(p * n)): + l, s = labels[j], segments[j] + box = w - l[3], l[2], w - l[1], l[4] + ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area + if (ioa < 0.30).all(): # allow 30% obscuration of existing labels + labels = np.concatenate((labels, [[l[0], *box]]), 0) + segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1)) + cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED) + + result = cv2.bitwise_and(src1=im, src2=im_new) + result = cv2.flip(result, 1) # augment segments (flip left-right) + i = result > 0 # pixels to replace + # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch + im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug + + return im, labels, segments + + +def cutout(im, labels, p=0.5): + # Applies image cutout augmentation https://arxiv.org/abs/1708.04552 + if random.random() < p: + h, w = im.shape[:2] + scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction + for s in scales: + mask_h = random.randint(1, int(h * s)) # create random masks + mask_w = random.randint(1, int(w * s)) + + # box + xmin = max(0, random.randint(0, w) - mask_w // 2) + ymin = max(0, random.randint(0, h) - mask_h // 2) + xmax = min(w, xmin + mask_w) + ymax = min(h, ymin + mask_h) + + # apply random color mask + im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)] + + # return unobscured labels + if len(labels) and s > 0.03: + box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32) + ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area + labels = labels[ioa < 0.60] # remove >60% obscured labels + + return labels + + +def mixup(im, labels, im2, labels2): + # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf + r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0 + im = (im * r + im2 * (1 - r)).astype(np.uint8) + labels = np.concatenate((labels, labels2), 0) + return im, labels + + +def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n) + # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio + w1, h1 = box1[2] - box1[0], box1[3] - box1[1] + w2, h2 = box2[2] - box2[0], box2[3] - box2[1] + ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio + return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates diff --git a/Y5/utils/autoanchor.py b/Y5/utils/autoanchor.py index 86a1baf..1a4c521 100755 --- a/Y5/utils/autoanchor.py +++ b/Y5/utils/autoanchor.py @@ -1,29 +1,32 @@ -# Auto-anchor utils +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +AutoAnchor utils +""" + +import random import numpy as np import torch import yaml -from scipy.cluster.vq import kmeans from tqdm import tqdm -from Y5.utils.general import colorstr +from utils.general import LOGGER, colorstr, emojis + +PREFIX = colorstr('AutoAnchor: ') def check_anchor_order(m): # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary - a = m.anchor_grid.prod(-1).view(-1) # anchor area + a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer da = a[-1] - a[0] # delta a ds = m.stride[-1] - m.stride[0] # delta s - if da.sign() != ds.sign(): # same order - print('Reversing anchor order') + if da and (da.sign() != ds.sign()): # same order + LOGGER.info(f'{PREFIX}Reversing anchor order') m.anchors[:] = m.anchors.flip(0) - m.anchor_grid[:] = m.anchor_grid.flip(0) def check_anchors(dataset, model, thr=4.0, imgsz=640): # Check anchor fit to data, recompute if necessary - prefix = colorstr('autoanchor: ') - print(f'\n{prefix}Analyzing anchors... ', end='') m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect() shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True) scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale @@ -31,35 +34,42 @@ def check_anchors(dataset, model, thr=4.0, imgsz=640): def metric(k): # compute metric r = wh[:, None] / k[None] - x = torch.min(r, 1. / r).min(2)[0] # ratio metric + x = torch.min(r, 1 / r).min(2)[0] # ratio metric best = x.max(1)[0] # best_x - aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold - bpr = (best > 1. / thr).float().mean() # best possible recall + aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold + bpr = (best > 1 / thr).float().mean() # best possible recall return bpr, aat - bpr, aat = metric(m.anchor_grid.clone().cpu().view(-1, 2)) - print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='') - if bpr < 0.98: # threshold to recompute - print('. Attempting to improve anchors, please wait...') - na = m.anchor_grid.numel() // 2 # number of anchors - new_anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) - new_bpr = metric(new_anchors.reshape(-1, 2))[0] + stride = m.stride.to(m.anchors.device).view(-1, 1, 1) # model strides + anchors = m.anchors.clone() * stride # current anchors + bpr, aat = metric(anchors.cpu().view(-1, 2)) + s = f'\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). ' + if bpr > 0.98: # threshold to recompute + LOGGER.info(emojis(f'{s}Current anchors are a good fit to dataset ✅')) + else: + LOGGER.info(emojis(f'{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...')) + na = m.anchors.numel() // 2 # number of anchors + try: + anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) + except Exception as e: + LOGGER.info(f'{PREFIX}ERROR: {e}') + new_bpr = metric(anchors)[0] if new_bpr > bpr: # replace anchors - new_anchors = torch.tensor(new_anchors, device=m.anchors.device).type_as(m.anchors) - m.anchor_grid[:] = new_anchors.clone().view_as(m.anchor_grid) # for inference - m.anchors[:] = new_anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss - check_anchor_order(m) - print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.') + anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors) + m.anchors[:] = anchors.clone().view_as(m.anchors) + check_anchor_order(m) # must be in pixel-space (not grid-space) + m.anchors /= stride + s = f'{PREFIX}Done ✅ (optional: update model *.yaml to use these anchors in the future)' else: - print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.') - print('') # newline + s = f'{PREFIX}Done ⚠️ (original anchors better than new anchors, proceeding with original anchors)' + LOGGER.info(emojis(s)) -def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): +def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): """ Creates kmeans-evolved anchors from training dataset Arguments: - path: path to dataset *.yaml, or a loaded dataset + dataset: path to data.yaml, or a loaded dataset n: number of anchors img_size: image size used for training thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0 @@ -72,12 +82,14 @@ def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=10 Usage: from utils.autoanchor import *; _ = kmean_anchors() """ - thr = 1. / thr - prefix = colorstr('autoanchor: ') + from scipy.cluster.vq import kmeans + + npr = np.random + thr = 1 / thr def metric(k, wh): # compute metrics r = wh[:, None] / k[None] - x = torch.min(r, 1. / r).min(2)[0] # ratio metric + x = torch.min(r, 1 / r).min(2)[0] # ratio metric # x = wh_iou(wh, torch.tensor(k)) # iou metric return x, x.max(1)[0] # x, best_x @@ -85,24 +97,24 @@ def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=10 _, best = metric(torch.tensor(k, dtype=torch.float32), wh) return (best * (best > thr).float()).mean() # fitness - def print_results(k): + def print_results(k, verbose=True): k = k[np.argsort(k.prod(1))] # sort small to large x, best = metric(k, wh0) bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr - print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr') - print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' - f'past_thr={x[x > thr].mean():.3f}-mean: ', end='') - for i, x in enumerate(k): - print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg + s = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n' \ + f'{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' \ + f'past_thr={x[x > thr].mean():.3f}-mean: ' + for x in k: + s += '%i,%i, ' % (round(x[0]), round(x[1])) + if verbose: + LOGGER.info(s[:-2]) return k - if isinstance(path, str): # *.yaml file - with open(path) as f: - data_dict = yaml.load(f, Loader=yaml.SafeLoader) # model dict - from utils.datasets import LoadImagesAndLabels + if isinstance(dataset, str): # *.yaml file + with open(dataset, errors='ignore') as f: + data_dict = yaml.safe_load(f) # model dict + from utils.dataloaders import LoadImagesAndLabels dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) - else: - dataset = path # dataset # Get label wh shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) @@ -111,18 +123,22 @@ def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=10 # Filter i = (wh0 < 3.0).any(1).sum() if i: - print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.') + LOGGER.info(f'{PREFIX}WARNING: Extremely small objects found: {i} of {len(wh0)} labels are < 3 pixels in size') wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels - # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 + # wh = wh * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 - # Kmeans calculation - print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...') - s = wh.std(0) # sigmas for whitening - k, dist = kmeans(wh / s, n, iter=30) # points, mean distance - k *= s - wh = torch.tensor(wh, dtype=torch.float32) # filtered - wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered - k = print_results(k) + # Kmeans init + try: + LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...') + assert n <= len(wh) # apply overdetermined constraint + s = wh.std(0) # sigmas for whitening + k = kmeans(wh / s, n, iter=30)[0] * s # points + assert n == len(k) # kmeans may return fewer points than requested if wh is insufficient or too similar + except Exception: + LOGGER.warning(f'{PREFIX}WARNING: switching strategies from kmeans to random init') + k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size # random init + wh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0)) + k = print_results(k, verbose=False) # Plot # k, d = [None] * 20, [None] * 20 @@ -137,19 +153,18 @@ def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=10 # fig.savefig('wh.png', dpi=200) # Evolve - npr = np.random f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma - pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar + pbar = tqdm(range(gen), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar for _ in pbar: v = np.ones(sh) while (v == 1).all(): # mutate until a change occurs (prevent duplicates) - v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) + v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) kg = (k.copy() * v).clip(min=2.0) fg = anchor_fitness(kg) if fg > f: f, k = fg, kg.copy() - pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' + pbar.desc = f'{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' if verbose: - print_results(k) + print_results(k, verbose) return print_results(k) diff --git a/Y5/utils/autobatch.py b/Y5/utils/autobatch.py new file mode 100755 index 0000000..7c0ed03 --- /dev/null +++ b/Y5/utils/autobatch.py @@ -0,0 +1,66 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Auto-batch utils +""" + +from copy import deepcopy + +import numpy as np +import torch + +from utils.general import LOGGER, colorstr, emojis +from utils.torch_utils import profile + + +def check_train_batch_size(model, imgsz=640, amp=True): + # Check YOLOv5 training batch size + with torch.cuda.amp.autocast(amp): + return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size + + +def autobatch(model, imgsz=640, fraction=0.9, batch_size=16): + # Automatically estimate best batch size to use `fraction` of available CUDA memory + # Usage: + # import torch + # from utils.autobatch import autobatch + # model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False) + # print(autobatch(model)) + + # Check device + prefix = colorstr('AutoBatch: ') + LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}') + device = next(model.parameters()).device # get model device + if device.type == 'cpu': + LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}') + return batch_size + + # Inspect CUDA memory + gb = 1 << 30 # bytes to GiB (1024 ** 3) + d = str(device).upper() # 'CUDA:0' + properties = torch.cuda.get_device_properties(device) # device properties + t = properties.total_memory / gb # GiB total + r = torch.cuda.memory_reserved(device) / gb # GiB reserved + a = torch.cuda.memory_allocated(device) / gb # GiB allocated + f = t - (r + a) # GiB free + LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free') + + # Profile batch sizes + batch_sizes = [1, 2, 4, 8, 16] + try: + img = [torch.zeros(b, 3, imgsz, imgsz) for b in batch_sizes] + results = profile(img, model, n=3, device=device) + except Exception as e: + LOGGER.warning(f'{prefix}{e}') + + # Fit a solution + y = [x[2] for x in results if x] # memory [2] + p = np.polyfit(batch_sizes[:len(y)], y, deg=1) # first degree polynomial fit + b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size) + if None in results: # some sizes failed + i = results.index(None) # first fail index + if b >= batch_sizes[i]: # y intercept above failure point + b = batch_sizes[max(i - 1, 0)] # select prior safe point + + fraction = np.polyval(p, b) / t # actual fraction predicted + LOGGER.info(emojis(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅')) + return b diff --git a/Y5/utils/aws/resume.py b/Y5/utils/aws/resume.py index 563f22b..b21731c 100755 --- a/Y5/utils/aws/resume.py +++ b/Y5/utils/aws/resume.py @@ -1,4 +1,4 @@ -# Resume all interrupted trainings in yolov5/ dir including DPP trainings +# Resume all interrupted trainings in yolov5/ dir including DDP trainings # Usage: $ python utils/aws/resume.py import os @@ -8,7 +8,10 @@ from pathlib import Path import torch import yaml -sys.path.append('./') # to run '$ python *.py' files in subdirectories +FILE = Path(__file__).resolve() +ROOT = FILE.parents[2] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH port = 0 # --master_port path = Path('').resolve() @@ -18,8 +21,8 @@ for last in path.rglob('*/**/last.pt'): continue # Load opt.yaml - with open(last.parent.parent / 'opt.yaml') as f: - opt = yaml.load(f, Loader=yaml.SafeLoader) + with open(last.parent.parent / 'opt.yaml', errors='ignore') as f: + opt = yaml.safe_load(f) # Get device count d = opt['device'].split(',') # devices @@ -28,7 +31,7 @@ for last in path.rglob('*/**/last.pt'): if ddp: # multi-GPU port += 1 - cmd = f'python -m torch.distributed.launch --nproc_per_node {nd} --master_port {port} train.py --resume {last}' + cmd = f'python -m torch.distributed.run --nproc_per_node {nd} --master_port {port} train.py --resume {last}' else: # single-GPU cmd = f'python train.py --resume {last}' diff --git a/Y5/utils/aws/userdata.sh b/Y5/utils/aws/userdata.sh index 890606b..5fc1332 100755 --- a/Y5/utils/aws/userdata.sh +++ b/Y5/utils/aws/userdata.sh @@ -7,9 +7,9 @@ cd home/ubuntu if [ ! -d yolov5 ]; then echo "Running first-time script." # install dependencies, download COCO, pull Docker - git clone https://github.com/ultralytics/yolov5 && sudo chmod -R 777 yolov5 + git clone https://github.com/ultralytics/yolov5 -b master && sudo chmod -R 777 yolov5 cd yolov5 - bash data/scripts/get_coco.sh && echo "Data done." & + bash data/scripts/get_coco.sh && echo "COCO done." & sudo docker pull ultralytics/yolov5:latest && echo "Docker done." & python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." & wait && echo "All tasks done." # finish background tasks diff --git a/Y5/utils/benchmarks.py b/Y5/utils/benchmarks.py new file mode 100755 index 0000000..d0f2a25 --- /dev/null +++ b/Y5/utils/benchmarks.py @@ -0,0 +1,148 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Run YOLOv5 benchmarks on all supported export formats + +Format | `export.py --include` | Model +--- | --- | --- +PyTorch | - | yolov5s.pt +TorchScript | `torchscript` | yolov5s.torchscript +ONNX | `onnx` | yolov5s.onnx +OpenVINO | `openvino` | yolov5s_openvino_model/ +TensorRT | `engine` | yolov5s.engine +CoreML | `coreml` | yolov5s.mlmodel +TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/ +TensorFlow GraphDef | `pb` | yolov5s.pb +TensorFlow Lite | `tflite` | yolov5s.tflite +TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite +TensorFlow.js | `tfjs` | yolov5s_web_model/ + +Requirements: + $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU + $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU + $ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT + +Usage: + $ python utils/benchmarks.py --weights yolov5s.pt --img 640 +""" + +import argparse +import sys +import time +from pathlib import Path + +import pandas as pd + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +# ROOT = ROOT.relative_to(Path.cwd()) # relative + +import export +import val +from utils import notebook_init +from utils.general import LOGGER, check_yaml, print_args +from utils.torch_utils import select_device + + +def run( + weights=ROOT / 'yolov5s.pt', # weights path + imgsz=640, # inference size (pixels) + batch_size=1, # batch size + data=ROOT / 'data/coco128.yaml', # dataset.yaml path + device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu + half=False, # use FP16 half-precision inference + test=False, # test exports only + pt_only=False, # test PyTorch only +): + y, t = [], time.time() + device = select_device(device) + for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable) + try: + assert i != 9, 'Edge TPU not supported' + assert i != 10, 'TF.js not supported' + if device.type != 'cpu': + assert gpu, f'{name} inference not supported on GPU' + + # Export + if f == '-': + w = weights # PyTorch format + else: + w = export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # all others + assert suffix in str(w), 'export failed' + + # Validate + result = val.run(data, w, batch_size, imgsz, plots=False, device=device, task='benchmark', half=half) + metrics = result[0] # metrics (mp, mr, map50, map, *losses(box, obj, cls)) + speeds = result[2] # times (preprocess, inference, postprocess) + y.append([name, round(metrics[3], 4), round(speeds[1], 2)]) # mAP, t_inference + except Exception as e: + LOGGER.warning(f'WARNING: Benchmark failure for {name}: {e}') + y.append([name, None, None]) # mAP, t_inference + if pt_only and i == 0: + break # break after PyTorch + + # Print results + LOGGER.info('\n') + parse_opt() + notebook_init() # print system info + py = pd.DataFrame(y, columns=['Format', 'mAP@0.5:0.95', 'Inference time (ms)'] if map else ['Format', 'Export', '']) + LOGGER.info(f'\nBenchmarks complete ({time.time() - t:.2f}s)') + LOGGER.info(str(py if map else py.iloc[:, :2])) + return py + + +def test( + weights=ROOT / 'yolov5s.pt', # weights path + imgsz=640, # inference size (pixels) + batch_size=1, # batch size + data=ROOT / 'data/coco128.yaml', # dataset.yaml path + device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu + half=False, # use FP16 half-precision inference + test=False, # test exports only + pt_only=False, # test PyTorch only +): + y, t = [], time.time() + device = select_device(device) + for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable) + try: + w = weights if f == '-' else \ + export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # weights + assert suffix in str(w), 'export failed' + y.append([name, True]) + except Exception: + y.append([name, False]) # mAP, t_inference + + # Print results + LOGGER.info('\n') + parse_opt() + notebook_init() # print system info + py = pd.DataFrame(y, columns=['Format', 'Export']) + LOGGER.info(f'\nExports complete ({time.time() - t:.2f}s)') + LOGGER.info(str(py)) + return py + + +def parse_opt(): + parser = argparse.ArgumentParser() + parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path') + parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)') + parser.add_argument('--batch-size', type=int, default=1, help='batch size') + parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path') + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') + parser.add_argument('--test', action='store_true', help='test exports only') + parser.add_argument('--pt-only', action='store_true', help='test PyTorch only') + opt = parser.parse_args() + opt.data = check_yaml(opt.data) # check YAML + print_args(vars(opt)) + return opt + + +def main(opt): + test(**vars(opt)) if opt.test else run(**vars(opt)) + + +if __name__ == "__main__": + opt = parse_opt() + main(opt) diff --git a/Y5/utils/callbacks.py b/Y5/utils/callbacks.py new file mode 100755 index 0000000..2b32df0 --- /dev/null +++ b/Y5/utils/callbacks.py @@ -0,0 +1,71 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Callback utils +""" + + +class Callbacks: + """" + Handles all registered callbacks for YOLOv5 Hooks + """ + + def __init__(self): + # Define the available callbacks + self._callbacks = { + 'on_pretrain_routine_start': [], + 'on_pretrain_routine_end': [], + 'on_train_start': [], + 'on_train_epoch_start': [], + 'on_train_batch_start': [], + 'optimizer_step': [], + 'on_before_zero_grad': [], + 'on_train_batch_end': [], + 'on_train_epoch_end': [], + 'on_val_start': [], + 'on_val_batch_start': [], + 'on_val_image_end': [], + 'on_val_batch_end': [], + 'on_val_end': [], + 'on_fit_epoch_end': [], # fit = train + val + 'on_model_save': [], + 'on_train_end': [], + 'on_params_update': [], + 'teardown': [],} + self.stop_training = False # set True to interrupt training + + def register_action(self, hook, name='', callback=None): + """ + Register a new action to a callback hook + + Args: + hook: The callback hook name to register the action to + name: The name of the action for later reference + callback: The callback to fire + """ + assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}" + assert callable(callback), f"callback '{callback}' is not callable" + self._callbacks[hook].append({'name': name, 'callback': callback}) + + def get_registered_actions(self, hook=None): + """" + Returns all the registered actions by callback hook + + Args: + hook: The name of the hook to check, defaults to all + """ + return self._callbacks[hook] if hook else self._callbacks + + def run(self, hook, *args, **kwargs): + """ + Loop through the registered actions and fire all callbacks + + Args: + hook: The name of the hook to check, defaults to all + args: Arguments to receive from YOLOv5 + kwargs: Keyword Arguments to receive from YOLOv5 + """ + + assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}" + + for logger in self._callbacks[hook]: + logger['callback'](*args, **kwargs) diff --git a/Y5/utils/dataloaders.py b/Y5/utils/dataloaders.py new file mode 100755 index 0000000..4690f0c --- /dev/null +++ b/Y5/utils/dataloaders.py @@ -0,0 +1,1087 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Dataloaders and dataset utils +""" + +import glob +import hashlib +import json +import math +import os +import random +import shutil +import time +from itertools import repeat +from multiprocessing.pool import Pool, ThreadPool +from pathlib import Path +from threading import Thread +from urllib.parse import urlparse +from zipfile import ZipFile + +import numpy as np +import torch +import torch.nn.functional as F +import yaml +from PIL import ExifTags, Image, ImageOps +from torch.utils.data import DataLoader, Dataset, dataloader, distributed +from tqdm import tqdm + +from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective +from utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, check_dataset, check_requirements, check_yaml, clean_str, + cv2, segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn) +from utils.torch_utils import torch_distributed_zero_first + +# Parameters +HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data' +IMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp' # include image suffixes +VID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv' # include video suffixes +BAR_FORMAT = '{l_bar}{bar:10}{r_bar}{bar:-10b}' # tqdm bar format +LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html + +# Get orientation exif tag +for orientation in ExifTags.TAGS.keys(): + if ExifTags.TAGS[orientation] == 'Orientation': + break + + +def get_hash(paths): + # Returns a single hash value of a list of paths (files or dirs) + size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes + h = hashlib.md5(str(size).encode()) # hash sizes + h.update(''.join(paths).encode()) # hash paths + return h.hexdigest() # return hash + + +def exif_size(img): + # Returns exif-corrected PIL size + s = img.size # (width, height) + try: + rotation = dict(img._getexif().items())[orientation] + if rotation in [6, 8]: # rotation 270 or 90 + s = (s[1], s[0]) + except Exception: + pass + + return s + + +def exif_transpose(image): + """ + Transpose a PIL image accordingly if it has an EXIF Orientation tag. + Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose() + + :param image: The image to transpose. + :return: An image. + """ + exif = image.getexif() + orientation = exif.get(0x0112, 1) # default 1 + if orientation > 1: + method = { + 2: Image.FLIP_LEFT_RIGHT, + 3: Image.ROTATE_180, + 4: Image.FLIP_TOP_BOTTOM, + 5: Image.TRANSPOSE, + 6: Image.ROTATE_270, + 7: Image.TRANSVERSE, + 8: Image.ROTATE_90,}.get(orientation) + if method is not None: + image = image.transpose(method) + del exif[0x0112] + image.info["exif"] = exif.tobytes() + return image + + +def create_dataloader(path, + imgsz, + batch_size, + stride, + single_cls=False, + hyp=None, + augment=False, + cache=False, + pad=0.0, + rect=False, + rank=-1, + workers=8, + image_weights=False, + quad=False, + prefix='', + shuffle=False): + if rect and shuffle: + LOGGER.warning('WARNING: --rect is incompatible with DataLoader shuffle, setting shuffle=False') + shuffle = False + with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP + dataset = LoadImagesAndLabels( + path, + imgsz, + batch_size, + augment=augment, # augmentation + hyp=hyp, # hyperparameters + rect=rect, # rectangular batches + cache_images=cache, + single_cls=single_cls, + stride=int(stride), + pad=pad, + image_weights=image_weights, + prefix=prefix) + + batch_size = min(batch_size, len(dataset)) + nd = torch.cuda.device_count() # number of CUDA devices + nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers + sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle) + loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates + return loader(dataset, + batch_size=batch_size, + shuffle=shuffle and sampler is None, + num_workers=nw, + sampler=sampler, + pin_memory=True, + collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn), dataset + + +class InfiniteDataLoader(dataloader.DataLoader): + """ Dataloader that reuses workers + + Uses same syntax as vanilla DataLoader + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler)) + self.iterator = super().__iter__() + + def __len__(self): + return len(self.batch_sampler.sampler) + + def __iter__(self): + for _ in range(len(self)): + yield next(self.iterator) + + +class _RepeatSampler: + """ Sampler that repeats forever + + Args: + sampler (Sampler) + """ + + def __init__(self, sampler): + self.sampler = sampler + + def __iter__(self): + while True: + yield from iter(self.sampler) + + +class LoadImages: + # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4` + def __init__(self, path, img_size=640, stride=32, auto=True): + p = str(Path(path).resolve()) # os-agnostic absolute path + if '*' in p: + files = sorted(glob.glob(p, recursive=True)) # glob + elif os.path.isdir(p): + files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir + elif os.path.isfile(p): + files = [p] # files + else: + raise Exception(f'ERROR: {p} does not exist') + + images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS] + videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS] + ni, nv = len(images), len(videos) + + self.img_size = img_size + self.stride = stride + self.files = images + videos + self.nf = ni + nv # number of files + self.video_flag = [False] * ni + [True] * nv + self.mode = 'image' + self.auto = auto + if any(videos): + self.new_video(videos[0]) # new video + else: + self.cap = None + assert self.nf > 0, f'No images or videos found in {p}. ' \ + f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}' + + def __iter__(self): + self.count = 0 + return self + + def __next__(self): + if self.count == self.nf: + raise StopIteration + path = self.files[self.count] + + if self.video_flag[self.count]: + # Read video + self.mode = 'video' + ret_val, img0 = self.cap.read() + while not ret_val: + self.count += 1 + self.cap.release() + if self.count == self.nf: # last video + raise StopIteration + path = self.files[self.count] + self.new_video(path) + ret_val, img0 = self.cap.read() + + self.frame += 1 + s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ' + + else: + # Read image + self.count += 1 + img0 = cv2.imread(path) # BGR + assert img0 is not None, f'Image Not Found {path}' + s = f'image {self.count}/{self.nf} {path}: ' + + # Padded resize + img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0] + + # Convert + img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB + img = np.ascontiguousarray(img) + + return path, img, img0, self.cap, s + + def new_video(self, path): + self.frame = 0 + self.cap = cv2.VideoCapture(path) + self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) + + def __len__(self): + return self.nf # number of files + + +class LoadWebcam: # for inference + # YOLOv5 local webcam dataloader, i.e. `python detect.py --source 0` + def __init__(self, pipe='0', img_size=640, stride=32): + self.img_size = img_size + self.stride = stride + self.pipe = eval(pipe) if pipe.isnumeric() else pipe + self.cap = cv2.VideoCapture(self.pipe) # video capture object + self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size + + def __iter__(self): + self.count = -1 + return self + + def __next__(self): + self.count += 1 + if cv2.waitKey(1) == ord('q'): # q to quit + self.cap.release() + cv2.destroyAllWindows() + raise StopIteration + + # Read frame + ret_val, img0 = self.cap.read() + img0 = cv2.flip(img0, 1) # flip left-right + + # Print + assert ret_val, f'Camera Error {self.pipe}' + img_path = 'webcam.jpg' + s = f'webcam {self.count}: ' + + # Padded resize + img = letterbox(img0, self.img_size, stride=self.stride)[0] + + # Convert + img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB + img = np.ascontiguousarray(img) + + return img_path, img, img0, None, s + + def __len__(self): + return 0 + + +class LoadStreams: + # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP streams` + def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True): + self.mode = 'stream' + self.img_size = img_size + self.stride = stride + + if os.path.isfile(sources): + with open(sources) as f: + sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())] + else: + sources = [sources] + + n = len(sources) + self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n + self.sources = [clean_str(x) for x in sources] # clean source names for later + self.auto = auto + for i, s in enumerate(sources): # index, source + # Start thread to read frames from video stream + st = f'{i + 1}/{n}: {s}... ' + if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'): # if source is YouTube video + check_requirements(('pafy', 'youtube_dl==2020.12.2')) + import pafy + s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL + s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam + cap = cv2.VideoCapture(s) + assert cap.isOpened(), f'{st}Failed to open {s}' + w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + fps = cap.get(cv2.CAP_PROP_FPS) # warning: may return 0 or nan + self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback + self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30 # 30 FPS fallback + + _, self.imgs[i] = cap.read() # guarantee first frame + self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True) + LOGGER.info(f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)") + self.threads[i].start() + LOGGER.info('') # newline + + # check for common shapes + s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs]) + self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal + if not self.rect: + LOGGER.warning('WARNING: Stream shapes differ. For optimal performance supply similarly-shaped streams.') + + def update(self, i, cap, stream): + # Read stream `i` frames in daemon thread + n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame + while cap.isOpened() and n < f: + n += 1 + # _, self.imgs[index] = cap.read() + cap.grab() + if n % read == 0: + success, im = cap.retrieve() + if success: + self.imgs[i] = im + else: + LOGGER.warning('WARNING: Video stream unresponsive, please check your IP camera connection.') + self.imgs[i] = np.zeros_like(self.imgs[i]) + cap.open(stream) # re-open stream if signal was lost + time.sleep(1 / self.fps[i]) # wait time + + def __iter__(self): + self.count = -1 + return self + + def __next__(self): + self.count += 1 + if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit + cv2.destroyAllWindows() + raise StopIteration + + # Letterbox + img0 = self.imgs.copy() + img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0] + + # Stack + img = np.stack(img, 0) + + # Convert + img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW + img = np.ascontiguousarray(img) + + return self.sources, img, img0, None, '' + + def __len__(self): + return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years + + +def img2label_paths(img_paths): + # Define label paths as a function of image paths + sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}' # /images/, /labels/ substrings + return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths] + + +class LoadImagesAndLabels(Dataset): + # YOLOv5 train_loader/val_loader, loads images and labels for training and validation + cache_version = 0.6 # dataset labels *.cache version + rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4] + + def __init__(self, + path, + img_size=640, + batch_size=16, + augment=False, + hyp=None, + rect=False, + image_weights=False, + cache_images=False, + single_cls=False, + stride=32, + pad=0.0, + prefix=''): + self.img_size = img_size + self.augment = augment + self.hyp = hyp + self.image_weights = image_weights + self.rect = False if image_weights else rect + self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training) + self.mosaic_border = [-img_size // 2, -img_size // 2] + self.stride = stride + self.path = path + self.albumentations = Albumentations() if augment else None + + try: + f = [] # image files + for p in path if isinstance(path, list) else [path]: + p = Path(p) # os-agnostic + if p.is_dir(): # dir + f += glob.glob(str(p / '**' / '*.*'), recursive=True) + # f = list(p.rglob('*.*')) # pathlib + elif p.is_file(): # file + with open(p) as t: + t = t.read().strip().splitlines() + parent = str(p.parent) + os.sep + f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path + # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib) + else: + raise Exception(f'{prefix}{p} does not exist') + self.im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS) + # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib + assert self.im_files, f'{prefix}No images found' + except Exception as e: + raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}') + + # Check cache + self.label_files = img2label_paths(self.im_files) # labels + cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') + try: + cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict + assert cache['version'] == self.cache_version # same version + assert cache['hash'] == get_hash(self.label_files + self.im_files) # same hash + except Exception: + cache, exists = self.cache_labels(cache_path, prefix), False # cache + + # Display cache + nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupt, total + if exists and LOCAL_RANK in {-1, 0}: + d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupt" + tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=BAR_FORMAT) # display cache results + if cache['msgs']: + LOGGER.info('\n'.join(cache['msgs'])) # display warnings + assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}' + + # Read cache + [cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items + labels, shapes, self.segments = zip(*cache.values()) + self.labels = list(labels) + self.shapes = np.array(shapes, dtype=np.float64) + self.im_files = list(cache.keys()) # update + self.label_files = img2label_paths(cache.keys()) # update + n = len(shapes) # number of images + bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index + nb = bi[-1] + 1 # number of batches + self.batch = bi # batch index of image + self.n = n + self.indices = range(n) + + # Update labels + include_class = [] # filter labels to include only these classes (optional) + include_class_array = np.array(include_class).reshape(1, -1) + for i, (label, segment) in enumerate(zip(self.labels, self.segments)): + if include_class: + j = (label[:, 0:1] == include_class_array).any(1) + self.labels[i] = label[j] + if segment: + self.segments[i] = segment[j] + if single_cls: # single-class training, merge all classes into 0 + self.labels[i][:, 0] = 0 + if segment: + self.segments[i][:, 0] = 0 + + # Rectangular Training + if self.rect: + # Sort by aspect ratio + s = self.shapes # wh + ar = s[:, 1] / s[:, 0] # aspect ratio + irect = ar.argsort() + self.im_files = [self.im_files[i] for i in irect] + self.label_files = [self.label_files[i] for i in irect] + self.labels = [self.labels[i] for i in irect] + self.shapes = s[irect] # wh + ar = ar[irect] + + # Set training image shapes + shapes = [[1, 1]] * nb + for i in range(nb): + ari = ar[bi == i] + mini, maxi = ari.min(), ari.max() + if maxi < 1: + shapes[i] = [maxi, 1] + elif mini > 1: + shapes[i] = [1, 1 / mini] + + self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride + + # Cache images into RAM/disk for faster training (WARNING: large datasets may exceed system resources) + self.ims = [None] * n + self.npy_files = [Path(f).with_suffix('.npy') for f in self.im_files] + if cache_images: + gb = 0 # Gigabytes of cached images + self.im_hw0, self.im_hw = [None] * n, [None] * n + fcn = self.cache_images_to_disk if cache_images == 'disk' else self.load_image + results = ThreadPool(NUM_THREADS).imap(fcn, range(n)) + pbar = tqdm(enumerate(results), total=n, bar_format=BAR_FORMAT, disable=LOCAL_RANK > 0) + for i, x in pbar: + if cache_images == 'disk': + gb += self.npy_files[i].stat().st_size + else: # 'ram' + self.ims[i], self.im_hw0[i], self.im_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i) + gb += self.ims[i].nbytes + pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})' + pbar.close() + + def cache_labels(self, path=Path('./labels.cache'), prefix=''): + # Cache dataset labels, check images and read shapes + x = {} # dict + nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages + desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..." + with Pool(NUM_THREADS) as pool: + pbar = tqdm(pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix))), + desc=desc, + total=len(self.im_files), + bar_format=BAR_FORMAT) + for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar: + nm += nm_f + nf += nf_f + ne += ne_f + nc += nc_f + if im_file: + x[im_file] = [lb, shape, segments] + if msg: + msgs.append(msg) + pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupt" + + pbar.close() + if msgs: + LOGGER.info('\n'.join(msgs)) + if nf == 0: + LOGGER.warning(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}') + x['hash'] = get_hash(self.label_files + self.im_files) + x['results'] = nf, nm, ne, nc, len(self.im_files) + x['msgs'] = msgs # warnings + x['version'] = self.cache_version # cache version + try: + np.save(path, x) # save cache for next time + path.with_suffix('.cache.npy').rename(path) # remove .npy suffix + LOGGER.info(f'{prefix}New cache created: {path}') + except Exception as e: + LOGGER.warning(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # not writeable + return x + + def __len__(self): + return len(self.im_files) + + # def __iter__(self): + # self.count = -1 + # print('ran dataset iter') + # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF) + # return self + + def __getitem__(self, index): + index = self.indices[index] # linear, shuffled, or image_weights + + hyp = self.hyp + mosaic = self.mosaic and random.random() < hyp['mosaic'] + if mosaic: + # Load mosaic + img, labels = self.load_mosaic(index) + shapes = None + + # MixUp augmentation + if random.random() < hyp['mixup']: + img, labels = mixup(img, labels, *self.load_mosaic(random.randint(0, self.n - 1))) + + else: + # Load image + img, (h0, w0), (h, w) = self.load_image(index) + + # Letterbox + shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape + img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment) + shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling + + labels = self.labels[index].copy() + if labels.size: # normalized xywh to pixel xyxy format + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1]) + + if self.augment: + img, labels = random_perspective(img, + labels, + degrees=hyp['degrees'], + translate=hyp['translate'], + scale=hyp['scale'], + shear=hyp['shear'], + perspective=hyp['perspective']) + + nl = len(labels) # number of labels + if nl: + labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3) + + if self.augment: + # Albumentations + img, labels = self.albumentations(img, labels) + nl = len(labels) # update after albumentations + + # HSV color-space + augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v']) + + # Flip up-down + if random.random() < hyp['flipud']: + img = np.flipud(img) + if nl: + labels[:, 2] = 1 - labels[:, 2] + + # Flip left-right + if random.random() < hyp['fliplr']: + img = np.fliplr(img) + if nl: + labels[:, 1] = 1 - labels[:, 1] + + # Cutouts + # labels = cutout(img, labels, p=0.5) + # nl = len(labels) # update after cutout + + labels_out = torch.zeros((nl, 6)) + if nl: + labels_out[:, 1:] = torch.from_numpy(labels) + + # Convert + img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB + img = np.ascontiguousarray(img) + + return torch.from_numpy(img), labels_out, self.im_files[index], shapes + + def load_image(self, i): + # Loads 1 image from dataset index 'i', returns (im, original hw, resized hw) + im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i], + if im is None: # not cached in RAM + if fn.exists(): # load npy + im = np.load(fn) + else: # read image + im = cv2.imread(f) # BGR + assert im is not None, f'Image Not Found {f}' + h0, w0 = im.shape[:2] # orig hw + r = self.img_size / max(h0, w0) # ratio + if r != 1: # if sizes are not equal + interp = cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA + im = cv2.resize(im, (int(w0 * r), int(h0 * r)), interpolation=interp) + return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized + else: + return self.ims[i], self.im_hw0[i], self.im_hw[i] # im, hw_original, hw_resized + + def cache_images_to_disk(self, i): + # Saves an image as an *.npy file for faster loading + f = self.npy_files[i] + if not f.exists(): + np.save(f.as_posix(), cv2.imread(self.im_files[i])) + + def load_mosaic(self, index): + # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic + labels4, segments4 = [], [] + s = self.img_size + yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y + indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices + random.shuffle(indices) + for i, index in enumerate(indices): + # Load image + img, _, (h, w) = self.load_image(index) + + # place img in img4 + if i == 0: # top left + img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles + x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image) + x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image) + elif i == 1: # top right + x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc + x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h + elif i == 2: # bottom left + x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) + x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) + elif i == 3: # bottom right + x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) + x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) + + img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] + padw = x1a - x1b + padh = y1a - y1b + + # Labels + labels, segments = self.labels[index].copy(), self.segments[index].copy() + if labels.size: + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format + segments = [xyn2xy(x, w, h, padw, padh) for x in segments] + labels4.append(labels) + segments4.extend(segments) + + # Concat/clip labels + labels4 = np.concatenate(labels4, 0) + for x in (labels4[:, 1:], *segments4): + np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() + # img4, labels4 = replicate(img4, labels4) # replicate + + # Augment + img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste']) + img4, labels4 = random_perspective(img4, + labels4, + segments4, + degrees=self.hyp['degrees'], + translate=self.hyp['translate'], + scale=self.hyp['scale'], + shear=self.hyp['shear'], + perspective=self.hyp['perspective'], + border=self.mosaic_border) # border to remove + + return img4, labels4 + + def load_mosaic9(self, index): + # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic + labels9, segments9 = [], [] + s = self.img_size + indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices + random.shuffle(indices) + hp, wp = -1, -1 # height, width previous + for i, index in enumerate(indices): + # Load image + img, _, (h, w) = self.load_image(index) + + # place img in img9 + if i == 0: # center + img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles + h0, w0 = h, w + c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates + elif i == 1: # top + c = s, s - h, s + w, s + elif i == 2: # top right + c = s + wp, s - h, s + wp + w, s + elif i == 3: # right + c = s + w0, s, s + w0 + w, s + h + elif i == 4: # bottom right + c = s + w0, s + hp, s + w0 + w, s + hp + h + elif i == 5: # bottom + c = s + w0 - w, s + h0, s + w0, s + h0 + h + elif i == 6: # bottom left + c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h + elif i == 7: # left + c = s - w, s + h0 - h, s, s + h0 + elif i == 8: # top left + c = s - w, s + h0 - hp - h, s, s + h0 - hp + + padx, pady = c[:2] + x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords + + # Labels + labels, segments = self.labels[index].copy(), self.segments[index].copy() + if labels.size: + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format + segments = [xyn2xy(x, w, h, padx, pady) for x in segments] + labels9.append(labels) + segments9.extend(segments) + + # Image + img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax] + hp, wp = h, w # height, width previous + + # Offset + yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y + img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s] + + # Concat/clip labels + labels9 = np.concatenate(labels9, 0) + labels9[:, [1, 3]] -= xc + labels9[:, [2, 4]] -= yc + c = np.array([xc, yc]) # centers + segments9 = [x - c for x in segments9] + + for x in (labels9[:, 1:], *segments9): + np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() + # img9, labels9 = replicate(img9, labels9) # replicate + + # Augment + img9, labels9 = random_perspective(img9, + labels9, + segments9, + degrees=self.hyp['degrees'], + translate=self.hyp['translate'], + scale=self.hyp['scale'], + shear=self.hyp['shear'], + perspective=self.hyp['perspective'], + border=self.mosaic_border) # border to remove + + return img9, labels9 + + @staticmethod + def collate_fn(batch): + im, label, path, shapes = zip(*batch) # transposed + for i, lb in enumerate(label): + lb[:, 0] = i # add target image index for build_targets() + return torch.stack(im, 0), torch.cat(label, 0), path, shapes + + @staticmethod + def collate_fn4(batch): + img, label, path, shapes = zip(*batch) # transposed + n = len(shapes) // 4 + im4, label4, path4, shapes4 = [], [], path[:n], shapes[:n] + + ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]]) + wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]]) + s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale + for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW + i *= 4 + if random.random() < 0.5: + im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2.0, mode='bilinear', + align_corners=False)[0].type(img[i].type()) + lb = label[i] + else: + im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2) + lb = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s + im4.append(im) + label4.append(lb) + + for i, lb in enumerate(label4): + lb[:, 0] = i # add target image index for build_targets() + + return torch.stack(im4, 0), torch.cat(label4, 0), path4, shapes4 + + +# Ancillary functions -------------------------------------------------------------------------------------------------- +def create_folder(path='./new'): + # Create folder + if os.path.exists(path): + shutil.rmtree(path) # delete output folder + os.makedirs(path) # make new output folder + + +def flatten_recursive(path=DATASETS_DIR / 'coco128'): + # Flatten a recursive directory by bringing all files to top level + new_path = Path(str(path) + '_flat') + create_folder(new_path) + for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)): + shutil.copyfile(file, new_path / Path(file).name) + + +def extract_boxes(path=DATASETS_DIR / 'coco128'): # from utils.dataloaders import *; extract_boxes() + # Convert detection dataset into classification dataset, with one directory per class + path = Path(path) # images dir + shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing + files = list(path.rglob('*.*')) + n = len(files) # number of files + for im_file in tqdm(files, total=n): + if im_file.suffix[1:] in IMG_FORMATS: + # image + im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB + h, w = im.shape[:2] + + # labels + lb_file = Path(img2label_paths([str(im_file)])[0]) + if Path(lb_file).exists(): + with open(lb_file) as f: + lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels + + for j, x in enumerate(lb): + c = int(x[0]) # class + f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename + if not f.parent.is_dir(): + f.parent.mkdir(parents=True) + + b = x[1:] * [w, h, w, h] # box + # b[2:] = b[2:].max() # rectangle to square + b[2:] = b[2:] * 1.2 + 3 # pad + b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) + + b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image + b[[1, 3]] = np.clip(b[[1, 3]], 0, h) + assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}' + + +def autosplit(path=DATASETS_DIR / 'coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False): + """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files + Usage: from utils.dataloaders import *; autosplit() + Arguments + path: Path to images directory + weights: Train, val, test weights (list, tuple) + annotated_only: Only use images with an annotated txt file + """ + path = Path(path) # images dir + files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) # image files only + n = len(files) # number of files + random.seed(0) # for reproducibility + indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split + + txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files + [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing + + print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only) + for i, img in tqdm(zip(indices, files), total=n): + if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label + with open(path.parent / txt[i], 'a') as f: + f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file + + +def verify_image_label(args): + # Verify one image-label pair + im_file, lb_file, prefix = args + nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments + try: + # verify images + im = Image.open(im_file) + im.verify() # PIL verify + shape = exif_size(im) # image size + assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels' + assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}' + if im.format.lower() in ('jpg', 'jpeg'): + with open(im_file, 'rb') as f: + f.seek(-2, 2) + if f.read() != b'\xff\xd9': # corrupt JPEG + ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100) + msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved' + + # verify labels + if os.path.isfile(lb_file): + nf = 1 # label found + with open(lb_file) as f: + lb = [x.split() for x in f.read().strip().splitlines() if len(x)] + if any(len(x) > 6 for x in lb): # is segment + classes = np.array([x[0] for x in lb], dtype=np.float32) + segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...) + lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh) + lb = np.array(lb, dtype=np.float32) + nl = len(lb) + if nl: + assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected' + assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}' + assert (lb[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}' + _, i = np.unique(lb, axis=0, return_index=True) + if len(i) < nl: # duplicate row check + lb = lb[i] # remove duplicates + if segments: + segments = segments[i] + msg = f'{prefix}WARNING: {im_file}: {nl - len(i)} duplicate labels removed' + else: + ne = 1 # label empty + lb = np.zeros((0, 5), dtype=np.float32) + else: + nm = 1 # label missing + lb = np.zeros((0, 5), dtype=np.float32) + return im_file, lb, shape, segments, nm, nf, ne, nc, msg + except Exception as e: + nc = 1 + msg = f'{prefix}WARNING: {im_file}: ignoring corrupt image/label: {e}' + return [None, None, None, None, nm, nf, ne, nc, msg] + + +def dataset_stats(path='coco128.yaml', autodownload=False, verbose=False, profile=False, hub=False): + """ Return dataset statistics dictionary with images and instances counts per split per class + To run in parent directory: export PYTHONPATH="$PWD/yolov5" + Usage1: from utils.dataloaders import *; dataset_stats('coco128.yaml', autodownload=True) + Usage2: from utils.dataloaders import *; dataset_stats('path/to/coco128_with_yaml.zip') + Arguments + path: Path to data.yaml or data.zip (with data.yaml inside data.zip) + autodownload: Attempt to download dataset if not found locally + verbose: Print stats dictionary + """ + + def _round_labels(labels): + # Update labels to integer class and 6 decimal place floats + return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels] + + def _find_yaml(dir): + # Return data.yaml file + files = list(dir.glob('*.yaml')) or list(dir.rglob('*.yaml')) # try root level first and then recursive + assert files, f'No *.yaml file found in {dir}' + if len(files) > 1: + files = [f for f in files if f.stem == dir.stem] # prefer *.yaml files that match dir name + assert files, f'Multiple *.yaml files found in {dir}, only 1 *.yaml file allowed' + assert len(files) == 1, f'Multiple *.yaml files found: {files}, only 1 *.yaml file allowed in {dir}' + return files[0] + + def _unzip(path): + # Unzip data.zip + if str(path).endswith('.zip'): # path is data.zip + assert Path(path).is_file(), f'Error unzipping {path}, file not found' + ZipFile(path).extractall(path=path.parent) # unzip + dir = path.with_suffix('') # dataset directory == zip name + assert dir.is_dir(), f'Error unzipping {path}, {dir} not found. path/to/abc.zip MUST unzip to path/to/abc/' + return True, str(dir), _find_yaml(dir) # zipped, data_dir, yaml_path + else: # path is data.yaml + return False, None, path + + def _hub_ops(f, max_dim=1920): + # HUB ops for 1 image 'f': resize and save at reduced quality in /dataset-hub for web/app viewing + f_new = im_dir / Path(f).name # dataset-hub image filename + try: # use PIL + im = Image.open(f) + r = max_dim / max(im.height, im.width) # ratio + if r < 1.0: # image too large + im = im.resize((int(im.width * r), int(im.height * r))) + im.save(f_new, 'JPEG', quality=75, optimize=True) # save + except Exception as e: # use OpenCV + print(f'WARNING: HUB ops PIL failure {f}: {e}') + im = cv2.imread(f) + im_height, im_width = im.shape[:2] + r = max_dim / max(im_height, im_width) # ratio + if r < 1.0: # image too large + im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA) + cv2.imwrite(str(f_new), im) + + zipped, data_dir, yaml_path = _unzip(Path(path)) + with open(check_yaml(yaml_path), errors='ignore') as f: + data = yaml.safe_load(f) # data dict + if zipped: + data['path'] = data_dir # TODO: should this be dir.resolve()? + check_dataset(data, autodownload) # download dataset if missing + hub_dir = Path(data['path'] + ('-hub' if hub else '')) + stats = {'nc': data['nc'], 'names': data['names']} # statistics dictionary + for split in 'train', 'val', 'test': + if data.get(split) is None: + stats[split] = None # i.e. no test set + continue + x = [] + dataset = LoadImagesAndLabels(data[split]) # load dataset + for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'): + x.append(np.bincount(label[:, 0].astype(int), minlength=data['nc'])) + x = np.array(x) # shape(128x80) + stats[split] = { + 'instance_stats': { + 'total': int(x.sum()), + 'per_class': x.sum(0).tolist()}, + 'image_stats': { + 'total': dataset.n, + 'unlabelled': int(np.all(x == 0, 1).sum()), + 'per_class': (x > 0).sum(0).tolist()}, + 'labels': [{ + str(Path(k).name): _round_labels(v.tolist())} for k, v in zip(dataset.im_files, dataset.labels)]} + + if hub: + im_dir = hub_dir / 'images' + im_dir.mkdir(parents=True, exist_ok=True) + for _ in tqdm(ThreadPool(NUM_THREADS).imap(_hub_ops, dataset.im_files), total=dataset.n, desc='HUB Ops'): + pass + + # Profile + stats_path = hub_dir / 'stats.json' + if profile: + for _ in range(1): + file = stats_path.with_suffix('.npy') + t1 = time.time() + np.save(file, stats) + t2 = time.time() + x = np.load(file, allow_pickle=True) + print(f'stats.npy times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write') + + file = stats_path.with_suffix('.json') + t1 = time.time() + with open(file, 'w') as f: + json.dump(stats, f) # save stats *.json + t2 = time.time() + with open(file) as f: + x = json.load(f) # load hyps dict + print(f'stats.json times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write') + + # Save, print and return + if hub: + print(f'Saving {stats_path.resolve()}...') + with open(stats_path, 'w') as f: + json.dump(stats, f) # save stats.json + if verbose: + print(json.dumps(stats, indent=2, sort_keys=False)) + return stats diff --git a/Y5/utils/docker/.dockerignore b/Y5/utils/docker/.dockerignore new file mode 100755 index 0000000..af51ccc --- /dev/null +++ b/Y5/utils/docker/.dockerignore @@ -0,0 +1,222 @@ +# Repo-specific DockerIgnore ------------------------------------------------------------------------------------------- +#.git +.cache +.idea +runs +output +coco +storage.googleapis.com + +data/samples/* +**/results*.csv +*.jpg + +# Neural Network weights ----------------------------------------------------------------------------------------------- +**/*.pt +**/*.pth +**/*.onnx +**/*.engine +**/*.mlmodel +**/*.torchscript +**/*.torchscript.pt +**/*.tflite +**/*.h5 +**/*.pb +*_saved_model/ +*_web_model/ +*_openvino_model/ + +# Below Copied From .gitignore ----------------------------------------------------------------------------------------- +# Below Copied From .gitignore ----------------------------------------------------------------------------------------- + + +# GitHub Python GitIgnore ---------------------------------------------------------------------------------------------- +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +wandb/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv* +venv*/ +ENV*/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + + +# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore ----------------------------------------------- + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon +Icon? + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + + +# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/* +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries +.html # Bokeh Plots +.pg # TensorFlow Frozen Graphs +.avi # videos + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ +cmake-build-release/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties diff --git a/Y5/utils/docker/Dockerfile b/Y5/utils/docker/Dockerfile new file mode 100755 index 0000000..a5fc7cb --- /dev/null +++ b/Y5/utils/docker/Dockerfile @@ -0,0 +1,68 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Builds ultralytics/yolov5:latest image on DockerHub https://hub.docker.com/r/ultralytics/yolov5 +# Image is CUDA-optimized for YOLOv5 single/multi-GPU training and inference + +# Start FROM NVIDIA PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch +FROM nvcr.io/nvidia/pytorch:22.05-py3 +RUN rm -rf /opt/pytorch # remove 1.2GB dir + +# Downloads to user config dir +ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/ + +# Install linux packages +RUN apt update && apt install --no-install-recommends -y zip htop screen libgl1-mesa-glx + +# Install pip packages +COPY requirements.txt . +RUN python -m pip install --upgrade pip +RUN pip uninstall -y torch torchvision torchtext Pillow +RUN pip install --no-cache -r requirements.txt albumentations wandb gsutil notebook Pillow>=9.1.0 \ + 'opencv-python<4.6.0.66' \ + --extra-index-url https://download.pytorch.org/whl/cu113 + +# Create working directory +RUN mkdir -p /usr/src/app +WORKDIR /usr/src/app + +# Copy contents +COPY . /usr/src/app +RUN git clone https://github.com/ultralytics/yolov5 /usr/src/yolov5 + +# Set environment variables +ENV OMP_NUM_THREADS=8 + + +# Usage Examples ------------------------------------------------------------------------------------------------------- + +# Build and Push +# t=ultralytics/yolov5:latest && sudo docker build -f utils/docker/Dockerfile -t $t . && sudo docker push $t + +# Pull and Run +# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t + +# Pull and Run with local directory access +# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/datasets:/usr/src/datasets $t + +# Kill all +# sudo docker kill $(sudo docker ps -q) + +# Kill all image-based +# sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest) + +# Bash into running container +# sudo docker exec -it 5a9b5863d93d bash + +# Bash into stopped container +# id=$(sudo docker ps -qa) && sudo docker start $id && sudo docker exec -it $id bash + +# Clean up +# docker system prune -a --volumes + +# Update Ubuntu drivers +# https://www.maketecheasier.com/install-nvidia-drivers-ubuntu/ + +# DDP test +# python -m torch.distributed.run --nproc_per_node 2 --master_port 1 train.py --epochs 3 + +# GCP VM from Image +# docker.io/ultralytics/yolov5:latest diff --git a/Y5/utils/docker/Dockerfile-arm64 b/Y5/utils/docker/Dockerfile-arm64 new file mode 100755 index 0000000..2e26105 --- /dev/null +++ b/Y5/utils/docker/Dockerfile-arm64 @@ -0,0 +1,42 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Builds ultralytics/yolov5:latest-arm64 image on DockerHub https://hub.docker.com/r/ultralytics/yolov5 +# Image is aarch64-compatible for Apple M1 and other ARM architectures i.e. Jetson Nano and Raspberry Pi + +# Start FROM Ubuntu image https://hub.docker.com/_/ubuntu +FROM arm64v8/ubuntu:20.04 + +# Downloads to user config dir +ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/ + +# Install linux packages +RUN apt update +RUN DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt install -y tzdata +RUN apt install --no-install-recommends -y python3-pip git zip curl htop gcc \ + libgl1-mesa-glx libglib2.0-0 libpython3.8-dev +# RUN alias python=python3 + +# Install pip packages +COPY requirements.txt . +RUN python3 -m pip install --upgrade pip +RUN pip install --no-cache -r requirements.txt gsutil notebook \ + tensorflow-aarch64 + # tensorflowjs \ + # onnx onnx-simplifier onnxruntime \ + # coremltools openvino-dev \ + +# Create working directory +RUN mkdir -p /usr/src/app +WORKDIR /usr/src/app + +# Copy contents +COPY . /usr/src/app +RUN git clone https://github.com/ultralytics/yolov5 /usr/src/yolov5 + + +# Usage Examples ------------------------------------------------------------------------------------------------------- + +# Build and Push +# t=ultralytics/yolov5:latest-M1 && sudo docker build --platform linux/arm64 -f utils/docker/Dockerfile-arm64 -t $t . && sudo docker push $t + +# Pull and Run +# t=ultralytics/yolov5:latest-M1 && sudo docker pull $t && sudo docker run -it --ipc=host -v "$(pwd)"/datasets:/usr/src/datasets $t diff --git a/Y5/utils/docker/Dockerfile-cpu b/Y5/utils/docker/Dockerfile-cpu new file mode 100755 index 0000000..c8aa8c6 --- /dev/null +++ b/Y5/utils/docker/Dockerfile-cpu @@ -0,0 +1,39 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Builds ultralytics/yolov5:latest-cpu image on DockerHub https://hub.docker.com/r/ultralytics/yolov5 +# Image is CPU-optimized for ONNX, OpenVINO and PyTorch YOLOv5 deployments + +# Start FROM Ubuntu image https://hub.docker.com/_/ubuntu +FROM ubuntu:20.04 + +# Downloads to user config dir +ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/ + +# Install linux packages +RUN apt update +RUN DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt install -y tzdata +RUN apt install --no-install-recommends -y python3-pip git zip curl htop libgl1-mesa-glx libglib2.0-0 libpython3.8-dev +# RUN alias python=python3 + +# Install pip packages +COPY requirements.txt . +RUN python3 -m pip install --upgrade pip +RUN pip install --no-cache -r requirements.txt albumentations gsutil notebook \ + coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu tensorflowjs \ + --extra-index-url https://download.pytorch.org/whl/cpu + +# Create working directory +RUN mkdir -p /usr/src/app +WORKDIR /usr/src/app + +# Copy contents +COPY . /usr/src/app +RUN git clone https://github.com/ultralytics/yolov5 /usr/src/yolov5 + + +# Usage Examples ------------------------------------------------------------------------------------------------------- + +# Build and Push +# t=ultralytics/yolov5:latest-cpu && sudo docker build -f utils/docker/Dockerfile-cpu -t $t . && sudo docker push $t + +# Pull and Run +# t=ultralytics/yolov5:latest-cpu && sudo docker pull $t && sudo docker run -it --ipc=host -v "$(pwd)"/datasets:/usr/src/datasets $t diff --git a/Y5/utils/downloads.py b/Y5/utils/downloads.py new file mode 100755 index 0000000..ebe5bd3 --- /dev/null +++ b/Y5/utils/downloads.py @@ -0,0 +1,178 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Download utils +""" + +import logging +import os +import platform +import subprocess +import time +import urllib +from pathlib import Path +from zipfile import ZipFile + +import requests +import torch + + +def is_url(url): + # Check if online file exists + try: + r = urllib.request.urlopen(url) # response + return r.getcode() == 200 + except urllib.request.HTTPError: + return False + + +def gsutil_getsize(url=''): + # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du + s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8') + return eval(s.split(' ')[0]) if len(s) else 0 # bytes + + +def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''): + # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes + from utils.general import LOGGER + + file = Path(file) + assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}" + try: # url1 + LOGGER.info(f'Downloading {url} to {file}...') + torch.hub.download_url_to_file(url, str(file), progress=LOGGER.level <= logging.INFO) + assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check + except Exception as e: # url2 + file.unlink(missing_ok=True) # remove partial downloads + LOGGER.info(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...') + os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail + finally: + if not file.exists() or file.stat().st_size < min_bytes: # check + file.unlink(missing_ok=True) # remove partial downloads + LOGGER.info(f"ERROR: {assert_msg}\n{error_msg}") + LOGGER.info('') + + +def attempt_download(file, repo='ultralytics/yolov5', release='v6.1'): + # Attempt file download from GitHub release assets if not found locally. release = 'latest', 'v6.1', etc. + from utils.general import LOGGER + + def github_assets(repository, version='latest'): + # Return GitHub repo tag (i.e. 'v6.1') and assets (i.e. ['yolov5s.pt', 'yolov5m.pt', ...]) + if version != 'latest': + version = f'tags/{version}' # i.e. tags/v6.1 + response = requests.get(f'https://api.github.com/repos/{repository}/releases/{version}').json() # github api + return response['tag_name'], [x['name'] for x in response['assets']] # tag, assets + + file = Path(str(file).strip().replace("'", '')) + if not file.exists(): + # URL specified + name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc. + if str(file).startswith(('http:/', 'https:/')): # download + url = str(file).replace(':/', '://') # Pathlib turns :// -> :/ + file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth... + if Path(file).is_file(): + LOGGER.info(f'Found {url} locally at {file}') # file already exists + else: + safe_download(file=file, url=url, min_bytes=1E5) + return file + + # GitHub assets + assets = [ + 'yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov5n6.pt', 'yolov5s6.pt', + 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] + try: + tag, assets = github_assets(repo, release) + except Exception: + try: + tag, assets = github_assets(repo) # latest release + except Exception: + try: + tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] + except Exception: + tag = release + + file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required) + if name in assets: + url3 = 'https://drive.google.com/drive/folders/1EFQTEUeXWSFww0luse2jB9M1QNZQGwNl' # backup gdrive mirror + safe_download( + file, + url=f'https://github.com/{repo}/releases/download/{tag}/{name}', + url2=f'https://storage.googleapis.com/{repo}/{tag}/{name}', # backup url (optional) + min_bytes=1E5, + error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/{tag} or {url3}') + + return str(file) + + +def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'): + # Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download() + t = time.time() + file = Path(file) + cookie = Path('cookie') # gdrive cookie + print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='') + file.unlink(missing_ok=True) # remove existing file + cookie.unlink(missing_ok=True) # remove existing cookie + + # Attempt file download + out = "NUL" if platform.system() == "Windows" else "/dev/null" + os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}') + if os.path.exists('cookie'): # large file + s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}' + else: # small file + s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"' + r = os.system(s) # execute, capture return + cookie.unlink(missing_ok=True) # remove existing cookie + + # Error check + if r != 0: + file.unlink(missing_ok=True) # remove partial + print('Download error ') # raise Exception('Download error') + return r + + # Unzip if archive + if file.suffix == '.zip': + print('unzipping... ', end='') + ZipFile(file).extractall(path=file.parent) # unzip + file.unlink() # remove zip + + print(f'Done ({time.time() - t:.1f}s)') + return r + + +def get_token(cookie="./cookie"): + with open(cookie) as f: + for line in f: + if "download" in line: + return line.split()[-1] + return "" + + +# Google utils: https://cloud.google.com/storage/docs/reference/libraries ---------------------------------------------- +# +# +# def upload_blob(bucket_name, source_file_name, destination_blob_name): +# # Uploads a file to a bucket +# # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python +# +# storage_client = storage.Client() +# bucket = storage_client.get_bucket(bucket_name) +# blob = bucket.blob(destination_blob_name) +# +# blob.upload_from_filename(source_file_name) +# +# print('File {} uploaded to {}.'.format( +# source_file_name, +# destination_blob_name)) +# +# +# def download_blob(bucket_name, source_blob_name, destination_file_name): +# # Uploads a blob from a bucket +# storage_client = storage.Client() +# bucket = storage_client.get_bucket(bucket_name) +# blob = bucket.blob(source_blob_name) +# +# blob.download_to_filename(destination_file_name) +# +# print('Blob {} downloaded to {}.'.format( +# source_blob_name, +# destination_file_name)) diff --git a/Y5/utils/flask_rest_api/README.md b/Y5/utils/flask_rest_api/README.md new file mode 100755 index 0000000..a726acb --- /dev/null +++ b/Y5/utils/flask_rest_api/README.md @@ -0,0 +1,73 @@ +# Flask REST API + +[REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are +commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API +created using Flask to expose the YOLOv5s model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/). + +## Requirements + +[Flask](https://palletsprojects.com/p/flask/) is required. Install with: + +```shell +$ pip install Flask +``` + +## Run + +After Flask installation run: + +```shell +$ python3 restapi.py --port 5000 +``` + +Then use [curl](https://curl.se/) to perform a request: + +```shell +$ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s' +``` + +The model inference results are returned as a JSON response: + +```json +[ + { + "class": 0, + "confidence": 0.8900438547, + "height": 0.9318675399, + "name": "person", + "width": 0.3264600933, + "xcenter": 0.7438579798, + "ycenter": 0.5207948685 + }, + { + "class": 0, + "confidence": 0.8440024257, + "height": 0.7155083418, + "name": "person", + "width": 0.6546785235, + "xcenter": 0.427829951, + "ycenter": 0.6334488392 + }, + { + "class": 27, + "confidence": 0.3771208823, + "height": 0.3902671337, + "name": "tie", + "width": 0.0696444362, + "xcenter": 0.3675483763, + "ycenter": 0.7991207838 + }, + { + "class": 27, + "confidence": 0.3527112305, + "height": 0.1540903747, + "name": "tie", + "width": 0.0336618312, + "xcenter": 0.7814827561, + "ycenter": 0.5065554976 + } +] +``` + +An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given +in `example_request.py` diff --git a/Y5/utils/flask_rest_api/example_request.py b/Y5/utils/flask_rest_api/example_request.py new file mode 100755 index 0000000..773ad89 --- /dev/null +++ b/Y5/utils/flask_rest_api/example_request.py @@ -0,0 +1,19 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Perform test request +""" + +import pprint + +import requests + +DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s" +IMAGE = "zidane.jpg" + +# Read image +with open(IMAGE, "rb") as f: + image_data = f.read() + +response = requests.post(DETECTION_URL, files={"image": image_data}).json() + +pprint.pprint(response) diff --git a/Y5/utils/flask_rest_api/restapi.py b/Y5/utils/flask_rest_api/restapi.py new file mode 100755 index 0000000..08036dd --- /dev/null +++ b/Y5/utils/flask_rest_api/restapi.py @@ -0,0 +1,46 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Run a Flask REST API exposing a YOLOv5s model +""" + +import argparse +import io + +import torch +from flask import Flask, request +from PIL import Image + +app = Flask(__name__) + +DETECTION_URL = "/v1/object-detection/yolov5s" + + +@app.route(DETECTION_URL, methods=["POST"]) +def predict(): + if request.method != "POST": + return + + if request.files.get("image"): + # Method 1 + # with request.files["image"] as f: + # im = Image.open(io.BytesIO(f.read())) + + # Method 2 + im_file = request.files["image"] + im_bytes = im_file.read() + im = Image.open(io.BytesIO(im_bytes)) + + results = model(im, size=640) # reduce size=320 for faster inference + return results.pandas().xyxy[0].to_json(orient="records") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model") + parser.add_argument("--port", default=5000, type=int, help="port number") + opt = parser.parse_args() + + # Fix known issue urllib.error.HTTPError 403: rate limit exceeded https://github.com/ultralytics/yolov5/pull/7210 + torch.hub._validate_not_a_forked_repo = lambda a, b, c: True + + model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache + app.run(host="0.0.0.0", port=opt.port) # debug=True causes Restarting with stat diff --git a/Y5/utils/general.py b/Y5/utils/general.py index bcafd51..9fc7349 100755 --- a/Y5/utils/general.py +++ b/Y5/utils/general.py @@ -1,44 +1,213 @@ -# General utils +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +General utils +""" +import contextlib import glob +import inspect import logging import math import os import platform import random import re -import subprocess +import shutil +import signal +import threading import time +import urllib +from datetime import datetime +from itertools import repeat +from multiprocessing.pool import ThreadPool from pathlib import Path +from subprocess import check_output +from typing import Optional +from zipfile import ZipFile import cv2 import numpy as np +import pandas as pd +import pkg_resources as pkg import torch import torchvision import yaml -from Y5.utils.google_utils import gsutil_getsize -from Y5.utils.metrics import fitness -from Y5.utils.torch_utils import init_torch_seeds +from utils.downloads import gsutil_getsize +from utils.metrics import box_iou, fitness + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +RANK = int(os.getenv('RANK', -1)) # Settings +DATASETS_DIR = ROOT.parent / 'datasets' # YOLOv5 datasets directory +NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads +AUTOINSTALL = str(os.getenv('YOLOv5_AUTOINSTALL', True)).lower() == 'true' # global auto-install mode +VERBOSE = str(os.getenv('YOLOv5_VERBOSE', True)).lower() == 'true' # global verbose mode +FONT = 'Arial.ttf' # https://ultralytics.com/assets/Arial.ttf + torch.set_printoptions(linewidth=320, precision=5, profile='long') np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5 +pd.options.display.max_columns = 10 cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader) -os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8)) # NumExpr max threads +os.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS) # NumExpr max threads +os.environ['OMP_NUM_THREADS'] = str(NUM_THREADS) # OpenMP max threads (PyTorch and SciPy) -def set_logging(rank=-1): - logging.basicConfig( - format="%(message)s", - level=logging.INFO if rank in [-1, 0] else logging.WARN) +def is_kaggle(): + # Is environment a Kaggle Notebook? + try: + assert os.environ.get('PWD') == '/kaggle/working' + assert os.environ.get('KAGGLE_URL_BASE') == 'https://www.kaggle.com' + return True + except AssertionError: + return False + + +def is_writeable(dir, test=False): + # Return True if directory has write permissions, test opening a file with write permissions if test=True + if not test: + return os.access(dir, os.R_OK) # possible issues on Windows + file = Path(dir) / 'tmp.txt' + try: + with open(file, 'w'): # open file with write permissions + pass + file.unlink() # remove file + return True + except OSError: + return False + + +def set_logging(name=None, verbose=VERBOSE): + # Sets level and returns logger + if is_kaggle(): + for h in logging.root.handlers: + logging.root.removeHandler(h) # remove all handlers associated with the root logger object + rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings + level = logging.INFO if verbose and rank in {-1, 0} else logging.WARNING + log = logging.getLogger(name) + log.setLevel(level) + handler = logging.StreamHandler() + handler.setFormatter(logging.Formatter("%(message)s")) + handler.setLevel(level) + log.addHandler(handler) + + +set_logging() # run before defining LOGGER +LOGGER = logging.getLogger("yolov5") # define globally (used in train.py, val.py, detect.py, etc.) + + +def user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'): + # Return path of user configuration directory. Prefer environment variable if exists. Make dir if required. + env = os.getenv(env_var) + if env: + path = Path(env) # use environment variable + else: + cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'} # 3 OS dirs + path = Path.home() / cfg.get(platform.system(), '') # OS-specific config dir + path = (path if is_writeable(path) else Path('/tmp')) / dir # GCP and AWS lambda fix, only /tmp is writeable + path.mkdir(exist_ok=True) # make if required + return path + + +CONFIG_DIR = user_config_dir() # Ultralytics settings dir + + +class Profile(contextlib.ContextDecorator): + # Usage: @Profile() decorator or 'with Profile():' context manager + def __enter__(self): + self.start = time.time() + + def __exit__(self, type, value, traceback): + print(f'Profile results: {time.time() - self.start:.5f}s') + + +class Timeout(contextlib.ContextDecorator): + # Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager + def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True): + self.seconds = int(seconds) + self.timeout_message = timeout_msg + self.suppress = bool(suppress_timeout_errors) + + def _timeout_handler(self, signum, frame): + raise TimeoutError(self.timeout_message) + + def __enter__(self): + if platform.system() != 'Windows': # not supported on Windows + signal.signal(signal.SIGALRM, self._timeout_handler) # Set handler for SIGALRM + signal.alarm(self.seconds) # start countdown for SIGALRM to be raised + + def __exit__(self, exc_type, exc_val, exc_tb): + if platform.system() != 'Windows': + signal.alarm(0) # Cancel SIGALRM if it's scheduled + if self.suppress and exc_type is TimeoutError: # Suppress TimeoutError + return True + + +class WorkingDirectory(contextlib.ContextDecorator): + # Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager + def __init__(self, new_dir): + self.dir = new_dir # new dir + self.cwd = Path.cwd().resolve() # current dir + + def __enter__(self): + os.chdir(self.dir) + + def __exit__(self, exc_type, exc_val, exc_tb): + os.chdir(self.cwd) + + +def try_except(func): + # try-except function. Usage: @try_except decorator + def handler(*args, **kwargs): + try: + func(*args, **kwargs) + except Exception as e: + print(e) + + return handler + + +def threaded(func): + # Multi-threads a target function and returns thread. Usage: @threaded decorator + def wrapper(*args, **kwargs): + thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True) + thread.start() + return thread + + return wrapper + + +def methods(instance): + # Get class/instance methods + return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")] + + +def print_args(args: Optional[dict] = None, show_file=True, show_fcn=False): + # Print function arguments (optional args dict) + x = inspect.currentframe().f_back # previous frame + file, _, fcn, _, _ = inspect.getframeinfo(x) + if args is None: # get args automatically + args, _, _, frm = inspect.getargvalues(x) + args = {k: v for k, v in frm.items() if k in args} + s = (f'{Path(file).stem}: ' if show_file else '') + (f'{fcn}: ' if show_fcn else '') + LOGGER.info(colorstr(s) + ', '.join(f'{k}={v}' for k, v in args.items())) def init_seeds(seed=0): - # Initialize random number generator (RNG) seeds + # Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html + # cudnn seed 0 settings are slower and more reproducible, else faster and less reproducible + import torch.backends.cudnn as cudnn random.seed(seed) np.random.seed(seed) - init_torch_seeds(seed) + torch.manual_seed(seed) + cudnn.benchmark, cudnn.deterministic = (False, True) if seed == 0 else (True, False) + + +def intersect_dicts(da, db, exclude=()): + # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values + return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape} def get_latest_run(search_dir='.'): @@ -47,106 +216,381 @@ def get_latest_run(search_dir='.'): return max(last_list, key=os.path.getctime) if last_list else '' -def isdocker(): - # Is environment a Docker container +def is_docker(): + # Is environment a Docker container? return Path('/workspace').exists() # or Path('/.dockerenv').exists() +def is_colab(): + # Is environment a Google Colab instance? + try: + import google.colab + return True + except ImportError: + return False + + +def is_pip(): + # Is file in a pip package? + return 'site-packages' in Path(__file__).resolve().parts + + +def is_ascii(s=''): + # Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7) + s = str(s) # convert list, tuple, None, etc. to str + return len(s.encode().decode('ascii', 'ignore')) == len(s) + + +def is_chinese(s='人工智能'): + # Is string composed of any Chinese characters? + return bool(re.search('[\u4e00-\u9fff]', str(s))) + + +def emojis(str=''): + # Return platform-dependent emoji-safe version of string + return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str + + +def file_age(path=__file__): + # Return days since last file update + dt = (datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime)) # delta + return dt.days # + dt.seconds / 86400 # fractional days + + +def file_date(path=__file__): + # Return human-readable file modification date, i.e. '2021-3-26' + t = datetime.fromtimestamp(Path(path).stat().st_mtime) + return f'{t.year}-{t.month}-{t.day}' + + +def file_size(path): + # Return file/dir size (MB) + mb = 1 << 20 # bytes to MiB (1024 ** 2) + path = Path(path) + if path.is_file(): + return path.stat().st_size / mb + elif path.is_dir(): + return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / mb + else: + return 0.0 + + def check_online(): # Check internet connectivity import socket try: - socket.create_connection(("1.1.1.1", 443), 5) # check host accesability + socket.create_connection(("1.1.1.1", 443), 5) # check host accessibility return True except OSError: return False +def git_describe(path=ROOT): # path must be a directory + # Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe + try: + assert (Path(path) / '.git').is_dir() + return check_output(f'git -C {path} describe --tags --long --always', shell=True).decode()[:-1] + except Exception: + return '' + + +@try_except +@WorkingDirectory(ROOT) def check_git_status(): # Recommend 'git pull' if code is out of date - print(colorstr('github: '), end='') - try: - assert Path('.git').exists(), 'skipping check (not a git repository)' - assert not isdocker(), 'skipping check (Docker image)' - assert check_online(), 'skipping check (offline)' + msg = ', for updates see https://github.com/ultralytics/yolov5' + s = colorstr('github: ') # string + assert Path('.git').exists(), s + 'skipping check (not a git repository)' + msg + assert not is_docker(), s + 'skipping check (Docker image)' + msg + assert check_online(), s + 'skipping check (offline)' + msg - cmd = 'git fetch && git config --get remote.origin.url' - url = subprocess.check_output(cmd, shell=True).decode().strip().rstrip('.git') # github repo url - branch = subprocess.check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out - n = int(subprocess.check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind - if n > 0: - s = f"⚠️ WARNING: code is out of date by {n} commit{'s' * (n > 1)}. " \ - f"Use 'git pull' to update or 'git clone {url}' to download latest." - else: - s = f'up to date with {url} ✅' - print(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) - except Exception as e: - print(e) + cmd = 'git fetch && git config --get remote.origin.url' + url = check_output(cmd, shell=True, timeout=5).decode().strip().rstrip('.git') # git fetch + branch = check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out + n = int(check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind + if n > 0: + s += f"⚠️ YOLOv5 is out of date by {n} commit{'s' * (n > 1)}. Use `git pull` or `git clone {url}` to update." + else: + s += f'up to date with {url} ✅' + LOGGER.info(emojis(s)) # emoji-safe -def check_requirements(file='requirements.txt', exclude=()): - # Check installed dependencies meet requirements - import pkg_resources - requirements = [f'{x.name}{x.specifier}' for x in pkg_resources.parse_requirements(Path(file).open()) - if x.name not in exclude] - pkg_resources.require(requirements) # DistributionNotFound or VersionConflict exception if requirements not met +def check_python(minimum='3.7.0'): + # Check current python version vs. required python version + check_version(platform.python_version(), minimum, name='Python ', hard=True) -def check_img_size(img_size, s=32): - # Verify img_size is a multiple of stride s - new_size = make_divisible(img_size, int(s)) # ceil gs-multiple - if new_size != img_size: - print('WARNING: --img-size %g must be multiple of max stride %g, updating to %g' % (img_size, s, new_size)) +def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False): + # Check version vs. required version + current, minimum = (pkg.parse_version(x) for x in (current, minimum)) + result = (current == minimum) if pinned else (current >= minimum) # bool + s = f'{name}{minimum} required by YOLOv5, but {name}{current} is currently installed' # string + if hard: + assert result, s # assert min requirements met + if verbose and not result: + LOGGER.warning(s) + return result + + +@try_except +def check_requirements(requirements=ROOT / 'requirements.txt', exclude=(), install=True, cmds=()): + # Check installed dependencies meet requirements (pass *.txt file or list of packages) + prefix = colorstr('red', 'bold', 'requirements:') + check_python() # check python version + if isinstance(requirements, (str, Path)): # requirements.txt file + file = Path(requirements) + assert file.exists(), f"{prefix} {file.resolve()} not found, check failed." + with file.open() as f: + requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(f) if x.name not in exclude] + else: # list or tuple of packages + requirements = [x for x in requirements if x not in exclude] + + n = 0 # number of packages updates + for i, r in enumerate(requirements): + try: + pkg.require(r) + except Exception: # DistributionNotFound or VersionConflict if requirements not met + s = f"{prefix} {r} not found and is required by YOLOv5" + if install and AUTOINSTALL: # check environment variable + LOGGER.info(f"{s}, attempting auto-update...") + try: + assert check_online(), f"'pip install {r}' skipped (offline)" + LOGGER.info(check_output(f'pip install "{r}" {cmds[i] if cmds else ""}', shell=True).decode()) + n += 1 + except Exception as e: + LOGGER.warning(f'{prefix} {e}') + else: + LOGGER.info(f'{s}. Please install and rerun your command.') + + if n: # if packages updated + source = file.resolve() if 'file' in locals() else requirements + s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \ + f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n" + LOGGER.info(emojis(s)) + + +def check_img_size(imgsz, s=32, floor=0): + # Verify image size is a multiple of stride s in each dimension + if isinstance(imgsz, int): # integer i.e. img_size=640 + new_size = max(make_divisible(imgsz, int(s)), floor) + else: # list i.e. img_size=[640, 480] + imgsz = list(imgsz) # convert to list if tuple + new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz] + if new_size != imgsz: + LOGGER.warning(f'WARNING: --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}') return new_size def check_imshow(): # Check if environment supports image displays try: - assert not isdocker(), 'cv2.imshow() is disabled in Docker environments' + assert not is_docker(), 'cv2.imshow() is disabled in Docker environments' + assert not is_colab(), 'cv2.imshow() is disabled in Google Colab environments' cv2.imshow('test', np.zeros((1, 1, 3))) cv2.waitKey(1) cv2.destroyAllWindows() cv2.waitKey(1) return True except Exception as e: - print(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}') + LOGGER.warning(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}') return False -def check_file(file): - # Search for file if not found - if os.path.isfile(file) or file == '': +def check_suffix(file='yolov5s.pt', suffix=('.pt',), msg=''): + # Check file(s) for acceptable suffix + if file and suffix: + if isinstance(suffix, str): + suffix = [suffix] + for f in file if isinstance(file, (list, tuple)) else [file]: + s = Path(f).suffix.lower() # file suffix + if len(s): + assert s in suffix, f"{msg}{f} acceptable suffix is {suffix}" + + +def check_yaml(file, suffix=('.yaml', '.yml')): + # Search/download YAML file (if necessary) and return path, checking suffix + return check_file(file, suffix) + + +def check_file(file, suffix=''): + # Search/download file (if necessary) and return path + check_suffix(file, suffix) # optional + file = str(file) # convert to str() + if Path(file).is_file() or not file: # exists return file - else: - files = glob.glob('./**/' + file, recursive=True) # find file - assert len(files), 'File Not Found: %s' % file # assert file was found - assert len(files) == 1, "Multiple files match '%s', specify exact path: %s" % (file, files) # assert unique + elif file.startswith(('http:/', 'https:/')): # download + url = file # warning: Pathlib turns :// -> :/ + file = Path(urllib.parse.unquote(file).split('?')[0]).name # '%2F' to '/', split https://url.com/file.txt?auth + if Path(file).is_file(): + LOGGER.info(f'Found {url} locally at {file}') # file already exists + else: + LOGGER.info(f'Downloading {url} to {file}...') + torch.hub.download_url_to_file(url, file) + assert Path(file).exists() and Path(file).stat().st_size > 0, f'File download failed: {url}' # check + return file + else: # search + files = [] + for d in 'data', 'models', 'utils': # search directories + files.extend(glob.glob(str(ROOT / d / '**' / file), recursive=True)) # find file + assert len(files), f'File not found: {file}' # assert file was found + assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique return files[0] # return file -def check_dataset(dict): - # Download dataset if not found locally - val, s = dict.get('val'), dict.get('download') - if val and len(val): +def check_font(font=FONT, progress=False): + # Download font to CONFIG_DIR if necessary + font = Path(font) + file = CONFIG_DIR / font.name + if not font.exists() and not file.exists(): + url = "https://ultralytics.com/assets/" + font.name + LOGGER.info(f'Downloading {url} to {file}...') + torch.hub.download_url_to_file(url, str(file), progress=progress) + + +def check_dataset(data, autodownload=True): + # Download, check and/or unzip dataset if not found locally + + # Download (optional) + extract_dir = '' + if isinstance(data, (str, Path)) and str(data).endswith('.zip'): # i.e. gs://bucket/dir/coco128.zip + download(data, dir=DATASETS_DIR, unzip=True, delete=False, curl=False, threads=1) + data = next((DATASETS_DIR / Path(data).stem).rglob('*.yaml')) + extract_dir, autodownload = data.parent, False + + # Read yaml (optional) + if isinstance(data, (str, Path)): + with open(data, errors='ignore') as f: + data = yaml.safe_load(f) # dictionary + + # Checks + for k in 'train', 'val', 'nc': + assert k in data, emojis(f"data.yaml '{k}:' field missing ❌") + if 'names' not in data: + LOGGER.warning(emojis("data.yaml 'names:' field missing ⚠, assigning default names 'class0', 'class1', etc.")) + data['names'] = [f'class{i}' for i in range(data['nc'])] # default names + + # Resolve paths + path = Path(extract_dir or data.get('path') or '') # optional 'path' default to '.' + if not path.is_absolute(): + path = (ROOT / path).resolve() + for k in 'train', 'val', 'test': + if data.get(k): # prepend path + data[k] = str(path / data[k]) if isinstance(data[k], str) else [str(path / x) for x in data[k]] + + # Parse yaml + train, val, test, s = (data.get(x) for x in ('train', 'val', 'test', 'download')) + if val: val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path if not all(x.exists() for x in val): - print('\nWARNING: Dataset not found, nonexistent paths: %s' % [str(x) for x in val if not x.exists()]) - if s and len(s): # download script - print('Downloading %s ...' % s) - if s.startswith('http') and s.endswith('.zip'): # URL - f = Path(s).name # filename - torch.hub.download_url_to_file(s, f) - r = os.system('unzip -q %s -d ../ && rm %s' % (f, f)) # unzip - else: # bash script - r = os.system(s) - print('Dataset autodownload %s\n' % ('success' if r == 0 else 'failure')) # analyze return value - else: - raise Exception('Dataset not found.') + LOGGER.info(emojis('\nDataset not found ⚠, missing paths %s' % [str(x) for x in val if not x.exists()])) + if not s or not autodownload: + raise Exception(emojis('Dataset not found ❌')) + t = time.time() + root = path.parent if 'path' in data else '..' # unzip directory i.e. '../' + if s.startswith('http') and s.endswith('.zip'): # URL + f = Path(s).name # filename + LOGGER.info(f'Downloading {s} to {f}...') + torch.hub.download_url_to_file(s, f) + Path(root).mkdir(parents=True, exist_ok=True) # create root + ZipFile(f).extractall(path=root) # unzip + Path(f).unlink() # remove zip + r = None # success + elif s.startswith('bash '): # bash script + LOGGER.info(f'Running {s} ...') + r = os.system(s) + else: # python script + r = exec(s, {'yaml': data}) # return None + dt = f'({round(time.time() - t, 1)}s)' + s = f"success ✅ {dt}, saved to {colorstr('bold', root)}" if r in (0, None) else f"failure {dt} ❌" + LOGGER.info(emojis(f"Dataset download {s}")) + check_font('Arial.ttf' if is_ascii(data['names']) else 'Arial.Unicode.ttf', progress=True) # download fonts + return data # dictionary + + +def check_amp(model): + # Check PyTorch Automatic Mixed Precision (AMP) functionality. Return True on correct operation + from models.common import AutoShape, DetectMultiBackend + + def amp_allclose(model, im): + # All close FP32 vs AMP results + m = AutoShape(model, verbose=False) # model + a = m(im).xywhn[0] # FP32 inference + m.amp = True + b = m(im).xywhn[0] # AMP inference + return a.shape == b.shape and torch.allclose(a, b, atol=0.1) # close to 10% absolute tolerance + + prefix = colorstr('AMP: ') + device = next(model.parameters()).device # get model device + if device.type == 'cpu': + return False # AMP disabled on CPU + f = ROOT / 'data' / 'images' / 'bus.jpg' # image to check + im = f if f.exists() else 'https://ultralytics.com/images/bus.jpg' if check_online() else np.ones((640, 640, 3)) + try: + assert amp_allclose(model, im) or amp_allclose(DetectMultiBackend('yolov5n.pt', device), im) + LOGGER.info(emojis(f'{prefix}checks passed ✅')) + return True + except Exception: + help_url = 'https://github.com/ultralytics/yolov5/issues/7908' + LOGGER.warning(emojis(f'{prefix}checks failed ❌, disabling Automatic Mixed Precision. See {help_url}')) + return False + + +def url2file(url): + # Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt + url = str(Path(url)).replace(':/', '://') # Pathlib turns :// -> :/ + return Path(urllib.parse.unquote(url)).name.split('?')[0] # '%2F' to '/', split https://url.com/file.txt?auth + + +def download(url, dir='.', unzip=True, delete=True, curl=False, threads=1, retry=3): + # Multi-threaded file download and unzip function, used in data.yaml for autodownload + def download_one(url, dir): + # Download 1 file + success = True + f = dir / Path(url).name # filename + if Path(url).is_file(): # exists in current path + Path(url).rename(f) # move to dir + elif not f.exists(): + LOGGER.info(f'Downloading {url} to {f}...') + for i in range(retry + 1): + if curl: + s = 'sS' if threads > 1 else '' # silent + r = os.system(f'curl -{s}L "{url}" -o "{f}" --retry 9 -C -') # curl download with retry, continue + success = r == 0 + else: + torch.hub.download_url_to_file(url, f, progress=threads == 1) # torch download + success = f.is_file() + if success: + break + elif i < retry: + LOGGER.warning(f'Download failure, retrying {i + 1}/{retry} {url}...') + else: + LOGGER.warning(f'Failed to download {url}...') + + if unzip and success and f.suffix in ('.zip', '.gz'): + LOGGER.info(f'Unzipping {f}...') + if f.suffix == '.zip': + ZipFile(f).extractall(path=dir) # unzip + elif f.suffix == '.gz': + os.system(f'tar xfz {f} --directory {f.parent}') # unzip + if delete: + f.unlink() # remove zip + + dir = Path(dir) + dir.mkdir(parents=True, exist_ok=True) # make directory + if threads > 1: + pool = ThreadPool(threads) + pool.imap(lambda x: download_one(*x), zip(url, repeat(dir))) # multi-threaded + pool.close() + pool.join() + else: + for u in [url] if isinstance(url, (str, Path)) else url: + download_one(u, dir) def make_divisible(x, divisor): - # Returns x evenly divisible by divisor + # Returns nearest x divisible by divisor + if isinstance(divisor, torch.Tensor): + divisor = int(divisor.max()) # to int return math.ceil(x / divisor) * divisor @@ -156,32 +600,33 @@ def clean_str(s): def one_cycle(y1=0.0, y2=1.0, steps=100): - # lambda function for sinusoidal ramp from y1 to y2 + # lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1 def colorstr(*input): # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world') *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string - colors = {'black': '\033[30m', # basic colors - 'red': '\033[31m', - 'green': '\033[32m', - 'yellow': '\033[33m', - 'blue': '\033[34m', - 'magenta': '\033[35m', - 'cyan': '\033[36m', - 'white': '\033[37m', - 'bright_black': '\033[90m', # bright colors - 'bright_red': '\033[91m', - 'bright_green': '\033[92m', - 'bright_yellow': '\033[93m', - 'bright_blue': '\033[94m', - 'bright_magenta': '\033[95m', - 'bright_cyan': '\033[96m', - 'bright_white': '\033[97m', - 'end': '\033[0m', # misc - 'bold': '\033[1m', - 'underline': '\033[4m'} + colors = { + 'black': '\033[30m', # basic colors + 'red': '\033[31m', + 'green': '\033[32m', + 'yellow': '\033[33m', + 'blue': '\033[34m', + 'magenta': '\033[35m', + 'cyan': '\033[36m', + 'white': '\033[37m', + 'bright_black': '\033[90m', # bright colors + 'bright_red': '\033[91m', + 'bright_green': '\033[92m', + 'bright_yellow': '\033[93m', + 'bright_blue': '\033[94m', + 'bright_magenta': '\033[95m', + 'bright_cyan': '\033[96m', + 'bright_white': '\033[97m', + 'end': '\033[0m', # misc + 'bold': '\033[1m', + 'underline': '\033[4m'} return ''.join(colors[x] for x in args) + f'{string}' + colors['end'] @@ -206,10 +651,9 @@ def labels_to_class_weights(labels, nc=80): def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)): # Produces image weights based on class_weights and image contents + # Usage: index = random.choices(range(n), weights=image_weights, k=1) # weighted image sample class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels]) - image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1) - # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample - return image_weights + return (class_weights.reshape(1, nc) * class_counts).sum(1) def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper) @@ -218,10 +662,10 @@ def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper) # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n') # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet - x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, - 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90] - return x + return [ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, + 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90] def xyxy2xywh(x): @@ -254,6 +698,18 @@ def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0): return y +def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0): + # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right + if clip: + clip_coords(x, (h - eps, w - eps)) # warning: inplace clip + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = ((x[:, 0] + x[:, 2]) / 2) / w # x center + y[:, 1] = ((x[:, 1] + x[:, 3]) / 2) / h # y center + y[:, 2] = (x[:, 2] - x[:, 0]) / w # width + y[:, 3] = (x[:, 3] - x[:, 1]) / h # height + return y + + def xyn2xy(x, w=640, h=640, padw=0, padh=0): # Convert normalized segments into pixel segments, shape (n,2) y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) @@ -267,7 +723,7 @@ def segment2box(segment, width=640, height=640): x, y = segment.T # segment xy inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height) x, y, = x[inside], y[inside] - return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # cls, xyxy + return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy def segments2boxes(segments): @@ -282,6 +738,7 @@ def segments2boxes(segments): def resample_segments(segments, n=1000): # Up-sample an (n,2) segment for i, s in enumerate(segments): + s = np.concatenate((s, s[0:1, :]), axis=0) x = np.linspace(0, len(s) - 1, n) xp = np.arange(len(s)) segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy @@ -304,114 +761,51 @@ def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None): return coords -def clip_coords(boxes, img_shape): +def clip_coords(boxes, shape): # Clip bounding xyxy bounding boxes to image shape (height, width) - boxes[:, 0].clamp_(0, img_shape[1]) # x1 - boxes[:, 1].clamp_(0, img_shape[0]) # y1 - boxes[:, 2].clamp_(0, img_shape[1]) # x2 - boxes[:, 3].clamp_(0, img_shape[0]) # y2 + if isinstance(boxes, torch.Tensor): # faster individually + boxes[:, 0].clamp_(0, shape[1]) # x1 + boxes[:, 1].clamp_(0, shape[0]) # y1 + boxes[:, 2].clamp_(0, shape[1]) # x2 + boxes[:, 3].clamp_(0, shape[0]) # y2 + else: # np.array (faster grouped) + boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2 + boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2 -def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7): - # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4 - box2 = box2.T - - # Get the coordinates of bounding boxes - if x1y1x2y2: # x1, y1, x2, y2 = box1 - b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] - b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] - else: # transform from xywh to xyxy - b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2 - b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2 - b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2 - b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2 - - # Intersection area - inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ - (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) - - # Union Area - w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps - w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps - union = w1 * h1 + w2 * h2 - inter + eps - - iou = inter / union - if GIoU or DIoU or CIoU: - cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width - ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height - if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 - c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared - rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + - (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared - if DIoU: - return iou - rho2 / c2 # DIoU - elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 - v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2) - with torch.no_grad(): - alpha = v / (v - iou + (1 + eps)) - return iou - (rho2 / c2 + v * alpha) # CIoU - else: # GIoU https://arxiv.org/pdf/1902.09630.pdf - c_area = cw * ch + eps # convex area - return iou - (c_area - union) / c_area # GIoU - else: - return iou # IoU - - -def box_iou(box1, box2): - # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py - """ - Return intersection-over-union (Jaccard index) of boxes. - Both sets of boxes are expected to be in (x1, y1, x2, y2) format. - Arguments: - box1 (Tensor[N, 4]) - box2 (Tensor[M, 4]) - Returns: - iou (Tensor[N, M]): the NxM matrix containing the pairwise - IoU values for every element in boxes1 and boxes2 - """ - - def box_area(box): - # box = 4xn - return (box[2] - box[0]) * (box[3] - box[1]) - - area1 = box_area(box1.T) - area2 = box_area(box2.T) - - # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) - inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) - return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter) - - -def wh_iou(wh1, wh2): - # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2 - wh1 = wh1[:, None] # [N,1,2] - wh2 = wh2[None] # [1,M,2] - inter = torch.min(wh1, wh2).prod(2) # [N,M] - return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter) - - -def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False, - labels=()): - """Runs Non-Maximum Suppression (NMS) on inference results +def non_max_suppression(prediction, + conf_thres=0.25, + iou_thres=0.45, + classes=None, + agnostic=False, + multi_label=False, + labels=(), + max_det=300): + """Non-Maximum Suppression (NMS) on inference results to reject overlapping bounding boxes Returns: list of detections, on (n,6) tensor per image [xyxy, conf, cls] """ + bs = prediction.shape[0] # batch size nc = prediction.shape[2] - 5 # number of classes xc = prediction[..., 4] > conf_thres # candidates + # Checks + assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0' + assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0' + # Settings - min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height - max_det = 300 # maximum number of detections per image + # min_wh = 2 # (pixels) minimum box width and height + max_wh = 7680 # (pixels) maximum box width and height max_nms = 30000 # maximum number of boxes into torchvision.ops.nms() - time_limit = 10.0 # seconds to quit after + time_limit = 0.3 + 0.03 * bs # seconds to quit after redundant = True # require redundant detections multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img) merge = False # use merge-NMS t = time.time() - output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0] + output = [torch.zeros((0, 6), device=prediction.device)] * bs for xi, x in enumerate(prediction): # image index, image inference # Apply constraints # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height @@ -419,11 +813,11 @@ def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=Non # Cat apriori labels if autolabelling if labels and len(labels[xi]): - l = labels[xi] - v = torch.zeros((len(l), nc + 5), device=x.device) - v[:, :4] = l[:, 1:5] # box + lb = labels[xi] + v = torch.zeros((len(lb), nc + 5), device=x.device) + v[:, :4] = lb[:, 1:5] # box v[:, 4] = 1.0 # conf - v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls + v[range(len(lb)), lb[:, 0].long() + 5] = 1.0 # cls x = torch.cat((x, v), 0) # If none remain process next image @@ -475,7 +869,7 @@ def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=Non output[xi] = x[i] if (time.time() - t) > time_limit: - print(f'WARNING: NMS time limit {time_limit}s exceeded') + LOGGER.warning(f'WARNING: NMS time limit {time_limit:.3f}s exceeded') break # time limit exceeded return output @@ -486,7 +880,7 @@ def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_op x = torch.load(f, map_location=torch.device('cpu')) if x.get('ema'): x['model'] = x['ema'] # replace model with ema - for k in 'optimizer', 'training_results', 'wandb_id', 'ema', 'updates': # keys + for k in 'optimizer', 'best_fitness', 'wandb_id', 'ema', 'updates': # keys x[k] = None x['epoch'] = -1 x['model'].half() # to FP16 @@ -494,42 +888,52 @@ def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_op p.requires_grad = False torch.save(x, s or f) mb = os.path.getsize(s or f) / 1E6 # filesize - print(f"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB") + LOGGER.info(f"Optimizer stripped from {f},{f' saved as {s},' if s else ''} {mb:.1f}MB") -def print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''): - # Print mutation results to evolve.txt (for use with train.py --evolve) - a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys - b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values - c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3) - print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c)) +def print_mutation(results, hyp, save_dir, bucket, prefix=colorstr('evolve: ')): + evolve_csv = save_dir / 'evolve.csv' + evolve_yaml = save_dir / 'hyp_evolve.yaml' + keys = ('metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', 'val/box_loss', + 'val/obj_loss', 'val/cls_loss') + tuple(hyp.keys()) # [results + hyps] + keys = tuple(x.strip() for x in keys) + vals = results + tuple(hyp.values()) + n = len(keys) + # Download (optional) if bucket: - url = 'gs://%s/evolve.txt' % bucket - if gsutil_getsize(url) > (os.path.getsize('evolve.txt') if os.path.exists('evolve.txt') else 0): - os.system('gsutil cp %s .' % url) # download evolve.txt if larger than local + url = f'gs://{bucket}/evolve.csv' + if gsutil_getsize(url) > (evolve_csv.stat().st_size if evolve_csv.exists() else 0): + os.system(f'gsutil cp {url} {save_dir}') # download evolve.csv if larger than local - with open('evolve.txt', 'a') as f: # append result - f.write(c + b + '\n') - x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows - x = x[np.argsort(-fitness(x))] # sort - np.savetxt('evolve.txt', x, '%10.3g') # save sort by fitness + # Log to evolve.csv + s = '' if evolve_csv.exists() else (('%20s,' * n % keys).rstrip(',') + '\n') # add header + with open(evolve_csv, 'a') as f: + f.write(s + ('%20.5g,' * n % vals).rstrip(',') + '\n') # Save yaml - for i, k in enumerate(hyp.keys()): - hyp[k] = float(x[0, i + 7]) - with open(yaml_file, 'w') as f: - results = tuple(x[0, :7]) - c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3) - f.write('# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: ' % len(x) + c + '\n\n') - yaml.dump(hyp, f, sort_keys=False) + with open(evolve_yaml, 'w') as f: + data = pd.read_csv(evolve_csv) + data = data.rename(columns=lambda x: x.strip()) # strip keys + i = np.argmax(fitness(data.values[:, :4])) # + generations = len(data) + f.write('# YOLOv5 Hyperparameter Evolution Results\n' + f'# Best generation: {i}\n' + + f'# Last generation: {generations - 1}\n' + '# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) + + '\n' + '# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n') + yaml.safe_dump(data.loc[i][7:].to_dict(), f, sort_keys=False) + + # Print to screen + LOGGER.info(prefix + f'{generations} generations finished, current result:\n' + prefix + + ', '.join(f'{x.strip():>20s}' for x in keys) + '\n' + prefix + ', '.join(f'{x:20.5g}' + for x in vals) + '\n\n') if bucket: - os.system('gsutil cp evolve.txt %s gs://%s' % (yaml_file, bucket)) # upload + os.system(f'gsutil cp {evolve_csv} {evolve_yaml} gs://{bucket}') # upload def apply_classifier(x, model, img, im0): - # applies a second stage classifier to yolo outputs + # Apply a second stage classifier to YOLO outputs + # Example model = torchvision.models.__dict__['efficientnet_b0'](pretrained=True).to(device).eval() im0 = [im0] if isinstance(im0, np.ndarray) else im0 for i, d in enumerate(x): # per image if d is not None and len(d): @@ -547,14 +951,13 @@ def apply_classifier(x, model, img, im0): # Classes pred_cls1 = d[:, 5].long() ims = [] - for j, a in enumerate(d): # per item + for a in d: cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])] im = cv2.resize(cutout, (224, 224)) # BGR - # cv2.imwrite('test%i.jpg' % j, cutout) im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32 - im /= 255.0 # 0 - 255 to 0.0 - 1.0 + im /= 255 # 0 - 255 to 0.0 - 1.0 ims.append(im) pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction @@ -563,14 +966,53 @@ def apply_classifier(x, model, img, im0): return x -def increment_path(path, exist_ok=True, sep=''): - # Increment path, i.e. runs/exp --> runs/exp{sep}0, runs/exp{sep}1 etc. +def increment_path(path, exist_ok=False, sep='', mkdir=False): + # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc. path = Path(path) # os-agnostic - if (path.exists() and exist_ok) or (not path.exists()): - return str(path) - else: - dirs = glob.glob(f"{path}{sep}*") # similar paths - matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs] - i = [int(m.groups()[0]) for m in matches if m] # indices - n = max(i) + 1 if i else 2 # increment number - return f"{path}{sep}{n}" # update path + if path.exists() and not exist_ok: + path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '') + + # Method 1 + for n in range(2, 9999): + p = f'{path}{sep}{n}{suffix}' # increment path + if not os.path.exists(p): # + break + path = Path(p) + + # Method 2 (deprecated) + # dirs = glob.glob(f"{path}{sep}*") # similar paths + # matches = [re.search(rf"{path.stem}{sep}(\d+)", d) for d in dirs] + # i = [int(m.groups()[0]) for m in matches if m] # indices + # n = max(i) + 1 if i else 2 # increment number + # path = Path(f"{path}{sep}{n}{suffix}") # increment path + + if mkdir: + path.mkdir(parents=True, exist_ok=True) # make directory + + return path + + +# OpenCV Chinese-friendly functions ------------------------------------------------------------------------------------ +imshow_ = cv2.imshow # copy to avoid recursion errors + + +def imread(path, flags=cv2.IMREAD_COLOR): + return cv2.imdecode(np.fromfile(path, np.uint8), flags) + + +def imwrite(path, im): + try: + cv2.imencode(Path(path).suffix, im)[1].tofile(path) + return True + except Exception: + return False + + +def imshow(path, im): + imshow_(path.encode('unicode_escape').decode(), im) + + +cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow # redefine + +# Variables ------------------------------------------------------------------------------------------------------------ +NCOLS = 0 if is_docker() else shutil.get_terminal_size().columns # terminal window size for tqdm diff --git a/Y5/utils/google_app_engine/additional_requirements.txt b/Y5/utils/google_app_engine/additional_requirements.txt index 5fcc305..42d7ffc 100755 --- a/Y5/utils/google_app_engine/additional_requirements.txt +++ b/Y5/utils/google_app_engine/additional_requirements.txt @@ -1,4 +1,4 @@ # add these requirements in your app on top of the existing ones -pip==18.1 +pip==21.1 Flask==1.0.2 gunicorn==19.9.0 diff --git a/Y5/utils/google_app_engine/app.yaml b/Y5/utils/google_app_engine/app.yaml index ac29d10..5056b7c 100755 --- a/Y5/utils/google_app_engine/app.yaml +++ b/Y5/utils/google_app_engine/app.yaml @@ -11,4 +11,4 @@ manual_scaling: resources: cpu: 1 memory_gb: 4 - disk_size_gb: 20 \ No newline at end of file + disk_size_gb: 20 diff --git a/Y5/utils/loggers/__init__.py b/Y5/utils/loggers/__init__.py new file mode 100755 index 0000000..42b696b --- /dev/null +++ b/Y5/utils/loggers/__init__.py @@ -0,0 +1,187 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Logging utils +""" + +import os +import warnings + +import pkg_resources as pkg +import torch +from torch.utils.tensorboard import SummaryWriter + +from utils.general import colorstr, cv2, emojis +from utils.loggers.wandb.wandb_utils import WandbLogger +from utils.plots import plot_images, plot_results +from utils.torch_utils import de_parallel + +LOGGERS = ('csv', 'tb', 'wandb') # text-file, TensorBoard, Weights & Biases +RANK = int(os.getenv('RANK', -1)) + +try: + import wandb + + assert hasattr(wandb, '__version__') # verify package import not local dir + if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.2') and RANK in {0, -1}: + try: + wandb_login_success = wandb.login(timeout=30) + except wandb.errors.UsageError: # known non-TTY terminal issue + wandb_login_success = False + if not wandb_login_success: + wandb = None +except (ImportError, AssertionError): + wandb = None + + +class Loggers(): + # YOLOv5 Loggers class + def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS): + self.save_dir = save_dir + self.weights = weights + self.opt = opt + self.hyp = hyp + self.logger = logger # for printing results to console + self.include = include + self.keys = [ + 'train/box_loss', + 'train/obj_loss', + 'train/cls_loss', # train loss + 'metrics/precision', + 'metrics/recall', + 'metrics/mAP_0.5', + 'metrics/mAP_0.5:0.95', # metrics + 'val/box_loss', + 'val/obj_loss', + 'val/cls_loss', # val loss + 'x/lr0', + 'x/lr1', + 'x/lr2'] # params + self.best_keys = ['best/epoch', 'best/precision', 'best/recall', 'best/mAP_0.5', 'best/mAP_0.5:0.95'] + for k in LOGGERS: + setattr(self, k, None) # init empty logger dictionary + self.csv = True # always log to csv + + # Message + if not wandb: + prefix = colorstr('Weights & Biases: ') + s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)" + self.logger.info(emojis(s)) + + # TensorBoard + s = self.save_dir + if 'tb' in self.include and not self.opt.evolve: + prefix = colorstr('TensorBoard: ') + self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/") + self.tb = SummaryWriter(str(s)) + + # W&B + if wandb and 'wandb' in self.include: + wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://') + run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None + self.opt.hyp = self.hyp # add hyperparameters + self.wandb = WandbLogger(self.opt, run_id) + # temp warn. because nested artifacts not supported after 0.12.10 + if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.11'): + self.logger.warning( + "YOLOv5 temporarily requires wandb version 0.12.10 or below. Some features may not work as expected." + ) + else: + self.wandb = None + + def on_train_start(self): + # Callback runs on train start + pass + + def on_pretrain_routine_end(self): + # Callback runs on pre-train routine end + paths = self.save_dir.glob('*labels*.jpg') # training labels + if self.wandb: + self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]}) + + def on_train_batch_end(self, ni, model, imgs, targets, paths, plots): + # Callback runs on train batch end + if plots: + if ni == 0: + if not self.opt.sync_bn: # --sync known issue https://github.com/ultralytics/yolov5/issues/3754 + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress jit trace warning + self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), []) + if ni < 3: + f = self.save_dir / f'train_batch{ni}.jpg' # filename + plot_images(imgs, targets, paths, f) + if self.wandb and ni == 10: + files = sorted(self.save_dir.glob('train*.jpg')) + self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]}) + + def on_train_epoch_end(self, epoch): + # Callback runs on train epoch end + if self.wandb: + self.wandb.current_epoch = epoch + 1 + + def on_val_image_end(self, pred, predn, path, names, im): + # Callback runs on val image end + if self.wandb: + self.wandb.val_one_image(pred, predn, path, names, im) + + def on_val_end(self): + # Callback runs on val end + if self.wandb: + files = sorted(self.save_dir.glob('val*.jpg')) + self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]}) + + def on_fit_epoch_end(self, vals, epoch, best_fitness, fi): + # Callback runs at the end of each fit (train+val) epoch + x = dict(zip(self.keys, vals)) + if self.csv: + file = self.save_dir / 'results.csv' + n = len(x) + 1 # number of cols + s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n') # add header + with open(file, 'a') as f: + f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n') + + if self.tb: + for k, v in x.items(): + self.tb.add_scalar(k, v, epoch) + + if self.wandb: + if best_fitness == fi: + best_results = [epoch] + vals[3:7] + for i, name in enumerate(self.best_keys): + self.wandb.wandb_run.summary[name] = best_results[i] # log best results in the summary + self.wandb.log(x) + self.wandb.end_epoch(best_result=best_fitness == fi) + + def on_model_save(self, last, epoch, final_epoch, best_fitness, fi): + # Callback runs on model save event + if self.wandb: + if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1: + self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi) + + def on_train_end(self, last, best, plots, epoch, results): + # Callback runs on training end + if plots: + plot_results(file=self.save_dir / 'results.csv') # save results.png + files = ['results.png', 'confusion_matrix.png', *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))] + files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter + self.logger.info(f"Results saved to {colorstr('bold', self.save_dir)}") + + if self.tb: + for f in files: + self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC') + + if self.wandb: + self.wandb.log(dict(zip(self.keys[3:10], results))) + self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]}) + # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model + if not self.opt.evolve: + wandb.log_artifact(str(best if best.exists() else last), + type='model', + name=f'run_{self.wandb.wandb_run.id}_model', + aliases=['latest', 'best', 'stripped']) + self.wandb.finish_run() + + def on_params_update(self, params): + # Update hyperparams or configs of the experiment + # params: A dict containing {param: value} pairs + if self.wandb: + self.wandb.wandb_run.config.update(params, allow_val_change=True) diff --git a/Y5/utils/loggers/__pycache__/__init__.cpython-37.pyc b/Y5/utils/loggers/__pycache__/__init__.cpython-37.pyc new file mode 100755 index 0000000..e4da763 Binary files /dev/null and b/Y5/utils/loggers/__pycache__/__init__.cpython-37.pyc differ diff --git a/Y5/utils/loggers/__pycache__/__init__.cpython-38.pyc b/Y5/utils/loggers/__pycache__/__init__.cpython-38.pyc new file mode 100755 index 0000000..11501e5 Binary files /dev/null and b/Y5/utils/loggers/__pycache__/__init__.cpython-38.pyc differ diff --git a/Y5/utils/loggers/wandb/README.md b/Y5/utils/loggers/wandb/README.md new file mode 100755 index 0000000..d78324b --- /dev/null +++ b/Y5/utils/loggers/wandb/README.md @@ -0,0 +1,162 @@ +📚 This guide explains how to use **Weights & Biases** (W&B) with YOLOv5 🚀. UPDATED 29 September 2021. + +- [About Weights & Biases](#about-weights-&-biases) +- [First-Time Setup](#first-time-setup) +- [Viewing runs](#viewing-runs) +- [Disabling wandb](#disabling-wandb) +- [Advanced Usage: Dataset Versioning and Evaluation](#advanced-usage) +- [Reports: Share your work with the world!](#reports) + +## About Weights & Biases + +Think of [W&B](https://wandb.ai/site?utm_campaign=repo_yolo_wandbtutorial) like GitHub for machine learning models. With a few lines of code, save everything you need to debug, compare and reproduce your models — architecture, hyperparameters, git commits, model weights, GPU usage, and even datasets and predictions. + +Used by top researchers including teams at OpenAI, Lyft, Github, and MILA, W&B is part of the new standard of best practices for machine learning. How W&B can help you optimize your machine learning workflows: + +- [Debug](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Free-2) model performance in real time +- [GPU usage](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#System-4) visualized automatically +- [Custom charts](https://wandb.ai/wandb/customizable-charts/reports/Powerful-Custom-Charts-To-Debug-Model-Peformance--VmlldzoyNzY4ODI) for powerful, extensible visualization +- [Share insights](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Share-8) interactively with collaborators +- [Optimize hyperparameters](https://docs.wandb.com/sweeps) efficiently +- [Track](https://docs.wandb.com/artifacts) datasets, pipelines, and production models + +## First-Time Setup + +
+ Toggle Details +When you first train, W&B will prompt you to create a new account and will generate an **API key** for you. If you are an existing user you can retrieve your key from https://wandb.ai/authorize. This key is used to tell W&B where to log your data. You only need to supply your key once, and then it is remembered on the same device. + +W&B will create a cloud **project** (default is 'YOLOv5') for your training runs, and each new training run will be provided a unique run **name** within that project as project/name. You can also manually set your project and run name as: + +```shell +$ python train.py --project ... --name ... +``` + +YOLOv5 notebook example: Open In Colab Open In Kaggle +Screen Shot 2021-09-29 at 10 23 13 PM + +
+ +## Viewing Runs + +
+ Toggle Details +Run information streams from your environment to the W&B cloud console as you train. This allows you to monitor and even cancel runs in realtime . All important information is logged: + +- Training & Validation losses +- Metrics: Precision, Recall, mAP@0.5, mAP@0.5:0.95 +- Learning Rate over time +- A bounding box debugging panel, showing the training progress over time +- GPU: Type, **GPU Utilization**, power, temperature, **CUDA memory usage** +- System: Disk I/0, CPU utilization, RAM memory usage +- Your trained model as W&B Artifact +- Environment: OS and Python types, Git repository and state, **training command** + +

Weights & Biases dashboard

+
+ +## Disabling wandb + +- training after running `wandb disabled` inside that directory creates no wandb run + ![Screenshot (84)](https://user-images.githubusercontent.com/15766192/143441777-c780bdd7-7cb4-4404-9559-b4316030a985.png) + +- To enable wandb again, run `wandb online` + ![Screenshot (85)](https://user-images.githubusercontent.com/15766192/143441866-7191b2cb-22f0-4e0f-ae64-2dc47dc13078.png) + +## Advanced Usage + +You can leverage W&B artifacts and Tables integration to easily visualize and manage your datasets, models and training evaluations. Here are some quick examples to get you started. + +
+

1: Train and Log Evaluation simultaneousy

+ This is an extension of the previous section, but it'll also training after uploading the dataset. This also evaluation Table + Evaluation table compares your predictions and ground truths across the validation set for each epoch. It uses the references to the already uploaded datasets, + so no images will be uploaded from your system more than once. +
+ Usage + Code $ python train.py --upload_data val + +![Screenshot from 2021-11-21 17-40-06](https://user-images.githubusercontent.com/15766192/142761183-c1696d8c-3f38-45ab-991a-bb0dfd98ae7d.png) + +
+ +

2. Visualize and Version Datasets

+ Log, visualize, dynamically query, and understand your data with W&B Tables. You can use the following command to log your dataset as a W&B Table. This will generate a {dataset}_wandb.yaml file which can be used to train from dataset artifact. +
+ Usage + Code $ python utils/logger/wandb/log_dataset.py --project ... --name ... --data .. + +![Screenshot (64)](https://user-images.githubusercontent.com/15766192/128486078-d8433890-98a3-4d12-8986-b6c0e3fc64b9.png) + +
+ +

3: Train using dataset artifact

+ When you upload a dataset as described in the first section, you get a new config file with an added `_wandb` to its name. This file contains the information that + can be used to train a model directly from the dataset artifact. This also logs evaluation +
+ Usage + Code $ python train.py --data {data}_wandb.yaml + +![Screenshot (72)](https://user-images.githubusercontent.com/15766192/128979739-4cf63aeb-a76f-483f-8861-1c0100b938a5.png) + +
+ +

4: Save model checkpoints as artifacts

+ To enable saving and versioning checkpoints of your experiment, pass `--save_period n` with the base cammand, where `n` represents checkpoint interval. + You can also log both the dataset and model checkpoints simultaneously. If not passed, only the final model will be logged + +
+ Usage + Code $ python train.py --save_period 1 + +![Screenshot (68)](https://user-images.githubusercontent.com/15766192/128726138-ec6c1f60-639d-437d-b4ee-3acd9de47ef3.png) + +
+ +
+ +

5: Resume runs from checkpoint artifacts.

+Any run can be resumed using artifacts if the --resume argument starts with wandb-artifact:// prefix followed by the run path, i.e, wandb-artifact://username/project/runid . This doesn't require the model checkpoint to be present on the local system. + +
+ Usage + Code $ python train.py --resume wandb-artifact://{run_path} + +![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png) + +
+ +

6: Resume runs from dataset artifact & checkpoint artifacts.

+ Local dataset or model checkpoints are not required. This can be used to resume runs directly on a different device + The syntax is same as the previous section, but you'll need to lof both the dataset and model checkpoints as artifacts, i.e, set bot --upload_dataset or + train from _wandb.yaml file and set --save_period + +
+ Usage + Code $ python train.py --resume wandb-artifact://{run_path} + +![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png) + +
+ + + +

Reports

+W&B Reports can be created from your saved runs for sharing online. Once a report is created you will receive a link you can use to publically share your results. Here is an example report created from the COCO128 tutorial trainings of all four YOLOv5 models ([link](https://wandb.ai/glenn-jocher/yolov5_tutorial/reports/YOLOv5-COCO128-Tutorial-Results--VmlldzozMDI5OTY)). + +Weights & Biases Reports + +## Environments + +YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled): + +- **Google Colab and Kaggle** notebooks with free GPU: Open In Colab Open In Kaggle +- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) +- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart) +- **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) Docker Pulls + +## Status + +![CI CPU testing](https://github.com/ultralytics/yolov5/workflows/CI%20CPU%20testing/badge.svg) + +If this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), validation ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on macOS, Windows, and Ubuntu every 24 hours and on every commit. diff --git a/Y5/utils/loggers/wandb/__init__.py b/Y5/utils/loggers/wandb/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/Y5/utils/loggers/wandb/__pycache__/__init__.cpython-37.pyc b/Y5/utils/loggers/wandb/__pycache__/__init__.cpython-37.pyc new file mode 100755 index 0000000..6455f79 Binary files /dev/null and b/Y5/utils/loggers/wandb/__pycache__/__init__.cpython-37.pyc differ diff --git a/Y5/utils/loggers/wandb/__pycache__/__init__.cpython-38.pyc b/Y5/utils/loggers/wandb/__pycache__/__init__.cpython-38.pyc new file mode 100755 index 0000000..30760d4 Binary files /dev/null and b/Y5/utils/loggers/wandb/__pycache__/__init__.cpython-38.pyc differ diff --git a/Y5/utils/loggers/wandb/__pycache__/wandb_utils.cpython-37.pyc b/Y5/utils/loggers/wandb/__pycache__/wandb_utils.cpython-37.pyc new file mode 100755 index 0000000..169b2a4 Binary files /dev/null and b/Y5/utils/loggers/wandb/__pycache__/wandb_utils.cpython-37.pyc differ diff --git a/Y5/utils/loggers/wandb/__pycache__/wandb_utils.cpython-38.pyc b/Y5/utils/loggers/wandb/__pycache__/wandb_utils.cpython-38.pyc new file mode 100755 index 0000000..159cb2a Binary files /dev/null and b/Y5/utils/loggers/wandb/__pycache__/wandb_utils.cpython-38.pyc differ diff --git a/Y5/utils/loggers/wandb/log_dataset.py b/Y5/utils/loggers/wandb/log_dataset.py new file mode 100755 index 0000000..06e81fb --- /dev/null +++ b/Y5/utils/loggers/wandb/log_dataset.py @@ -0,0 +1,27 @@ +import argparse + +from wandb_utils import WandbLogger + +from utils.general import LOGGER + +WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' + + +def create_dataset_artifact(opt): + logger = WandbLogger(opt, None, job_type='Dataset Creation') # TODO: return value unused + if not logger.wandb: + LOGGER.info("install wandb using `pip install wandb` to log the dataset") + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path') + parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') + parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project') + parser.add_argument('--entity', default=None, help='W&B entity') + parser.add_argument('--name', type=str, default='log dataset', help='name of W&B run') + + opt = parser.parse_args() + opt.resume = False # Explicitly disallow resume check for dataset upload job + + create_dataset_artifact(opt) diff --git a/Y5/utils/loggers/wandb/sweep.py b/Y5/utils/loggers/wandb/sweep.py new file mode 100755 index 0000000..d49ea6f --- /dev/null +++ b/Y5/utils/loggers/wandb/sweep.py @@ -0,0 +1,41 @@ +import sys +from pathlib import Path + +import wandb + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[3] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH + +from train import parse_opt, train +from utils.callbacks import Callbacks +from utils.general import increment_path +from utils.torch_utils import select_device + + +def sweep(): + wandb.init() + # Get hyp dict from sweep agent. Copy because train() modifies parameters which confused wandb. + hyp_dict = vars(wandb.config).get("_items").copy() + + # Workaround: get necessary opt args + opt = parse_opt(known=True) + opt.batch_size = hyp_dict.get("batch_size") + opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve)) + opt.epochs = hyp_dict.get("epochs") + opt.nosave = True + opt.data = hyp_dict.get("data") + opt.weights = str(opt.weights) + opt.cfg = str(opt.cfg) + opt.data = str(opt.data) + opt.hyp = str(opt.hyp) + opt.project = str(opt.project) + device = select_device(opt.device, batch_size=opt.batch_size) + + # train + train(hyp_dict, opt, device, callbacks=Callbacks()) + + +if __name__ == "__main__": + sweep() diff --git a/Y5/utils/loggers/wandb/sweep.yaml b/Y5/utils/loggers/wandb/sweep.yaml new file mode 100755 index 0000000..688b1ea --- /dev/null +++ b/Y5/utils/loggers/wandb/sweep.yaml @@ -0,0 +1,143 @@ +# Hyperparameters for training +# To set range- +# Provide min and max values as: +# parameter: +# +# min: scalar +# max: scalar +# OR +# +# Set a specific list of search space- +# parameter: +# values: [scalar1, scalar2, scalar3...] +# +# You can use grid, bayesian and hyperopt search strategy +# For more info on configuring sweeps visit - https://docs.wandb.ai/guides/sweeps/configuration + +program: utils/loggers/wandb/sweep.py +method: random +metric: + name: metrics/mAP_0.5 + goal: maximize + +parameters: + # hyperparameters: set either min, max range or values list + data: + value: "data/coco128.yaml" + batch_size: + values: [64] + epochs: + values: [10] + + lr0: + distribution: uniform + min: 1e-5 + max: 1e-1 + lrf: + distribution: uniform + min: 0.01 + max: 1.0 + momentum: + distribution: uniform + min: 0.6 + max: 0.98 + weight_decay: + distribution: uniform + min: 0.0 + max: 0.001 + warmup_epochs: + distribution: uniform + min: 0.0 + max: 5.0 + warmup_momentum: + distribution: uniform + min: 0.0 + max: 0.95 + warmup_bias_lr: + distribution: uniform + min: 0.0 + max: 0.2 + box: + distribution: uniform + min: 0.02 + max: 0.2 + cls: + distribution: uniform + min: 0.2 + max: 4.0 + cls_pw: + distribution: uniform + min: 0.5 + max: 2.0 + obj: + distribution: uniform + min: 0.2 + max: 4.0 + obj_pw: + distribution: uniform + min: 0.5 + max: 2.0 + iou_t: + distribution: uniform + min: 0.1 + max: 0.7 + anchor_t: + distribution: uniform + min: 2.0 + max: 8.0 + fl_gamma: + distribution: uniform + min: 0.0 + max: 4.0 + hsv_h: + distribution: uniform + min: 0.0 + max: 0.1 + hsv_s: + distribution: uniform + min: 0.0 + max: 0.9 + hsv_v: + distribution: uniform + min: 0.0 + max: 0.9 + degrees: + distribution: uniform + min: 0.0 + max: 45.0 + translate: + distribution: uniform + min: 0.0 + max: 0.9 + scale: + distribution: uniform + min: 0.0 + max: 0.9 + shear: + distribution: uniform + min: 0.0 + max: 10.0 + perspective: + distribution: uniform + min: 0.0 + max: 0.001 + flipud: + distribution: uniform + min: 0.0 + max: 1.0 + fliplr: + distribution: uniform + min: 0.0 + max: 1.0 + mosaic: + distribution: uniform + min: 0.0 + max: 1.0 + mixup: + distribution: uniform + min: 0.0 + max: 1.0 + copy_paste: + distribution: uniform + min: 0.0 + max: 1.0 diff --git a/Y5/utils/loggers/wandb/wandb_utils.py b/Y5/utils/loggers/wandb/wandb_utils.py new file mode 100755 index 0000000..04521bf --- /dev/null +++ b/Y5/utils/loggers/wandb/wandb_utils.py @@ -0,0 +1,577 @@ +"""Utilities and tools for tracking runs with Weights & Biases.""" + +import logging +import os +import sys +from contextlib import contextmanager +from pathlib import Path +from typing import Dict + +import yaml +from tqdm import tqdm + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[3] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH + +from utils.dataloaders import LoadImagesAndLabels, img2label_paths +from utils.general import LOGGER, check_dataset, check_file + +try: + import wandb + + assert hasattr(wandb, '__version__') # verify package import not local dir +except (ImportError, AssertionError): + wandb = None + +RANK = int(os.getenv('RANK', -1)) +WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' + + +def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX): + return from_string[len(prefix):] + + +def check_wandb_config_file(data_config_file): + wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path + if Path(wandb_config).is_file(): + return wandb_config + return data_config_file + + +def check_wandb_dataset(data_file): + is_trainset_wandb_artifact = False + is_valset_wandb_artifact = False + if check_file(data_file) and data_file.endswith('.yaml'): + with open(data_file, errors='ignore') as f: + data_dict = yaml.safe_load(f) + is_trainset_wandb_artifact = isinstance(data_dict['train'], + str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX) + is_valset_wandb_artifact = isinstance(data_dict['val'], + str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX) + if is_trainset_wandb_artifact or is_valset_wandb_artifact: + return data_dict + else: + return check_dataset(data_file) + + +def get_run_info(run_path): + run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX)) + run_id = run_path.stem + project = run_path.parent.stem + entity = run_path.parent.parent.stem + model_artifact_name = 'run_' + run_id + '_model' + return entity, project, run_id, model_artifact_name + + +def check_wandb_resume(opt): + process_wandb_config_ddp_mode(opt) if RANK not in [-1, 0] else None + if isinstance(opt.resume, str): + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + if RANK not in [-1, 0]: # For resuming DDP runs + entity, project, run_id, model_artifact_name = get_run_info(opt.resume) + api = wandb.Api() + artifact = api.artifact(entity + '/' + project + '/' + model_artifact_name + ':latest') + modeldir = artifact.download() + opt.weights = str(Path(modeldir) / "last.pt") + return True + return None + + +def process_wandb_config_ddp_mode(opt): + with open(check_file(opt.data), errors='ignore') as f: + data_dict = yaml.safe_load(f) # data dict + train_dir, val_dir = None, None + if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX): + api = wandb.Api() + train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias) + train_dir = train_artifact.download() + train_path = Path(train_dir) / 'data/images/' + data_dict['train'] = str(train_path) + + if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX): + api = wandb.Api() + val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias) + val_dir = val_artifact.download() + val_path = Path(val_dir) / 'data/images/' + data_dict['val'] = str(val_path) + if train_dir or val_dir: + ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml') + with open(ddp_data_path, 'w') as f: + yaml.safe_dump(data_dict, f) + opt.data = ddp_data_path + + +class WandbLogger(): + """Log training runs, datasets, models, and predictions to Weights & Biases. + + This logger sends information to W&B at wandb.ai. By default, this information + includes hyperparameters, system configuration and metrics, model metrics, + and basic data metrics and analyses. + + By providing additional command line arguments to train.py, datasets, + models and predictions can also be logged. + + For more on how this logger is used, see the Weights & Biases documentation: + https://docs.wandb.com/guides/integrations/yolov5 + """ + + def __init__(self, opt, run_id=None, job_type='Training'): + """ + - Initialize WandbLogger instance + - Upload dataset if opt.upload_dataset is True + - Setup trainig processes if job_type is 'Training' + + arguments: + opt (namespace) -- Commandline arguments for this run + run_id (str) -- Run ID of W&B run to be resumed + job_type (str) -- To set the job_type for this run + + """ + # Pre-training routine -- + self.job_type = job_type + self.wandb, self.wandb_run = wandb, None if not wandb else wandb.run + self.val_artifact, self.train_artifact = None, None + self.train_artifact_path, self.val_artifact_path = None, None + self.result_artifact = None + self.val_table, self.result_table = None, None + self.bbox_media_panel_images = [] + self.val_table_path_map = None + self.max_imgs_to_log = 16 + self.wandb_artifact_data_dict = None + self.data_dict = None + # It's more elegant to stick to 1 wandb.init call, + # but useful config data is overwritten in the WandbLogger's wandb.init call + if isinstance(opt.resume, str): # checks resume from artifact + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + entity, project, run_id, model_artifact_name = get_run_info(opt.resume) + model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name + assert wandb, 'install wandb to resume wandb runs' + # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config + self.wandb_run = wandb.init(id=run_id, + project=project, + entity=entity, + resume='allow', + allow_val_change=True) + opt.resume = model_artifact_name + elif self.wandb: + self.wandb_run = wandb.init(config=opt, + resume="allow", + project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem, + entity=opt.entity, + name=opt.name if opt.name != 'exp' else None, + job_type=job_type, + id=run_id, + allow_val_change=True) if not wandb.run else wandb.run + if self.wandb_run: + if self.job_type == 'Training': + if opt.upload_dataset: + if not opt.resume: + self.wandb_artifact_data_dict = self.check_and_upload_dataset(opt) + + if opt.resume: + # resume from artifact + if isinstance(opt.resume, str) and opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + self.data_dict = dict(self.wandb_run.config.data_dict) + else: # local resume + self.data_dict = check_wandb_dataset(opt.data) + else: + self.data_dict = check_wandb_dataset(opt.data) + self.wandb_artifact_data_dict = self.wandb_artifact_data_dict or self.data_dict + + # write data_dict to config. useful for resuming from artifacts. Do this only when not resuming. + self.wandb_run.config.update({'data_dict': self.wandb_artifact_data_dict}, allow_val_change=True) + self.setup_training(opt) + + if self.job_type == 'Dataset Creation': + self.wandb_run.config.update({"upload_dataset": True}) + self.data_dict = self.check_and_upload_dataset(opt) + + def check_and_upload_dataset(self, opt): + """ + Check if the dataset format is compatible and upload it as W&B artifact + + arguments: + opt (namespace)-- Commandline arguments for current run + + returns: + Updated dataset info dictionary where local dataset paths are replaced by WAND_ARFACT_PREFIX links. + """ + assert wandb, 'Install wandb to upload dataset' + config_path = self.log_dataset_artifact(opt.data, opt.single_cls, + 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem) + with open(config_path, errors='ignore') as f: + wandb_data_dict = yaml.safe_load(f) + return wandb_data_dict + + def setup_training(self, opt): + """ + Setup the necessary processes for training YOLO models: + - Attempt to download model checkpoint and dataset artifacts if opt.resume stats with WANDB_ARTIFACT_PREFIX + - Update data_dict, to contain info of previous run if resumed and the paths of dataset artifact if downloaded + - Setup log_dict, initialize bbox_interval + + arguments: + opt (namespace) -- commandline arguments for this run + + """ + self.log_dict, self.current_epoch = {}, 0 + self.bbox_interval = opt.bbox_interval + if isinstance(opt.resume, str): + modeldir, _ = self.download_model_artifact(opt) + if modeldir: + self.weights = Path(modeldir) / "last.pt" + config = self.wandb_run.config + opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp, opt.imgsz = str( + self.weights), config.save_period, config.batch_size, config.bbox_interval, config.epochs,\ + config.hyp, config.imgsz + data_dict = self.data_dict + if self.val_artifact is None: # If --upload_dataset is set, use the existing artifact, don't download + self.train_artifact_path, self.train_artifact = self.download_dataset_artifact( + data_dict.get('train'), opt.artifact_alias) + self.val_artifact_path, self.val_artifact = self.download_dataset_artifact( + data_dict.get('val'), opt.artifact_alias) + + if self.train_artifact_path is not None: + train_path = Path(self.train_artifact_path) / 'data/images/' + data_dict['train'] = str(train_path) + if self.val_artifact_path is not None: + val_path = Path(self.val_artifact_path) / 'data/images/' + data_dict['val'] = str(val_path) + + if self.val_artifact is not None: + self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") + columns = ["epoch", "id", "ground truth", "prediction"] + columns.extend(self.data_dict['names']) + self.result_table = wandb.Table(columns) + self.val_table = self.val_artifact.get("val") + if self.val_table_path_map is None: + self.map_val_table_path() + if opt.bbox_interval == -1: + self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1 + if opt.evolve or opt.noplots: + self.bbox_interval = opt.bbox_interval = opt.epochs + 1 # disable bbox_interval + train_from_artifact = self.train_artifact_path is not None and self.val_artifact_path is not None + # Update the the data_dict to point to local artifacts dir + if train_from_artifact: + self.data_dict = data_dict + + def download_dataset_artifact(self, path, alias): + """ + download the model checkpoint artifact if the path starts with WANDB_ARTIFACT_PREFIX + + arguments: + path -- path of the dataset to be used for training + alias (str)-- alias of the artifact to be download/used for training + + returns: + (str, wandb.Artifact) -- path of the downladed dataset and it's corresponding artifact object if dataset + is found otherwise returns (None, None) + """ + if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX): + artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias) + dataset_artifact = wandb.use_artifact(artifact_path.as_posix().replace("\\", "/")) + assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'" + datadir = dataset_artifact.download() + return datadir, dataset_artifact + return None, None + + def download_model_artifact(self, opt): + """ + download the model checkpoint artifact if the resume path starts with WANDB_ARTIFACT_PREFIX + + arguments: + opt (namespace) -- Commandline arguments for this run + """ + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest") + assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist' + modeldir = model_artifact.download() + # epochs_trained = model_artifact.metadata.get('epochs_trained') + total_epochs = model_artifact.metadata.get('total_epochs') + is_finished = total_epochs is None + assert not is_finished, 'training is finished, can only resume incomplete runs.' + return modeldir, model_artifact + return None, None + + def log_model(self, path, opt, epoch, fitness_score, best_model=False): + """ + Log the model checkpoint as W&B artifact + + arguments: + path (Path) -- Path of directory containing the checkpoints + opt (namespace) -- Command line arguments for this run + epoch (int) -- Current epoch number + fitness_score (float) -- fitness score for current epoch + best_model (boolean) -- Boolean representing if the current checkpoint is the best yet. + """ + model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', + type='model', + metadata={ + 'original_url': str(path), + 'epochs_trained': epoch + 1, + 'save period': opt.save_period, + 'project': opt.project, + 'total_epochs': opt.epochs, + 'fitness_score': fitness_score}) + model_artifact.add_file(str(path / 'last.pt'), name='last.pt') + wandb.log_artifact(model_artifact, + aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 'best' if best_model else '']) + LOGGER.info(f"Saving model artifact on epoch {epoch + 1}") + + def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False): + """ + Log the dataset as W&B artifact and return the new data file with W&B links + + arguments: + data_file (str) -- the .yaml file with information about the dataset like - path, classes etc. + single_class (boolean) -- train multi-class data as single-class + project (str) -- project name. Used to construct the artifact path + overwrite_config (boolean) -- overwrites the data.yaml file if set to true otherwise creates a new + file with _wandb postfix. Eg -> data_wandb.yaml + + returns: + the new .yaml file with artifact links. it can be used to start training directly from artifacts + """ + upload_dataset = self.wandb_run.config.upload_dataset + log_val_only = isinstance(upload_dataset, str) and upload_dataset == 'val' + self.data_dict = check_dataset(data_file) # parse and check + data = dict(self.data_dict) + nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names']) + names = {k: v for k, v in enumerate(names)} # to index dictionary + + # log train set + if not log_val_only: + self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(data['train'], rect=True, batch_size=1), + names, + name='train') if data.get('train') else None + if data.get('train'): + data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train') + + self.val_artifact = self.create_dataset_table( + LoadImagesAndLabels(data['val'], rect=True, batch_size=1), names, name='val') if data.get('val') else None + if data.get('val'): + data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val') + + path = Path(data_file) + # create a _wandb.yaml file with artifacts links if both train and test set are logged + if not log_val_only: + path = (path.stem if overwrite_config else path.stem + '_wandb') + '.yaml' # updated data.yaml path + path = ROOT / 'data' / path + data.pop('download', None) + data.pop('path', None) + with open(path, 'w') as f: + yaml.safe_dump(data, f) + LOGGER.info(f"Created dataset config file {path}") + + if self.job_type == 'Training': # builds correct artifact pipeline graph + if not log_val_only: + self.wandb_run.log_artifact( + self.train_artifact) # calling use_artifact downloads the dataset. NOT NEEDED! + self.wandb_run.use_artifact(self.val_artifact) + self.val_artifact.wait() + self.val_table = self.val_artifact.get('val') + self.map_val_table_path() + else: + self.wandb_run.log_artifact(self.train_artifact) + self.wandb_run.log_artifact(self.val_artifact) + return path + + def map_val_table_path(self): + """ + Map the validation dataset Table like name of file -> it's id in the W&B Table. + Useful for - referencing artifacts for evaluation. + """ + self.val_table_path_map = {} + LOGGER.info("Mapping dataset") + for i, data in enumerate(tqdm(self.val_table.data)): + self.val_table_path_map[data[3]] = data[0] + + def create_dataset_table(self, dataset: LoadImagesAndLabels, class_to_id: Dict[int, str], name: str = 'dataset'): + """ + Create and return W&B artifact containing W&B Table of the dataset. + + arguments: + dataset -- instance of LoadImagesAndLabels class used to iterate over the data to build Table + class_to_id -- hash map that maps class ids to labels + name -- name of the artifact + + returns: + dataset artifact to be logged or used + """ + # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging + artifact = wandb.Artifact(name=name, type="dataset") + img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None + img_files = tqdm(dataset.im_files) if not img_files else img_files + for img_file in img_files: + if Path(img_file).is_dir(): + artifact.add_dir(img_file, name='data/images') + labels_path = 'labels'.join(dataset.path.rsplit('images', 1)) + artifact.add_dir(labels_path, name='data/labels') + else: + artifact.add_file(img_file, name='data/images/' + Path(img_file).name) + label_file = Path(img2label_paths([img_file])[0]) + artifact.add_file(str(label_file), name='data/labels/' + + label_file.name) if label_file.exists() else None + table = wandb.Table(columns=["id", "train_image", "Classes", "name"]) + class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()]) + for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)): + box_data, img_classes = [], {} + for cls, *xywh in labels[:, 1:].tolist(): + cls = int(cls) + box_data.append({ + "position": { + "middle": [xywh[0], xywh[1]], + "width": xywh[2], + "height": xywh[3]}, + "class_id": cls, + "box_caption": "%s" % (class_to_id[cls])}) + img_classes[cls] = class_to_id[cls] + boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space + table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), list(img_classes.values()), + Path(paths).name) + artifact.add(table, name) + return artifact + + def log_training_progress(self, predn, path, names): + """ + Build evaluation Table. Uses reference from validation dataset table. + + arguments: + predn (list): list of predictions in the native space in the format - [xmin, ymin, xmax, ymax, confidence, class] + path (str): local path of the current evaluation image + names (dict(int, str)): hash map that maps class ids to labels + """ + class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()]) + box_data = [] + avg_conf_per_class = [0] * len(self.data_dict['names']) + pred_class_count = {} + for *xyxy, conf, cls in predn.tolist(): + if conf >= 0.25: + cls = int(cls) + box_data.append({ + "position": { + "minX": xyxy[0], + "minY": xyxy[1], + "maxX": xyxy[2], + "maxY": xyxy[3]}, + "class_id": cls, + "box_caption": f"{names[cls]} {conf:.3f}", + "scores": { + "class_score": conf}, + "domain": "pixel"}) + avg_conf_per_class[cls] += conf + + if cls in pred_class_count: + pred_class_count[cls] += 1 + else: + pred_class_count[cls] = 1 + + for pred_class in pred_class_count.keys(): + avg_conf_per_class[pred_class] = avg_conf_per_class[pred_class] / pred_class_count[pred_class] + + boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space + id = self.val_table_path_map[Path(path).name] + self.result_table.add_data(self.current_epoch, id, self.val_table.data[id][1], + wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set), + *avg_conf_per_class) + + def val_one_image(self, pred, predn, path, names, im): + """ + Log validation data for one image. updates the result Table if validation dataset is uploaded and log bbox media panel + + arguments: + pred (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class] + predn (list): list of predictions in the native space - [xmin, ymin, xmax, ymax, confidence, class] + path (str): local path of the current evaluation image + """ + if self.val_table and self.result_table: # Log Table if Val dataset is uploaded as artifact + self.log_training_progress(predn, path, names) + + if len(self.bbox_media_panel_images) < self.max_imgs_to_log and self.current_epoch > 0: + if self.current_epoch % self.bbox_interval == 0: + box_data = [{ + "position": { + "minX": xyxy[0], + "minY": xyxy[1], + "maxX": xyxy[2], + "maxY": xyxy[3]}, + "class_id": int(cls), + "box_caption": f"{names[int(cls)]} {conf:.3f}", + "scores": { + "class_score": conf}, + "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()] + boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space + self.bbox_media_panel_images.append(wandb.Image(im, boxes=boxes, caption=path.name)) + + def log(self, log_dict): + """ + save the metrics to the logging dictionary + + arguments: + log_dict (Dict) -- metrics/media to be logged in current step + """ + if self.wandb_run: + for key, value in log_dict.items(): + self.log_dict[key] = value + + def end_epoch(self, best_result=False): + """ + commit the log_dict, model artifacts and Tables to W&B and flush the log_dict. + + arguments: + best_result (boolean): Boolean representing if the result of this evaluation is best or not + """ + if self.wandb_run: + with all_logging_disabled(): + if self.bbox_media_panel_images: + self.log_dict["BoundingBoxDebugger"] = self.bbox_media_panel_images + try: + wandb.log(self.log_dict) + except BaseException as e: + LOGGER.info( + f"An error occurred in wandb logger. The training will proceed without interruption. More info\n{e}" + ) + self.wandb_run.finish() + self.wandb_run = None + + self.log_dict = {} + self.bbox_media_panel_images = [] + if self.result_artifact: + self.result_artifact.add(self.result_table, 'result') + wandb.log_artifact(self.result_artifact, + aliases=[ + 'latest', 'last', 'epoch ' + str(self.current_epoch), + ('best' if best_result else '')]) + + wandb.log({"evaluation": self.result_table}) + columns = ["epoch", "id", "ground truth", "prediction"] + columns.extend(self.data_dict['names']) + self.result_table = wandb.Table(columns) + self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") + + def finish_run(self): + """ + Log metrics if any and finish the current W&B run + """ + if self.wandb_run: + if self.log_dict: + with all_logging_disabled(): + wandb.log(self.log_dict) + wandb.run.finish() + + +@contextmanager +def all_logging_disabled(highest_level=logging.CRITICAL): + """ source - https://gist.github.com/simon-weber/7853144 + A context manager that will prevent any logging messages triggered during the body from being processed. + :param highest_level: the maximum logging level in use. + This would only need to be changed if a custom level greater than CRITICAL is defined. + """ + previous_level = logging.root.manager.disable + logging.disable(highest_level) + try: + yield + finally: + logging.disable(previous_level) diff --git a/Y5/utils/loss.py b/Y5/utils/loss.py index 82c3271..9b9c3d9 100755 --- a/Y5/utils/loss.py +++ b/Y5/utils/loss.py @@ -1,10 +1,13 @@ -# Loss functions +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Loss functions +""" import torch import torch.nn as nn -from Y5.utils.general import bbox_iou -from Y5.utils.torch_utils import is_parallel +from utils.metrics import bbox_iou +from utils.torch_utils import de_parallel def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441 @@ -15,7 +18,7 @@ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#iss class BCEBlurWithLogitsLoss(nn.Module): # BCEwithLogitLoss() with reduced missing label effects. def __init__(self, alpha=0.05): - super(BCEBlurWithLogitsLoss, self).__init__() + super().__init__() self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss() self.alpha = alpha @@ -32,7 +35,7 @@ class BCEBlurWithLogitsLoss(nn.Module): class FocalLoss(nn.Module): # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): - super(FocalLoss, self).__init__() + super().__init__() self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() self.gamma = gamma self.alpha = alpha @@ -62,7 +65,7 @@ class FocalLoss(nn.Module): class QFocalLoss(nn.Module): # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): - super(QFocalLoss, self).__init__() + super().__init__() self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() self.gamma = gamma self.alpha = alpha @@ -86,9 +89,10 @@ class QFocalLoss(nn.Module): class ComputeLoss: + sort_obj_iou = False + # Compute losses def __init__(self, model, autobalance=False): - super(ComputeLoss, self).__init__() device = next(model.parameters()).device # get model device h = model.hyp # hyperparameters @@ -97,49 +101,60 @@ class ComputeLoss: BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device)) # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3 - self.cp, self.cn = smooth_BCE(eps=0.0) + self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets # Focal loss g = h['fl_gamma'] # focal loss gamma if g > 0: BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g) - det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module - self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7 - self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index - self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance - for k in 'na', 'nc', 'nl', 'anchors': - setattr(self, k, getattr(det, k)) + m = de_parallel(model).model[-1] # Detect() module + self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7 + self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index + self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance + self.na = m.na # number of anchors + self.nc = m.nc # number of classes + self.nl = m.nl # number of layers + self.anchors = m.anchors + self.device = device - def __call__(self, p, targets): # predictions, targets, model - device = targets.device - lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device) + def __call__(self, p, targets): # predictions, targets + lcls = torch.zeros(1, device=self.device) # class loss + lbox = torch.zeros(1, device=self.device) # box loss + lobj = torch.zeros(1, device=self.device) # object loss tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets # Losses for i, pi in enumerate(p): # layer index, layer predictions b, a, gj, gi = indices[i] # image, anchor, gridy, gridx - tobj = torch.zeros_like(pi[..., 0], device=device) # target obj + tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device) # target obj n = b.shape[0] # number of targets if n: - ps = pi[b, a, gj, gi] # prediction subset corresponding to targets + # pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1) # faster, requires torch 1.8.0 + pxy, pwh, _, pcls = pi[b, a, gj, gi].split((2, 2, 1, self.nc), 1) # target-subset of predictions # Regression - pxy = ps[:, :2].sigmoid() * 2. - 0.5 - pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i] + pxy = pxy.sigmoid() * 2 - 0.5 + pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i] pbox = torch.cat((pxy, pwh), 1) # predicted box - iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target) + iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(prediction, target) lbox += (1.0 - iou).mean() # iou loss # Objectness - tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio + iou = iou.detach().clamp(0).type(tobj.dtype) + if self.sort_obj_iou: + j = iou.argsort() + b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j] + if self.gr < 1: + iou = (1.0 - self.gr) + self.gr * iou + tobj[b, a, gj, gi] = iou # iou ratio # Classification if self.nc > 1: # cls loss (only if multiple classes) - t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets + t = torch.full_like(pcls, self.cn, device=self.device) # targets t[range(n), tcls[i]] = self.cp - lcls += self.BCEcls(ps[:, 5:], t) # BCE + lcls += self.BCEcls(pcls, t) # BCE # Append targets to text file # with open('targets.txt', 'a') as file: @@ -157,41 +172,46 @@ class ComputeLoss: lcls *= self.hyp['cls'] bs = tobj.shape[0] # batch size - loss = lbox + lobj + lcls - return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach() + return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach() def build_targets(self, p, targets): # Build targets for compute_loss(), input targets(image,class,x,y,w,h) na, nt = self.na, targets.shape[0] # number of anchors, targets tcls, tbox, indices, anch = [], [], [], [] - gain = torch.ones(7, device=targets.device) # normalized to gridspace gain - ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) - targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices + gain = torch.ones(7, device=self.device) # normalized to gridspace gain + ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) + targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2) # append anchor indices g = 0.5 # bias - off = torch.tensor([[0, 0], - [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m - # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm - ], device=targets.device).float() * g # offsets + off = torch.tensor( + [ + [0, 0], + [1, 0], + [0, 1], + [-1, 0], + [0, -1], # j,k,l,m + # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm + ], + device=self.device).float() * g # offsets for i in range(self.nl): - anchors = self.anchors[i] - gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain + anchors, shape = self.anchors[i], p[i].shape + gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain # Match targets to anchors - t = targets * gain + t = targets * gain # shape(3,n,7) if nt: # Matches - r = t[:, :, 4:6] / anchors[:, None] # wh ratio - j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare + r = t[..., 4:6] / anchors[:, None] # wh ratio + j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t'] # compare # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2)) t = t[j] # filter # Offsets gxy = t[:, 2:4] # grid xy gxi = gain[[2, 3]] - gxy # inverse - j, k = ((gxy % 1. < g) & (gxy > 1.)).T - l, m = ((gxi % 1. < g) & (gxi > 1.)).T + j, k = ((gxy % 1 < g) & (gxy > 1)).T + l, m = ((gxi % 1 < g) & (gxi > 1)).T j = torch.stack((torch.ones_like(j), j, k, l, m)) t = t.repeat((5, 1, 1))[j] offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] @@ -200,15 +220,13 @@ class ComputeLoss: offsets = 0 # Define - b, c = t[:, :2].long().T # image, class - gxy = t[:, 2:4] # grid xy - gwh = t[:, 4:6] # grid wh + bc, gxy, gwh, a = t.chunk(4, 1) # (image, class), grid xy, grid wh, anchors + a, (b, c) = a.long().view(-1), bc.long().T # anchors, image, class gij = (gxy - offsets).long() - gi, gj = gij.T # grid xy indices + gi, gj = gij.T # grid indices # Append - a = t[:, 6].long() # anchor indices - indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices + indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, anchor, grid tbox.append(torch.cat((gxy - gij, gwh), 1)) # box anch.append(anchors[a]) # anchors tcls.append(c) # class diff --git a/Y5/utils/metrics.py b/Y5/utils/metrics.py index 666b8c7..e17747b 100755 --- a/Y5/utils/metrics.py +++ b/Y5/utils/metrics.py @@ -1,13 +1,16 @@ -# Model validation metrics +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Model validation metrics +""" +import math +import warnings from pathlib import Path import matplotlib.pyplot as plt import numpy as np import torch -from . import general - def fitness(x): # Model fitness as a weighted combination of metrics @@ -15,7 +18,15 @@ def fitness(x): return (x[:, :4] * w).sum(1) -def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()): +def smooth(y, f=0.05): + # Box filter of fraction f + nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd) + p = np.ones(nf // 2) # ones padding + yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded + return np.convolve(yp, np.ones(nf) / nf, mode='valid') # y-smoothed + + +def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16): """ Compute the average precision, given the recall and precision curves. Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. # Arguments @@ -34,7 +45,7 @@ def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] # Find unique classes - unique_classes = np.unique(target_cls) + unique_classes, nt = np.unique(target_cls, return_counts=True) nc = unique_classes.shape[0] # number of classes, number of detections # Create Precision-Recall curve and compute AP for each class @@ -42,40 +53,44 @@ def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000)) for ci, c in enumerate(unique_classes): i = pred_cls == c - n_l = (target_cls == c).sum() # number of labels + n_l = nt[ci] # number of labels n_p = i.sum() # number of predictions - if n_p == 0 or n_l == 0: continue - else: - # Accumulate FPs and TPs - fpc = (1 - tp[i]).cumsum(0) - tpc = tp[i].cumsum(0) - # Recall - recall = tpc / (n_l + 1e-16) # recall curve - r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases + # Accumulate FPs and TPs + fpc = (1 - tp[i]).cumsum(0) + tpc = tp[i].cumsum(0) - # Precision - precision = tpc / (tpc + fpc) # precision curve - p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score + # Recall + recall = tpc / (n_l + eps) # recall curve + r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases - # AP from recall-precision curve - for j in range(tp.shape[1]): - ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j]) - if plot and j == 0: - py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5 + # Precision + precision = tpc / (tpc + fpc) # precision curve + p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score + + # AP from recall-precision curve + for j in range(tp.shape[1]): + ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j]) + if plot and j == 0: + py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5 # Compute F1 (harmonic mean of precision and recall) - f1 = 2 * p * r / (p + r + 1e-16) + f1 = 2 * p * r / (p + r + eps) + names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data + names = dict(enumerate(names)) # to dict if plot: plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names) plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1') plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision') plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall') - i = f1.mean(0).argmax() # max F1 index - return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32') + i = smooth(f1.mean(0), 0.1).argmax() # max F1 index + p, r, f1 = p[:, i], r[:, i], f1[:, i] + tp = (r * nt).round() # true positives + fp = (tp / (p + eps) - tp).round() # false positives + return tp, fp, p, r, f1, ap, unique_classes.astype(int) def compute_ap(recall, precision): @@ -88,8 +103,8 @@ def compute_ap(recall, precision): """ # Append sentinel values to beginning and end - mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01])) - mpre = np.concatenate(([1.], precision, [0.])) + mrec = np.concatenate(([0.0], recall, [1.0])) + mpre = np.concatenate(([1.0], precision, [0.0])) # Compute the precision envelope mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) @@ -127,7 +142,7 @@ class ConfusionMatrix: detections = detections[detections[:, 4] > self.conf] gt_classes = labels[:, 0].int() detection_classes = detections[:, 5].int() - iou = general.box_iou(labels[:, 1:], detections[:, :4]) + iou = box_iou(labels[:, 1:], detections[:, :4]) x = torch.where(iou > self.iou_thres) if x[0].shape[0]: @@ -141,11 +156,11 @@ class ConfusionMatrix: matches = np.zeros((0, 3)) n = matches.shape[0] > 0 - m0, m1, _ = matches.transpose().astype(np.int16) + m0, m1, _ = matches.transpose().astype(int) for i, gc in enumerate(gt_classes): j = m0 == i if n and sum(j) == 1: - self.matrix[gc, detection_classes[m1[j]]] += 1 # correct + self.matrix[detection_classes[m1[j]], gc] += 1 # correct else: self.matrix[self.nc, gc] += 1 # background FP @@ -157,33 +172,148 @@ class ConfusionMatrix: def matrix(self): return self.matrix - def plot(self, save_dir='', names=()): + def tp_fp(self): + tp = self.matrix.diagonal() # true positives + fp = self.matrix.sum(1) - tp # false positives + # fn = self.matrix.sum(0) - tp # false negatives (missed detections) + return tp[:-1], fp[:-1] # remove background class + + def plot(self, normalize=True, save_dir='', names=()): try: import seaborn as sn - array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize + array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1) # normalize columns array[array < 0.005] = np.nan # don't annotate (would appear as 0.00) fig = plt.figure(figsize=(12, 9), tight_layout=True) - sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size - labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels - sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True, - xticklabels=names + ['background FP'] if labels else "auto", - yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1)) + nc, nn = self.nc, len(names) # number of classes, names + sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size + labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered + sn.heatmap(array, + annot=nc < 30, + annot_kws={ + "size": 8}, + cmap='Blues', + fmt='.2f', + square=True, + vmin=0.0, + xticklabels=names + ['background FP'] if labels else "auto", + yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1)) fig.axes[0].set_xlabel('True') fig.axes[0].set_ylabel('Predicted') fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250) + plt.close() except Exception as e: - pass + print(f'WARNING: ConfusionMatrix plot failure: {e}') def print(self): for i in range(self.nc + 1): print(' '.join(map(str, self.matrix[i]))) +def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7): + # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4) + + # Get the coordinates of bounding boxes + if xywh: # transform from xywh to xyxy + (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, 1), box2.chunk(4, 1) + w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2 + b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_ + b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_ + else: # x1, y1, x2, y2 = box1 + b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, 1) + b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, 1) + w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps + w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps + + # Intersection area + inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ + (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) + + # Union Area + union = w1 * h1 + w2 * h2 - inter + eps + + # IoU + iou = inter / union + if CIoU or DIoU or GIoU: + cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width + ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height + if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 + c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared + rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2 + if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 + v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2) + with torch.no_grad(): + alpha = v / (v - iou + (1 + eps)) + return iou - (rho2 / c2 + v * alpha) # CIoU + return iou - rho2 / c2 # DIoU + c_area = cw * ch + eps # convex area + return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf + return iou # IoU + + +def box_area(box): + # box = xyxy(4,n) + return (box[2] - box[0]) * (box[3] - box[1]) + + +def box_iou(box1, box2): + # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py + """ + Return intersection-over-union (Jaccard index) of boxes. + Both sets of boxes are expected to be in (x1, y1, x2, y2) format. + Arguments: + box1 (Tensor[N, 4]) + box2 (Tensor[M, 4]) + Returns: + iou (Tensor[N, M]): the NxM matrix containing the pairwise + IoU values for every element in boxes1 and boxes2 + """ + + # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) + (a1, a2), (b1, b2) = box1[:, None].chunk(2, 2), box2.chunk(2, 1) + inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2) + + # IoU = inter / (area1 + area2 - inter) + return inter / (box_area(box1.T)[:, None] + box_area(box2.T) - inter) + + +def bbox_ioa(box1, box2, eps=1E-7): + """ Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2 + box1: np.array of shape(4) + box2: np.array of shape(nx4) + returns: np.array of shape(n) + """ + + # Get the coordinates of bounding boxes + b1_x1, b1_y1, b1_x2, b1_y2 = box1 + b2_x1, b2_y1, b2_x2, b2_y2 = box2.T + + # Intersection area + inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \ + (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0) + + # box2 area + box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps + + # Intersection over box2 area + return inter_area / box2_area + + +def wh_iou(wh1, wh2): + # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2 + wh1 = wh1[:, None] # [N,1,2] + wh2 = wh2[None] # [1,M,2] + inter = torch.min(wh1, wh2).prod(2) # [N,M] + return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter) + + # Plots ---------------------------------------------------------------------------------------------------------------- -def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()): + +def plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=()): # Precision-recall curve fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) py = np.stack(py, axis=1) @@ -200,10 +330,11 @@ def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()): ax.set_xlim(0, 1) ax.set_ylim(0, 1) plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") - fig.savefig(Path(save_dir), dpi=250) + fig.savefig(save_dir, dpi=250) + plt.close() -def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'): +def plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric'): # Metric-confidence curve fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) @@ -213,11 +344,12 @@ def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence' else: ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric) - y = py.mean(0) + y = smooth(py.mean(0), 0.05) ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}') ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_xlim(0, 1) ax.set_ylim(0, 1) plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") - fig.savefig(Path(save_dir), dpi=250) + fig.savefig(save_dir, dpi=250) + plt.close() diff --git a/Y5/utils/plots.py b/Y5/utils/plots.py index 8ee380c..1bbb9c0 100755 --- a/Y5/utils/plots.py +++ b/Y5/utils/plots.py @@ -1,38 +1,156 @@ -# Plotting utils +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Plotting utils +""" -import glob import math import os -import random from copy import copy from pathlib import Path +from urllib.error import URLError import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd -import seaborn as sns +import seaborn as sn import torch -import yaml -from common import global_para as gp from PIL import Image, ImageDraw, ImageFont -from scipy.signal import butter, filtfilt -from Y5.utils.general import xywh2xyxy, xyxy2xywh -from Y5.utils.metrics import fitness -from cv2AddChineseText import cv2AddChineseText +from utils.general import (CONFIG_DIR, FONT, LOGGER, Timeout, check_font, check_requirements, clip_coords, + increment_path, is_ascii, threaded, try_except, xywh2xyxy, xyxy2xywh) +from utils.metrics import fitness + # Settings +RANK = int(os.getenv('RANK', -1)) matplotlib.rc('font', **{'size': 11}) matplotlib.use('Agg') # for writing to files only -def color_list(): - # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb - def hex2rgb(h): +class Colors: + # Ultralytics color palette https://ultralytics.com/ + def __init__(self): + # hex = matplotlib.colors.TABLEAU_COLORS.values() + hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB', + '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7') + self.palette = [self.hex2rgb(f'#{c}') for c in hexs] + self.n = len(self.palette) + + def __call__(self, i, bgr=False): + c = self.palette[int(i) % self.n] + return (c[2], c[1], c[0]) if bgr else c + + @staticmethod + def hex2rgb(h): # rgb order (PIL) return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4)) - return [hex2rgb(h) for h in matplotlib.colors.TABLEAU_COLORS.values()] # or BASE_ (8), CSS4_ (148), XKCD_ (949) + +colors = Colors() # create instance for 'from utils.plots import colors' + + +def check_pil_font(font=FONT, size=10): + # Return a PIL TrueType Font, downloading to CONFIG_DIR if necessary + font = Path(font) + font = font if font.exists() else (CONFIG_DIR / font.name) + try: + return ImageFont.truetype(str(font) if font.exists() else font.name, size) + except Exception: # download if missing + try: + check_font(font) + return ImageFont.truetype(str(font), size) + except TypeError: + check_requirements('Pillow>=8.4.0') # known issue https://github.com/ultralytics/yolov5/issues/5374 + except URLError: # not online + return ImageFont.load_default() + + +class Annotator: + # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations + def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'): + assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.' + non_ascii = not is_ascii(example) # non-latin labels, i.e. asian, arabic, cyrillic + self.pil = pil or non_ascii + if self.pil: # use PIL + self.im = im if isinstance(im, Image.Image) else Image.fromarray(im) + self.draw = ImageDraw.Draw(self.im) + self.font = check_pil_font(font='Arial.Unicode.ttf' if non_ascii else font, + size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12)) + else: # use cv2 + self.im = im + self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width + + def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)): + # Add one xyxy box to image with label + if self.pil or not is_ascii(label): + self.draw.rectangle(box, width=self.lw, outline=color) # box + if label: + w, h = self.font.getsize(label) # text width, height + outside = box[1] - h >= 0 # label fits outside box + self.draw.rectangle( + (box[0], box[1] - h if outside else box[1], box[0] + w + 1, + box[1] + 1 if outside else box[1] + h + 1), + fill=color, + ) + # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0 + self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font) + else: # cv2 + p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3])) + cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA) + if label: + tf = max(self.lw - 1, 1) # font thickness + w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0] # text width, height + outside = p1[1] - h >= 3 + p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3 + cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled + cv2.putText(self.im, + label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2), + 0, + self.lw / 3, + txt_color, + thickness=tf, + lineType=cv2.LINE_AA) + + def rectangle(self, xy, fill=None, outline=None, width=1): + # Add rectangle to image (PIL-only) + self.draw.rectangle(xy, fill, outline, width) + + def text(self, xy, text, txt_color=(255, 255, 255)): + # Add text to image (PIL-only) + w, h = self.font.getsize(text) # text width, height + self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font) + + def result(self): + # Return annotated image as array + return np.asarray(self.im) + + +def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')): + """ + x: Features to be visualized + module_type: Module type + stage: Module stage within model + n: Maximum number of feature maps to plot + save_dir: Directory to save results + """ + if 'Detect' not in module_type: + batch, channels, height, width = x.shape # batch, channels, height, width + if height > 1 and width > 1: + f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename + + blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels + n = min(n, channels) # number of plots + fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols + ax = ax.ravel() + plt.subplots_adjust(wspace=0.05, hspace=0.05) + for i in range(n): + ax[i].imshow(blocks[i].squeeze()) # cmap='gray' + ax[i].axis('off') + + LOGGER.info(f'Saving {f}... ({n}/{channels})') + plt.savefig(f, dpi=300, bbox_inches='tight') + plt.close() + np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy()) # npy save def hist2d(x, y, n=100): @@ -45,6 +163,8 @@ def hist2d(x, y, n=100): def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5): + from scipy.signal import butter, filtfilt + # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy def butter_lowpass(cutoff, fs, order): nyq = 0.5 * fs @@ -55,77 +175,6 @@ def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5): return filtfilt(b, a, data) # forward-backward filter -def plot_one_box1(x, img, color=None, label=None, line_thickness=3): - # Plots one bounding box on image img - tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness - color = color or [random.randint(0, 255) for _ in range(3)] - c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) - cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA) - if label: - tf = max(tl - 1, 1) # font thickness - t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] - c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3 - cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled - cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) -def plot_one_box(x, draw, height,width,color=None, label=None, Index = None, line_thickness=3): - # Plots one bounding box on image img - tl = line_thickness or round(0.002 * (height + width) / 2) + 1 # line/font thickness - color = color or tuple(random.randint(0, 255) for _ in range(3)) - c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) - #ÏÔʾindex - - - # draw.text((c1[0]-20, c1[1]), str(Index), (0, 0, 255),font=fontStyle) - draw.rectangle((c1, c2), fill=None, outline=color, width=tl) - if label: - tf = max(tl - 1, 1) # font thickness - t_size = cv2.getTextSize(label, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=gp.fontScale , thickness=tl)[0] - print(label,t_size[0],t_size[1]) - c1 = c1[0],c1[1]-t_size[1] - c2 = c1[0] + t_size[0], c1[1]+t_size[1] - draw.rectangle((c1, c2), fill=color, outline=color, width=tl) - #cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled - #cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) - #if not label == None: - - draw = cv2AddChineseText(draw, label,(c1[0], c1[1]), textColor = (225, 255, 255), textSize=tf*17) - #img = cv2AddChineseText(img, "ÊýÁ¿: {}".format(str("011")), (2000,100), textColor=(0, 255, 0), textSize=80) - return draw - -def plot_one_box_PIL(box, img, color=None, label=None, line_thickness=None): - img = Image.fromarray(img) - draw = ImageDraw.Draw(img) - line_thickness = line_thickness or max(int(min(img.size) / 200), 2) - draw.rectangle(box, width=line_thickness, outline=tuple(color)) # plot - if label: - fontsize = max(round(max(img.size) / 40), 12) - font = ImageFont.truetype("Arial.ttf", fontsize) - txt_width, txt_height = font.getsize(label) - draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=tuple(color)) - draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font) - return np.asarray(img) - - -def plot_wh_methods(): # from utils.plots import *; plot_wh_methods() - # Compares the two methods for width-height anchor multiplication - # https://github.com/ultralytics/yolov3/issues/168 - x = np.arange(-4.0, 4.0, .1) - ya = np.exp(x) - yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2 - - fig = plt.figure(figsize=(6, 3), tight_layout=True) - plt.plot(x, ya, '.-', label='YOLOv3') - plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2') - plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6') - plt.xlim(left=-4, right=4) - plt.ylim(bottom=0, top=6) - plt.xlabel('input') - plt.ylabel('output') - plt.grid() - plt.legend() - fig.savefig('comparison.png', dpi=200) - - def output_to_target(output): # Convert model output to target format [batch_id, class_id, x, y, w, h, conf] targets = [] @@ -135,83 +184,66 @@ def output_to_target(output): return np.array(targets) -def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16): +@threaded +def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=1920, max_subplots=16): # Plot image grid with labels - if isinstance(images, torch.Tensor): images = images.cpu().float().numpy() if isinstance(targets, torch.Tensor): targets = targets.cpu().numpy() - - # un-normalise if np.max(images[0]) <= 1: - images *= 255 - - tl = 3 # line thickness - tf = max(tl - 1, 1) # font thickness + images *= 255 # de-normalise (optional) bs, _, h, w = images.shape # batch size, _, height, width bs = min(bs, max_subplots) # limit plot images ns = np.ceil(bs ** 0.5) # number of subplots (square) - # Check if we should resize - scale_factor = max_size / max(h, w) - if scale_factor < 1: - h = math.ceil(scale_factor * h) - w = math.ceil(scale_factor * w) - - colors = color_list() # list of colors + # Build Image mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init - for i, img in enumerate(images): + for i, im in enumerate(images): if i == max_subplots: # if last batch has fewer images than we expect break + x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin + im = im.transpose(1, 2, 0) + mosaic[y:y + h, x:x + w, :] = im - block_x = int(w * (i // ns)) - block_y = int(h * (i % ns)) + # Resize (optional) + scale = max_size / ns / max(h, w) + if scale < 1: + h = math.ceil(scale * h) + w = math.ceil(scale * w) + mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h))) - img = img.transpose(1, 2, 0) - if scale_factor < 1: - img = cv2.resize(img, (w, h)) - - mosaic[block_y:block_y + h, block_x:block_x + w, :] = img + # Annotate + fs = int((h + w) * ns * 0.01) # font size + annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names) + for i in range(i + 1): + x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin + annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders + if paths: + annotator.text((x + 5, y + 5 + h), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames if len(targets) > 0: - image_targets = targets[targets[:, 0] == i] - boxes = xywh2xyxy(image_targets[:, 2:6]).T - classes = image_targets[:, 1].astype('int') - labels = image_targets.shape[1] == 6 # labels if no conf column - conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred) + ti = targets[targets[:, 0] == i] # image targets + boxes = xywh2xyxy(ti[:, 2:6]).T + classes = ti[:, 1].astype('int') + labels = ti.shape[1] == 6 # labels if no conf column + conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred) if boxes.shape[1]: if boxes.max() <= 1.01: # if normalized with tolerance 0.01 boxes[[0, 2]] *= w # scale to pixels boxes[[1, 3]] *= h - elif scale_factor < 1: # absolute coords need scale if image scales - boxes *= scale_factor - boxes[[0, 2]] += block_x - boxes[[1, 3]] += block_y - for j, box in enumerate(boxes.T): - cls = int(classes[j]) - color = colors[cls % len(colors)] + elif scale < 1: # absolute coords need scale if image scales + boxes *= scale + boxes[[0, 2]] += x + boxes[[1, 3]] += y + for j, box in enumerate(boxes.T.tolist()): + cls = classes[j] + color = colors(cls) cls = names[cls] if names else cls if labels or conf[j] > 0.25: # 0.25 conf thresh - label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j]) - plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl) - - # Draw image filename labels - if paths: - label = Path(paths[i]).name[:40] # trim to 40 char - t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] - cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf, - lineType=cv2.LINE_AA) - - # Image border - cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3) - - if fname: - r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size - mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA) - # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save - Image.fromarray(mosaic).save(fname) # PIL save - return mosaic + label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}' + annotator.box_label(box, label, color=color) + annotator.im.save(fname) # save def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''): @@ -231,9 +263,9 @@ def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''): plt.close() -def plot_test_txt(): # from utils.plots import *; plot_test() - # Plot test.txt histograms - x = np.loadtxt('test.txt', dtype=np.float32) +def plot_val_txt(): # from utils.plots import *; plot_val() + # Plot val.txt histograms + x = np.loadtxt('val.txt', dtype=np.float32) box = xyxy2xywh(x[:, :4]) cx, cy = box[:, 0], box[:, 1] @@ -255,71 +287,94 @@ def plot_targets_txt(): # from utils.plots import *; plot_targets_txt() fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True) ax = ax.ravel() for i in range(4): - ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std())) + ax[i].hist(x[i], bins=100, label=f'{x[i].mean():.3g} +/- {x[i].std():.3g}') ax[i].legend() ax[i].set_title(s[i]) plt.savefig('targets.jpg', dpi=200) -def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt() - # Plot study.txt generated by test.py - fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True) - # ax = ax.ravel() +def plot_val_study(file='', dir='', x=None): # from utils.plots import *; plot_val_study() + # Plot file=study.txt generated by val.py (or plot all study*.txt in dir) + save_dir = Path(file).parent if file else Path(dir) + plot2 = False # plot additional results + if plot2: + ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel() fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True) - # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s', 'yolov5m', 'yolov5l', 'yolov5x']]: - for f in sorted(Path(path).glob('study*.txt')): + # for f in [save_dir / f'study_coco_{x}.txt' for x in ['yolov5n6', 'yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]: + for f in sorted(save_dir.glob('study*.txt')): y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T x = np.arange(y.shape[1]) if x is None else np.array(x) - s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)'] - # for i in range(7): - # ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8) - # ax[i].set_title(s[i]) + if plot2: + s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)'] + for i in range(7): + ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8) + ax[i].set_title(s[i]) j = y[3].argmax() + 1 - ax2.plot(y[6, :j], y[3, :j] * 1E2, '.-', linewidth=2, markersize=8, + ax2.plot(y[5, 1:j], + y[3, 1:j] * 1E2, + '.-', + linewidth=2, + markersize=8, label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO')) ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5], - 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet') + 'k.-', + linewidth=2, + markersize=8, + alpha=.25, + label='EfficientDet') ax2.grid(alpha=0.2) ax2.set_yticks(np.arange(20, 60, 5)) - ax2.set_xlim(0, 30) - ax2.set_ylim(30, 55) + ax2.set_xlim(0, 57) + ax2.set_ylim(25, 55) ax2.set_xlabel('GPU Speed (ms/img)') ax2.set_ylabel('COCO AP val') ax2.legend(loc='lower right') - plt.savefig(str(Path(path).name) + '.png', dpi=300) + f = save_dir / 'study.png' + print(f'Saving {f}...') + plt.savefig(f, dpi=300) -def plot_labels(labels, save_dir=Path(''), loggers=None): +@try_except # known issue https://github.com/ultralytics/yolov5/issues/5395 +@Timeout(30) # known issue https://github.com/ultralytics/yolov5/issues/5611 +def plot_labels(labels, names=(), save_dir=Path('')): # plot dataset labels - print('Plotting labels... ') + LOGGER.info(f"Plotting labels to {save_dir / 'labels.jpg'}... ") c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes nc = int(c.max() + 1) # number of classes - colors = color_list() x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height']) # seaborn correlogram - sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9)) + sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9)) plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200) plt.close() # matplotlib labels matplotlib.use('svg') # faster ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel() - ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) - ax[0].set_xlabel('classes') - sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9) - sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9) + y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) + try: # color histogram bars by class + [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # known issue #3195 + except Exception: + pass + ax[0].set_ylabel('instances') + if 0 < len(names) < 30: + ax[0].set_xticks(range(len(names))) + ax[0].set_xticklabels(names, rotation=90, fontsize=10) + else: + ax[0].set_xlabel('classes') + sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9) + sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9) # rectangles labels[:, 1:3] = 0.5 # center labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000 img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255) for cls, *box in labels[:1000]: - ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot + ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot ax[1].imshow(img) ax[1].axis('off') @@ -331,34 +386,58 @@ def plot_labels(labels, save_dir=Path(''), loggers=None): matplotlib.use('Agg') plt.close() - # loggers - for k, v in loggers.items() or {}: - if k == 'wandb' and v: - v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False) - -def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution() - # Plot hyperparameter evolution results in evolve.txt - with open(yaml_file) as f: - hyp = yaml.load(f, Loader=yaml.SafeLoader) - x = np.loadtxt('evolve.txt', ndmin=2) +def plot_evolve(evolve_csv='path/to/evolve.csv'): # from utils.plots import *; plot_evolve() + # Plot evolve.csv hyp evolution results + evolve_csv = Path(evolve_csv) + data = pd.read_csv(evolve_csv) + keys = [x.strip() for x in data.columns] + x = data.values f = fitness(x) - # weights = (f - f.min()) ** 2 # for weighted results + j = np.argmax(f) # max fitness index plt.figure(figsize=(10, 12), tight_layout=True) matplotlib.rc('font', **{'size': 8}) - for i, (k, v) in enumerate(hyp.items()): - y = x[:, i + 7] - # mu = (y * weights).sum() / weights.sum() # best weighted result - mu = y[f.argmax()] # best single result + print(f'Best results from row {j} of {evolve_csv}:') + for i, k in enumerate(keys[7:]): + v = x[:, 7 + i] + mu = v[j] # best single result plt.subplot(6, 5, i + 1) - plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none') + plt.scatter(v, f, c=hist2d(v, f, 20), cmap='viridis', alpha=.8, edgecolors='none') plt.plot(mu, f.max(), 'k+', markersize=15) - plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters + plt.title(f'{k} = {mu:.3g}', fontdict={'size': 9}) # limit to 40 characters if i % 5 != 0: plt.yticks([]) - print('%15s: %.3g' % (k, mu)) - plt.savefig('evolve.png', dpi=200) - print('\nPlot saved as evolve.png') + print(f'{k:>15}: {mu:.3g}') + f = evolve_csv.with_suffix('.png') # filename + plt.savefig(f, dpi=200) + plt.close() + print(f'Saved {f}') + + +def plot_results(file='path/to/results.csv', dir=''): + # Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv') + save_dir = Path(file).parent if file else Path(dir) + fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True) + ax = ax.ravel() + files = list(save_dir.glob('results*.csv')) + assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.' + for f in files: + try: + data = pd.read_csv(f) + s = [x.strip() for x in data.columns] + x = data.values[:, 0] + for i, j in enumerate([1, 2, 3, 4, 5, 8, 9, 10, 6, 7]): + y = data.values[:, j].astype('float') + # y[y == 0] = np.nan # don't show zero values + ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8) + ax[i].set_title(s[j], fontsize=12) + # if j in [8, 9, 10]: # share train and val loss y axes + # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5]) + except Exception as e: + LOGGER.info(f'Warning: Plotting error for {f}: {e}') + ax[1].legend() + fig.savefig(save_dir / 'results.png', dpi=200) + plt.close() def profile_idetection(start=0, stop=0, labels=(), save_dir=''): @@ -387,66 +466,24 @@ def profile_idetection(start=0, stop=0, labels=(), save_dir=''): else: a.remove() except Exception as e: - print('Warning: Plotting error for %s; %s' % (f, e)) - + print(f'Warning: Plotting error for {f}; {e}') ax[1].legend() plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200) -def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay() - # Plot training 'results*.txt', overlaying train and val losses - s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends - t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles - for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')): - results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T - n = results.shape[1] # number of rows - x = range(start, min(stop, n) if stop else n) - fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True) - ax = ax.ravel() - for i in range(5): - for j in [i, i + 5]: - y = results[j, x] - ax[i].plot(x, y, marker='.', label=s[j]) - # y_smooth = butter_lowpass_filtfilt(y) - # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j]) - - ax[i].set_title(t[i]) - ax[i].legend() - ax[i].set_ylabel(f) if i == 0 else None # add filename - fig.savefig(f.replace('.txt', '.png'), dpi=200) - - -def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''): - # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp') - fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True) - ax = ax.ravel() - s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall', - 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95'] - if bucket: - # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id] - files = ['results%g.txt' % x for x in id] - c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id) - os.system(c) - else: - files = list(Path(save_dir).glob('results*.txt')) - assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir) - for fi, f in enumerate(files): - try: - results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T - n = results.shape[1] # number of rows - x = range(start, min(stop, n) if stop else n) - for i in range(10): - y = results[i, x] - if i in [0, 1, 2, 5, 6, 7]: - y[y == 0] = np.nan # don't show zero loss values - # y /= y[0] # normalize - label = labels[fi] if len(labels) else f.stem - ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8) - ax[i].set_title(s[i]) - # if i in [5, 6, 7]: # share train and val loss y axes - # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5]) - except Exception as e: - print('Warning: Plotting error for %s; %s' % (f, e)) - - ax[1].legend() - fig.savefig(Path(save_dir) / 'results.png', dpi=200) +def save_one_box(xyxy, im, file=Path('im.jpg'), gain=1.02, pad=10, square=False, BGR=False, save=True): + # Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop + xyxy = torch.tensor(xyxy).view(-1, 4) + b = xyxy2xywh(xyxy) # boxes + if square: + b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square + b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad + xyxy = xywh2xyxy(b).long() + clip_coords(xyxy, im.shape) + crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)] + if save: + file.parent.mkdir(parents=True, exist_ok=True) # make directory + f = str(increment_path(file).with_suffix('.jpg')) + # cv2.imwrite(f, crop) # https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue + Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)).save(f, quality=95, subsampling=0) + return crop diff --git a/Y5/utils/torch_utils.py b/Y5/utils/torch_utils.py index 1b1cc20..d11df83 100755 --- a/Y5/utils/torch_utils.py +++ b/Y5/utils/torch_utils.py @@ -1,135 +1,155 @@ -# PyTorch utils +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +PyTorch utils +""" -import logging import math import os +import platform import subprocess import time +import warnings from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch -import torch.backends.cudnn as cudnn +import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F -import torchvision + +from utils.general import LOGGER, file_date, git_describe try: - import thop # for FLOPS computation + import thop # for FLOPs computation except ImportError: thop = None -logger = logging.getLogger(__name__) + +# Suppress PyTorch warnings +warnings.filterwarnings('ignore', message='User provided device_type of \'cuda\', but CUDA is not available. Disabling') @contextmanager def torch_distributed_zero_first(local_rank: int): - """ - Decorator to make all processes in distributed training wait for each local_master to do something. - """ + # Decorator to make all processes in distributed training wait for each local_master to do something if local_rank not in [-1, 0]: - torch.distributed.barrier() + dist.barrier(device_ids=[local_rank]) yield if local_rank == 0: - torch.distributed.barrier() + dist.barrier(device_ids=[0]) -def init_torch_seeds(seed=0): - # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html - torch.manual_seed(seed) - if seed == 0: # slower, more reproducible - cudnn.benchmark, cudnn.deterministic = False, True - else: # faster, less reproducible - cudnn.benchmark, cudnn.deterministic = True, False +def device_count(): + # Returns number of CUDA devices available. Safe version of torch.cuda.device_count(). Supports Linux and Windows + assert platform.system() in ('Linux', 'Windows'), 'device_count() only supported on Linux or Windows' + try: + cmd = 'nvidia-smi -L | wc -l' if platform.system() == 'Linux' else 'nvidia-smi -L | find /c /v ""' # Windows + return int(subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]) + except Exception: + return 0 -def git_describe(): - # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe - if Path('.git').exists(): - return subprocess.check_output('git describe --tags --long --always', shell=True).decode('utf-8')[:-1] - else: - return '' - - -def select_device(device='', batch_size=None): - # device = 'cpu' or '0' or '0,1,2,3' - s = f'YOLOv5 {git_describe()} torch {torch.__version__} ' # string - cpu = device.lower() == 'cpu' - if cpu: +def select_device(device='', batch_size=0, newline=True): + # device = None or 'cpu' or 0 or '0' or '0,1,2,3' + s = f'YOLOv5 🚀 {git_describe() or file_date()} Python-{platform.python_version()} torch-{torch.__version__} ' + device = str(device).strip().lower().replace('cuda:', '').replace('none', '') # to string, 'cuda:0' to '0' + cpu = device == 'cpu' + mps = device == 'mps' # Apple Metal Performance Shaders (MPS) + if cpu or mps: os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False elif device: # non-cpu device requested - os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable - assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability + os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable - must be before assert is_available() + assert torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', '')), \ + f"Invalid CUDA '--device {device}' requested, use '--device cpu' or pass valid CUDA device(s)" cuda = not cpu and torch.cuda.is_available() if cuda: - n = torch.cuda.device_count() - if n > 1 and batch_size: # check that batch_size is compatible with device_count + devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7 + n = len(devices) # device count + if n > 1 and batch_size > 0: # check batch_size is divisible by device_count assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}' - space = ' ' * len(s) - for i, d in enumerate(device.split(',') if device else range(n)): + space = ' ' * (len(s) + 1) + for i, d in enumerate(devices): p = torch.cuda.get_device_properties(i) - s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB + s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\n" # bytes to MB + elif mps: + s += 'MPS\n' else: s += 'CPU\n' - logger.info(s) # skip a line - return torch.device('cuda:0' if cuda else 'cpu') + if not newline: + s = s.rstrip() + LOGGER.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe + return torch.device('cuda:0' if cuda else 'mps' if mps else 'cpu') -def time_synchronized(): - # pytorch-accurate time +def time_sync(): + # PyTorch-accurate time if torch.cuda.is_available(): torch.cuda.synchronize() return time.time() -def profile(x, ops, n=100, device=None): - # profile a pytorch module or list of modules. Example usage: - # x = torch.randn(16, 3, 640, 640) # input +def profile(input, ops, n=10, device=None): + # YOLOv5 speed/memory/FLOPs profiler + # + # Usage: + # input = torch.randn(16, 3, 640, 640) # m1 = lambda x: x * torch.sigmoid(x) # m2 = nn.SiLU() - # profile(x, [m1, m2], n=100) # profile speed over 100 iterations + # profile(input, [m1, m2], n=100) # profile over 100 iterations - device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') - x = x.to(device) - x.requires_grad = True - print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '') - print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}") - for m in ops if isinstance(ops, list) else [ops]: - m = m.to(device) if hasattr(m, 'to') else m # device - m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type - dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward - try: - flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS - except: - flops = 0 + results = [] + if not isinstance(device, torch.device): + device = select_device(device) + print(f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}" + f"{'input':>24s}{'output':>24s}") - for _ in range(n): - t[0] = time_synchronized() - y = m(x) - t[1] = time_synchronized() + for x in input if isinstance(input, list) else [input]: + x = x.to(device) + x.requires_grad = True + for m in ops if isinstance(ops, list) else [ops]: + m = m.to(device) if hasattr(m, 'to') else m # device + m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m + tf, tb, t = 0, 0, [0, 0, 0] # dt forward, backward try: - _ = y.sum().backward() - t[2] = time_synchronized() - except: # no backward method - t[2] = float('nan') - dtf += (t[1] - t[0]) * 1000 / n # ms per op forward - dtb += (t[2] - t[1]) * 1000 / n # ms per op backward + flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs + except Exception: + flops = 0 - s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' - s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list' - p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters - print(f'{p:12.4g}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}') + try: + for _ in range(n): + t[0] = time_sync() + y = m(x) + t[1] = time_sync() + try: + _ = (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward() + t[2] = time_sync() + except Exception: # no backward method + # print(e) # for debug + t[2] = float('nan') + tf += (t[1] - t[0]) * 1000 / n # ms per op forward + tb += (t[2] - t[1]) * 1000 / n # ms per op backward + mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0 # (GB) + s_in, s_out = (tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' for x in (x, y)) # shapes + p = sum(x.numel() for x in m.parameters()) if isinstance(m, nn.Module) else 0 # parameters + print(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}') + results.append([p, flops, mem, tf, tb, s_in, s_out]) + except Exception as e: + print(e) + results.append(None) + torch.cuda.empty_cache() + return results def is_parallel(model): + # Returns True if model is of type DP or DDP return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) -def intersect_dicts(da, db, exclude=()): - # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values - return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape} +def de_parallel(model): + # De-parallelize a model: returns single-GPU model if model is of type DP or DDP + return model.module if is_parallel(model) else model def initialize_weights(model): @@ -140,7 +160,7 @@ def initialize_weights(model): elif t is nn.BatchNorm2d: m.eps = 1e-3 m.momentum = 0.03 - elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]: + elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]: m.inplace = True @@ -151,7 +171,7 @@ def find_modules(model, mclass=nn.Conv2d): def sparsity(model): # Return global model sparsity - a, b = 0., 0. + a, b = 0, 0 for p in model.parameters(): a += p.numel() b += (p == 0).sum() @@ -170,7 +190,7 @@ def prune(model, amount=0.3): def fuse_conv_and_bn(conv, bn): - # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ + # Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ fusedconv = nn.Conv2d(conv.in_channels, conv.out_channels, kernel_size=conv.kernel_size, @@ -179,12 +199,12 @@ def fuse_conv_and_bn(conv, bn): groups=conv.groups, bias=True).requires_grad_(False).to(conv.weight.device) - # prepare filters + # Prepare filters w_conv = conv.weight.clone().view(conv.out_channels, -1) w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) - fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size())) + fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape)) - # prepare spatial bias + # Prepare spatial bias b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) @@ -197,55 +217,36 @@ def model_info(model, verbose=False, img_size=640): n_p = sum(x.numel() for x in model.parameters()) # number parameters n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients if verbose: - print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma')) + print(f"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}") for i, (name, p) in enumerate(model.named_parameters()): name = name.replace('module_list.', '') print('%5g %40s %9s %12g %20s %10.3g %10.3g' % (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) - try: # FLOPS + try: # FLOPs from thop import profile stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32 img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input - flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS + flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPs img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float - fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS - except (ImportError, Exception): + fs = ', %.1f GFLOPs' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPs + except Exception: fs = '' - logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}") - - -def load_classifier(name='resnet101', n=2): - # Loads a pretrained model reshaped to n-class output - model = torchvision.models.__dict__[name](pretrained=True) - - # ResNet model properties - # input_size = [3, 224, 224] - # input_space = 'RGB' - # input_range = [0, 1] - # mean = [0.485, 0.456, 0.406] - # std = [0.229, 0.224, 0.225] - - # Reshape output to n classes - filters = model.fc.weight.shape[1] - model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True) - model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True) - model.fc.out_features = n - return model + name = Path(model.yaml_file).stem.replace('yolov5', 'YOLOv5') if hasattr(model, 'yaml_file') else 'Model' + LOGGER.info(f"{name} summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}") def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) - # scales img(bs,3,y,x) by ratio constrained to gs-multiple + # Scales img(bs,3,y,x) by ratio constrained to gs-multiple if ratio == 1.0: return img - else: - h, w = img.shape[2:] - s = (int(h * ratio), int(w * ratio)) # new size - img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize - if not same_shape: # pad/crop img - h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)] - return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean + h, w = img.shape[2:] + s = (int(h * ratio), int(w * ratio)) # new size + img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize + if not same_shape: # pad/crop img + h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w)) + return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean def copy_attr(a, b, include=(), exclude=()): @@ -257,23 +258,42 @@ def copy_attr(a, b, include=(), exclude=()): setattr(a, k, v) +class EarlyStopping: + # YOLOv5 simple early stopper + def __init__(self, patience=30): + self.best_fitness = 0.0 # i.e. mAP + self.best_epoch = 0 + self.patience = patience or float('inf') # epochs to wait after fitness stops improving to stop + self.possible_stop = False # possible stop may occur next epoch + + def __call__(self, epoch, fitness): + if fitness >= self.best_fitness: # >= 0 to allow for early zero-fitness stage of training + self.best_epoch = epoch + self.best_fitness = fitness + delta = epoch - self.best_epoch # epochs without improvement + self.possible_stop = delta >= (self.patience - 1) # possible stop may occur next epoch + stop = delta >= self.patience # stop training if patience exceeded + if stop: + LOGGER.info(f'Stopping training early as no improvement observed in last {self.patience} epochs. ' + f'Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\n' + f'To update EarlyStopping(patience={self.patience}) pass a new patience value, ' + f'i.e. `python train.py --patience 300` or use `--patience 0` to disable EarlyStopping.') + return stop + + class ModelEMA: - """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models - Keep a moving average of everything in the model state_dict (parameters and buffers). - This is intended to allow functionality like - https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage - A smoothed version of the weights is necessary for some training schemes to perform well. - This class is sensitive where it is initialized in the sequence of model init, - GPU assignment and distributed training wrappers. + """ Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models + Keeps a moving average of everything in the model state_dict (parameters and buffers) + For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage """ - def __init__(self, model, decay=0.9999, updates=0): + def __init__(self, model, decay=0.9999, tau=2000, updates=0): # Create EMA - self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA + self.ema = deepcopy(de_parallel(model)).eval() # FP32 EMA # if next(model.parameters()).device.type != 'cpu': # self.ema.half() # FP16 EMA self.updates = updates # number of EMA updates - self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs) + self.decay = lambda x: decay * (1 - math.exp(-x / tau)) # decay exponential ramp (to help early epochs) for p in self.ema.parameters(): p.requires_grad_(False) @@ -283,11 +303,11 @@ class ModelEMA: self.updates += 1 d = self.decay(self.updates) - msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict + msd = de_parallel(model).state_dict() # model state_dict for k, v in self.ema.state_dict().items(): if v.dtype.is_floating_point: v *= d - v += (1. - d) * msd[k].detach() + v += (1 - d) * msd[k].detach() def update_attr(self, model, include=(), exclude=('process_group', 'reducer')): # Update EMA attributes diff --git a/Y5_20221014/data/Argoverse.yaml b/Y5_20221014/data/Argoverse.yaml new file mode 100755 index 0000000..9d21296 --- /dev/null +++ b/Y5_20221014/data/Argoverse.yaml @@ -0,0 +1,67 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ by Argo AI +# Example usage: python train.py --data Argoverse.yaml +# parent +# ├── yolov5 +# └── datasets +# └── Argoverse ← downloads here (31.3 GB) + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/Argoverse # dataset root dir +train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images +val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images +test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview + +# Classes +nc: 8 # number of classes +names: ['person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign'] # class names + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import json + + from tqdm import tqdm + from utils.general import download, Path + + + def argoverse2yolo(set): + labels = {} + a = json.load(open(set, "rb")) + for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."): + img_id = annot['image_id'] + img_name = a['images'][img_id]['name'] + img_label_name = f'{img_name[:-3]}txt' + + cls = annot['category_id'] # instance class id + x_center, y_center, width, height = annot['bbox'] + x_center = (x_center + width / 2) / 1920.0 # offset and scale + y_center = (y_center + height / 2) / 1200.0 # offset and scale + width /= 1920.0 # scale + height /= 1200.0 # scale + + img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']] + if not img_dir.exists(): + img_dir.mkdir(parents=True, exist_ok=True) + + k = str(img_dir / img_label_name) + if k not in labels: + labels[k] = [] + labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n") + + for k in labels: + with open(k, "w") as f: + f.writelines(labels[k]) + + + # Download + dir = Path('../datasets/Argoverse') # dataset root dir + urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip'] + download(urls, dir=dir, delete=False) + + # Convert + annotations_dir = 'Argoverse-HD/annotations/' + (dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images' + for d in "train.json", "val.json": + argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels diff --git a/Y5_20221014/data/GlobalWheat2020.yaml b/Y5_20221014/data/GlobalWheat2020.yaml new file mode 100755 index 0000000..4c43693 --- /dev/null +++ b/Y5_20221014/data/GlobalWheat2020.yaml @@ -0,0 +1,54 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Global Wheat 2020 dataset http://www.global-wheat.com/ by University of Saskatchewan +# Example usage: python train.py --data GlobalWheat2020.yaml +# parent +# ├── yolov5 +# └── datasets +# └── GlobalWheat2020 ← downloads here (7.0 GB) + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/GlobalWheat2020 # dataset root dir +train: # train images (relative to 'path') 3422 images + - images/arvalis_1 + - images/arvalis_2 + - images/arvalis_3 + - images/ethz_1 + - images/rres_1 + - images/inrae_1 + - images/usask_1 +val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1) + - images/ethz_1 +test: # test images (optional) 1276 images + - images/utokyo_1 + - images/utokyo_2 + - images/nau_1 + - images/uq_1 + +# Classes +nc: 1 # number of classes +names: ['wheat_head'] # class names + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + from utils.general import download, Path + + + # Download + dir = Path(yaml['path']) # dataset root dir + urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip', + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip'] + download(urls, dir=dir) + + # Make Directories + for p in 'annotations', 'images', 'labels': + (dir / p).mkdir(parents=True, exist_ok=True) + + # Move + for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \ + 'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1': + (dir / p).rename(dir / 'images' / p) # move to /images + f = (dir / p).with_suffix('.json') # json file + if f.exists(): + f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations diff --git a/Y5_20221014/data/Objects365.yaml b/Y5_20221014/data/Objects365.yaml new file mode 100755 index 0000000..4cc9475 --- /dev/null +++ b/Y5_20221014/data/Objects365.yaml @@ -0,0 +1,114 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Objects365 dataset https://www.objects365.org/ by Megvii +# Example usage: python train.py --data Objects365.yaml +# parent +# ├── yolov5 +# └── datasets +# └── Objects365 ← downloads here (712 GB = 367G data + 345G zips) + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/Objects365 # dataset root dir +train: images/train # train images (relative to 'path') 1742289 images +val: images/val # val images (relative to 'path') 80000 images +test: # test images (optional) + +# Classes +nc: 365 # number of classes +names: ['Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup', + 'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book', + 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag', + 'Pillow', 'Boots', 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', 'Monitor/TV', + 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle', + 'Stool', 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Basket', 'Drum', 'Pen/Pencil', 'Bus', 'Wild Bird', + 'High Heels', 'Motorcycle', 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', 'Truck', + 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning', + 'Bed', 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', 'Air Conditioner', 'Knife', + 'Hockey Stick', 'Paddle', 'Pickup Truck', 'Fork', 'Traffic Sign', 'Balloon', 'Tripod', 'Dog', 'Spoon', 'Clock', + 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', 'Blackboard/Whiteboard', 'Napkin', 'Other Fish', + 'Orange/Tangerine', 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', 'Fan', + 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard', + 'Luggage', 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', 'Sports Car', 'Stop Sign', + 'Dessert', 'Scooter', 'Stroller', 'Crane', 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat', + 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', 'Elephant', 'Skateboard', 'Surfboard', + 'Gun', 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', 'Toilet', 'Kite', 'Strawberry', + 'Other Balls', 'Shovel', 'Pepper', 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks', + 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', 'Coffee Table', 'Side Table', 'Scissors', + 'Marker', 'Pie', 'Ladder', 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', 'Zebra', 'Grape', + 'Giraffe', 'Potato', 'Sausage', 'Tricycle', 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck', + 'Billiards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', 'Briefcase', 'Cucumber', 'Cigar/Cigarette', + 'Paint Brush', 'Pear', 'Heavy Truck', 'Hamburger', 'Extractor', 'Extension Cord', 'Tong', 'Tennis Racket', + 'Folder', 'American Football', 'earphone', 'Mask', 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine', + 'Slide', 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', 'Washing Machine/Drying Machine', + 'Chicken', 'Printer', 'Watermelon', 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hot-air balloon', + 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', 'Blender', 'Peach', 'Rice', 'Wallet/Purse', + 'Volleyball', 'Deer', 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', 'Golf Ball', + 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin', + 'Megaphone', 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', 'Sandwich', 'Nuts', + 'Speed Limit Sign', 'Induction Cooker', 'Broom', 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit', + 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', 'Notepaper', 'Cherry', 'Pliers', 'CD', + 'Pasta', 'Hammer', 'Cue', 'Avocado', 'Hamimelon', 'Flask', 'Mushroom', 'Screwdriver', 'Soap', 'Recorder', + 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', 'Tape Measure/Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips', + 'Steak', 'Crosswalk Sign', 'Stapler', 'Camel', 'Formula 1', 'Pomegranate', 'Dishwasher', 'Crab', + 'Hoverboard', 'Meat ball', 'Rice Cooker', 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal', + 'Butterfly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', 'Electric Drill', 'Hair Dryer', 'Egg tart', + 'Jellyfish', 'Treadmill', 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', 'Target', 'French', + 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell', + 'Scallop', 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Tennis paddle', 'Cosmetics Brush/Eyeliner Pencil', + 'Chainsaw', 'Eraser', 'Lobster', 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', 'Table Tennis'] + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + from tqdm import tqdm + + from utils.general import Path, check_requirements, download, np, xyxy2xywhn + + check_requirements(('pycocotools>=2.0',)) + from pycocotools.coco import COCO + + # Make Directories + dir = Path(yaml['path']) # dataset root dir + for p in 'images', 'labels': + (dir / p).mkdir(parents=True, exist_ok=True) + for q in 'train', 'val': + (dir / p / q).mkdir(parents=True, exist_ok=True) + + # Train, Val Splits + for split, patches in [('train', 50 + 1), ('val', 43 + 1)]: + print(f"Processing {split} in {patches} patches ...") + images, labels = dir / 'images' / split, dir / 'labels' / split + + # Download + url = f"https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/{split}/" + if split == 'train': + download([f'{url}zhiyuan_objv2_{split}.tar.gz'], dir=dir, delete=False) # annotations json + download([f'{url}patch{i}.tar.gz' for i in range(patches)], dir=images, curl=True, delete=False, threads=8) + elif split == 'val': + download([f'{url}zhiyuan_objv2_{split}.json'], dir=dir, delete=False) # annotations json + download([f'{url}images/v1/patch{i}.tar.gz' for i in range(15 + 1)], dir=images, curl=True, delete=False, threads=8) + download([f'{url}images/v2/patch{i}.tar.gz' for i in range(16, patches)], dir=images, curl=True, delete=False, threads=8) + + # Move + for f in tqdm(images.rglob('*.jpg'), desc=f'Moving {split} images'): + f.rename(images / f.name) # move to /images/{split} + + # Labels + coco = COCO(dir / f'zhiyuan_objv2_{split}.json') + names = [x["name"] for x in coco.loadCats(coco.getCatIds())] + for cid, cat in enumerate(names): + catIds = coco.getCatIds(catNms=[cat]) + imgIds = coco.getImgIds(catIds=catIds) + for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'): + width, height = im["width"], im["height"] + path = Path(im["file_name"]) # image filename + try: + with open(labels / path.with_suffix('.txt').name, 'a') as file: + annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None) + for a in coco.loadAnns(annIds): + x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner) + xyxy = np.array([x, y, x + w, y + h])[None] # pixels(1,4) + x, y, w, h = xyxy2xywhn(xyxy, w=width, h=height, clip=True)[0] # normalized and clipped + file.write(f"{cid} {x:.5f} {y:.5f} {w:.5f} {h:.5f}\n") + except Exception as e: + print(e) diff --git a/Y5_20221014/data/SKU-110K.yaml b/Y5_20221014/data/SKU-110K.yaml new file mode 100755 index 0000000..2acf34d --- /dev/null +++ b/Y5_20221014/data/SKU-110K.yaml @@ -0,0 +1,53 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 by Trax Retail +# Example usage: python train.py --data SKU-110K.yaml +# parent +# ├── yolov5 +# └── datasets +# └── SKU-110K ← downloads here (13.6 GB) + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/SKU-110K # dataset root dir +train: train.txt # train images (relative to 'path') 8219 images +val: val.txt # val images (relative to 'path') 588 images +test: test.txt # test images (optional) 2936 images + +# Classes +nc: 1 # number of classes +names: ['object'] # class names + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import shutil + from tqdm import tqdm + from utils.general import np, pd, Path, download, xyxy2xywh + + + # Download + dir = Path(yaml['path']) # dataset root dir + parent = Path(dir.parent) # download dir + urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz'] + download(urls, dir=parent, delete=False) + + # Rename directories + if dir.exists(): + shutil.rmtree(dir) + (parent / 'SKU110K_fixed').rename(dir) # rename dir + (dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir + + # Convert labels + names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names + for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv': + x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations + images, unique_images = x[:, 0], np.unique(x[:, 0]) + with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f: + f.writelines(f'./images/{s}\n' for s in unique_images) + for im in tqdm(unique_images, desc=f'Converting {dir / d}'): + cls = 0 # single-class dataset + with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f: + for r in x[images == im]: + w, h = r[6], r[7] # image width, height + xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance + f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label diff --git a/Y5_20221014/data/VOC.yaml b/Y5_20221014/data/VOC.yaml new file mode 100755 index 0000000..636ddc4 --- /dev/null +++ b/Y5_20221014/data/VOC.yaml @@ -0,0 +1,81 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC by University of Oxford +# Example usage: python train.py --data VOC.yaml +# parent +# ├── yolov5 +# └── datasets +# └── VOC ← downloads here (2.8 GB) + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/VOC +train: # train images (relative to 'path') 16551 images + - images/train2012 + - images/train2007 + - images/val2012 + - images/val2007 +val: # val images (relative to 'path') 4952 images + - images/test2007 +test: # test images (optional) + - images/test2007 + +# Classes +nc: 20 # number of classes +names: ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', + 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] # class names + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + import xml.etree.ElementTree as ET + + from tqdm import tqdm + from utils.general import download, Path + + + def convert_label(path, lb_path, year, image_id): + def convert_box(size, box): + dw, dh = 1. / size[0], 1. / size[1] + x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2] + return x * dw, y * dh, w * dw, h * dh + + in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml') + out_file = open(lb_path, 'w') + tree = ET.parse(in_file) + root = tree.getroot() + size = root.find('size') + w = int(size.find('width').text) + h = int(size.find('height').text) + + for obj in root.iter('object'): + cls = obj.find('name').text + if cls in yaml['names'] and not int(obj.find('difficult').text) == 1: + xmlbox = obj.find('bndbox') + bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')]) + cls_id = yaml['names'].index(cls) # class id + out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n') + + + # Download + dir = Path(yaml['path']) # dataset root dir + url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' + urls = [f'{url}VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images + f'{url}VOCtest_06-Nov-2007.zip', # 438MB, 4953 images + f'{url}VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images + download(urls, dir=dir / 'images', delete=False, curl=True, threads=3) + + # Convert + path = dir / 'images/VOCdevkit' + for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'): + imgs_path = dir / 'images' / f'{image_set}{year}' + lbs_path = dir / 'labels' / f'{image_set}{year}' + imgs_path.mkdir(exist_ok=True, parents=True) + lbs_path.mkdir(exist_ok=True, parents=True) + + with open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt') as f: + image_ids = f.read().strip().split() + for id in tqdm(image_ids, desc=f'{image_set}{year}'): + f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path + lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path + f.rename(imgs_path / f.name) # move image + convert_label(path, lb_path, year, id) # convert labels to YOLO format diff --git a/Y5_20221014/data/VisDrone.yaml b/Y5_20221014/data/VisDrone.yaml new file mode 100755 index 0000000..10337b4 --- /dev/null +++ b/Y5_20221014/data/VisDrone.yaml @@ -0,0 +1,61 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset by Tianjin University +# Example usage: python train.py --data VisDrone.yaml +# parent +# ├── yolov5 +# └── datasets +# └── VisDrone ← downloads here (2.3 GB) + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/VisDrone # dataset root dir +train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images +val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images +test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images + +# Classes +nc: 10 # number of classes +names: ['pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor'] + + +# Download script/URL (optional) --------------------------------------------------------------------------------------- +download: | + from utils.general import download, os, Path + + def visdrone2yolo(dir): + from PIL import Image + from tqdm import tqdm + + def convert_box(size, box): + # Convert VisDrone box to YOLO xywh box + dw = 1. / size[0] + dh = 1. / size[1] + return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh + + (dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory + pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}') + for f in pbar: + img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size + lines = [] + with open(f, 'r') as file: # read annotation.txt + for row in [x.split(',') for x in file.read().strip().splitlines()]: + if row[4] == '0': # VisDrone 'ignored regions' class 0 + continue + cls = int(row[5]) - 1 + box = convert_box(img_size, tuple(map(int, row[:4]))) + lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n") + with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl: + fl.writelines(lines) # write label.txt + + + # Download + dir = Path(yaml['path']) # dataset root dir + urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip', + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip', + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip', + 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip'] + download(urls, dir=dir, curl=True, threads=4) + + # Convert + for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev': + visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels diff --git a/Y5_20221014/data/coco.yaml b/Y5_20221014/data/coco.yaml new file mode 100755 index 0000000..0c0c4ad --- /dev/null +++ b/Y5_20221014/data/coco.yaml @@ -0,0 +1,45 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# COCO 2017 dataset http://cocodataset.org by Microsoft +# Example usage: python train.py --data coco.yaml +# parent +# ├── yolov5 +# └── datasets +# └── coco ← downloads here (20.1 GB) + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/coco # dataset root dir +train: train2017.txt # train images (relative to 'path') 118287 images +val: val2017.txt # val images (relative to 'path') 5000 images +test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794 + +# Classes +nc: 80 # number of classes +names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', + 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', + 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', + 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', + 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', + 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', + 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', + 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', + 'hair drier', 'toothbrush'] # class names + + +# Download script/URL (optional) +download: | + from utils.general import download, Path + + + # Download labels + segments = False # segment or box labels + dir = Path(yaml['path']) # dataset root dir + url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' + urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels + download(urls, dir=dir.parent) + + # Download data + urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images + 'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images + 'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional) + download(urls, dir=dir / 'images', threads=3) diff --git a/Y5_20221014/data/coco128.yaml b/Y5_20221014/data/coco128.yaml new file mode 100755 index 0000000..2517d20 --- /dev/null +++ b/Y5_20221014/data/coco128.yaml @@ -0,0 +1,30 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics +# Example usage: python train.py --data coco128.yaml +# parent +# ├── yolov5 +# └── datasets +# └── coco128 ← downloads here (7 MB) + + +# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] +path: ../datasets/coco128 # dataset root dir +train: images/train2017 # train images (relative to 'path') 128 images +val: images/train2017 # val images (relative to 'path') 128 images +test: # test images (optional) + +# Classes +nc: 80 # number of classes +names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', + 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', + 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', + 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', + 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', + 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', + 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', + 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', + 'hair drier', 'toothbrush'] # class names + + +# Download script/URL (optional) +download: https://ultralytics.com/assets/coco128.zip diff --git a/Y5_20221014/data/hyps/hyp.Objects365.yaml b/Y5_20221014/data/hyps/hyp.Objects365.yaml new file mode 100755 index 0000000..7497174 --- /dev/null +++ b/Y5_20221014/data/hyps/hyp.Objects365.yaml @@ -0,0 +1,34 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Hyperparameters for Objects365 training +# python train.py --weights yolov5m.pt --data Objects365.yaml --evolve +# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials + +lr0: 0.00258 +lrf: 0.17 +momentum: 0.779 +weight_decay: 0.00058 +warmup_epochs: 1.33 +warmup_momentum: 0.86 +warmup_bias_lr: 0.0711 +box: 0.0539 +cls: 0.299 +cls_pw: 0.825 +obj: 0.632 +obj_pw: 1.0 +iou_t: 0.2 +anchor_t: 3.44 +anchors: 3.2 +fl_gamma: 0.0 +hsv_h: 0.0188 +hsv_s: 0.704 +hsv_v: 0.36 +degrees: 0.0 +translate: 0.0902 +scale: 0.491 +shear: 0.0 +perspective: 0.0 +flipud: 0.0 +fliplr: 0.5 +mosaic: 1.0 +mixup: 0.0 +copy_paste: 0.0 diff --git a/Y5_20221014/data/hyps/hyp.VOC.yaml b/Y5_20221014/data/hyps/hyp.VOC.yaml new file mode 100755 index 0000000..0aa4e7d --- /dev/null +++ b/Y5_20221014/data/hyps/hyp.VOC.yaml @@ -0,0 +1,40 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Hyperparameters for VOC training +# python train.py --batch 128 --weights yolov5m6.pt --data VOC.yaml --epochs 50 --img 512 --hyp hyp.scratch-med.yaml --evolve +# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials + +# YOLOv5 Hyperparameter Evolution Results +# Best generation: 467 +# Last generation: 996 +# metrics/precision, metrics/recall, metrics/mAP_0.5, metrics/mAP_0.5:0.95, val/box_loss, val/obj_loss, val/cls_loss +# 0.87729, 0.85125, 0.91286, 0.72664, 0.0076739, 0.0042529, 0.0013865 + +lr0: 0.00334 +lrf: 0.15135 +momentum: 0.74832 +weight_decay: 0.00025 +warmup_epochs: 3.3835 +warmup_momentum: 0.59462 +warmup_bias_lr: 0.18657 +box: 0.02 +cls: 0.21638 +cls_pw: 0.5 +obj: 0.51728 +obj_pw: 0.67198 +iou_t: 0.2 +anchor_t: 3.3744 +fl_gamma: 0.0 +hsv_h: 0.01041 +hsv_s: 0.54703 +hsv_v: 0.27739 +degrees: 0.0 +translate: 0.04591 +scale: 0.75544 +shear: 0.0 +perspective: 0.0 +flipud: 0.0 +fliplr: 0.5 +mosaic: 0.85834 +mixup: 0.04266 +copy_paste: 0.0 +anchors: 3.412 diff --git a/Y5_20221014/data/hyps/hyp.scratch-high.yaml b/Y5_20221014/data/hyps/hyp.scratch-high.yaml new file mode 100755 index 0000000..123cc84 --- /dev/null +++ b/Y5_20221014/data/hyps/hyp.scratch-high.yaml @@ -0,0 +1,34 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Hyperparameters for high-augmentation COCO training from scratch +# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300 +# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials + +lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3) +lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf) +momentum: 0.937 # SGD momentum/Adam beta1 +weight_decay: 0.0005 # optimizer weight decay 5e-4 +warmup_epochs: 3.0 # warmup epochs (fractions ok) +warmup_momentum: 0.8 # warmup initial momentum +warmup_bias_lr: 0.1 # warmup initial bias lr +box: 0.05 # box loss gain +cls: 0.3 # cls loss gain +cls_pw: 1.0 # cls BCELoss positive_weight +obj: 0.7 # obj loss gain (scale with pixels) +obj_pw: 1.0 # obj BCELoss positive_weight +iou_t: 0.20 # IoU training threshold +anchor_t: 4.0 # anchor-multiple threshold +# anchors: 3 # anchors per output layer (0 to ignore) +fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) +hsv_h: 0.015 # image HSV-Hue augmentation (fraction) +hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) +hsv_v: 0.4 # image HSV-Value augmentation (fraction) +degrees: 0.0 # image rotation (+/- deg) +translate: 0.1 # image translation (+/- fraction) +scale: 0.9 # image scale (+/- gain) +shear: 0.0 # image shear (+/- deg) +perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 +flipud: 0.0 # image flip up-down (probability) +fliplr: 0.5 # image flip left-right (probability) +mosaic: 1.0 # image mosaic (probability) +mixup: 0.1 # image mixup (probability) +copy_paste: 0.1 # segment copy-paste (probability) diff --git a/Y5_20221014/data/hyps/hyp.scratch-low.yaml b/Y5_20221014/data/hyps/hyp.scratch-low.yaml new file mode 100755 index 0000000..b9ef1d5 --- /dev/null +++ b/Y5_20221014/data/hyps/hyp.scratch-low.yaml @@ -0,0 +1,34 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Hyperparameters for low-augmentation COCO training from scratch +# python train.py --batch 64 --cfg yolov5n6.yaml --weights '' --data coco.yaml --img 640 --epochs 300 --linear +# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials + +lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3) +lrf: 0.01 # final OneCycleLR learning rate (lr0 * lrf) +momentum: 0.937 # SGD momentum/Adam beta1 +weight_decay: 0.0005 # optimizer weight decay 5e-4 +warmup_epochs: 3.0 # warmup epochs (fractions ok) +warmup_momentum: 0.8 # warmup initial momentum +warmup_bias_lr: 0.1 # warmup initial bias lr +box: 0.05 # box loss gain +cls: 0.5 # cls loss gain +cls_pw: 1.0 # cls BCELoss positive_weight +obj: 1.0 # obj loss gain (scale with pixels) +obj_pw: 1.0 # obj BCELoss positive_weight +iou_t: 0.20 # IoU training threshold +anchor_t: 4.0 # anchor-multiple threshold +# anchors: 3 # anchors per output layer (0 to ignore) +fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) +hsv_h: 0.015 # image HSV-Hue augmentation (fraction) +hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) +hsv_v: 0.4 # image HSV-Value augmentation (fraction) +degrees: 0.0 # image rotation (+/- deg) +translate: 0.1 # image translation (+/- fraction) +scale: 0.5 # image scale (+/- gain) +shear: 0.0 # image shear (+/- deg) +perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 +flipud: 0.0 # image flip up-down (probability) +fliplr: 0.5 # image flip left-right (probability) +mosaic: 1.0 # image mosaic (probability) +mixup: 0.0 # image mixup (probability) +copy_paste: 0.0 # segment copy-paste (probability) diff --git a/Y5_20221014/data/hyps/hyp.scratch-med.yaml b/Y5_20221014/data/hyps/hyp.scratch-med.yaml new file mode 100755 index 0000000..d6867d7 --- /dev/null +++ b/Y5_20221014/data/hyps/hyp.scratch-med.yaml @@ -0,0 +1,34 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Hyperparameters for medium-augmentation COCO training from scratch +# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300 +# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials + +lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3) +lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf) +momentum: 0.937 # SGD momentum/Adam beta1 +weight_decay: 0.0005 # optimizer weight decay 5e-4 +warmup_epochs: 3.0 # warmup epochs (fractions ok) +warmup_momentum: 0.8 # warmup initial momentum +warmup_bias_lr: 0.1 # warmup initial bias lr +box: 0.05 # box loss gain +cls: 0.3 # cls loss gain +cls_pw: 1.0 # cls BCELoss positive_weight +obj: 0.7 # obj loss gain (scale with pixels) +obj_pw: 1.0 # obj BCELoss positive_weight +iou_t: 0.20 # IoU training threshold +anchor_t: 4.0 # anchor-multiple threshold +# anchors: 3 # anchors per output layer (0 to ignore) +fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) +hsv_h: 0.015 # image HSV-Hue augmentation (fraction) +hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) +hsv_v: 0.4 # image HSV-Value augmentation (fraction) +degrees: 0.0 # image rotation (+/- deg) +translate: 0.1 # image translation (+/- fraction) +scale: 0.9 # image scale (+/- gain) +shear: 0.0 # image shear (+/- deg) +perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 +flipud: 0.0 # image flip up-down (probability) +fliplr: 0.5 # image flip left-right (probability) +mosaic: 1.0 # image mosaic (probability) +mixup: 0.1 # image mixup (probability) +copy_paste: 0.0 # segment copy-paste (probability) diff --git a/Y5_20221014/data/images/bus.jpg b/Y5_20221014/data/images/bus.jpg new file mode 100755 index 0000000..b43e311 Binary files /dev/null and b/Y5_20221014/data/images/bus.jpg differ diff --git a/Y5/data/images/zidane.jpg b/Y5_20221014/data/images/zidane.jpg similarity index 100% rename from Y5/data/images/zidane.jpg rename to Y5_20221014/data/images/zidane.jpg diff --git a/Y5_20221014/data/only_bird.yaml b/Y5_20221014/data/only_bird.yaml new file mode 100755 index 0000000..2a0e9cd --- /dev/null +++ b/Y5_20221014/data/only_bird.yaml @@ -0,0 +1,24 @@ +# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC/ +# Train command: python train.py --data voc.yaml +# Default dataset location is next to /yolov5: +# /parent_folder +# /VOC +# /yolov5 + + +# download command/URL (optional) +#download: bash data/scripts/get_voc.sh + +# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/] +train: /data/DataManagement/Project/CAS_ProjectBird/CDB_ProjectBird/images/train/ # 16551 images +val: /data/DataManagement/Project/CAS_ProjectBird/CDB_ProjectBird/images/test/ # 4952 images + +#train: /data1/Hatcher/model/data_MPKFNet/data/VOC/VOCdevkit/VOCYOLO/images/train # 16551 images +#val: /data1/Hatcher/model/data_MPKFNet/data/VOC/VOCdevkit/VOCYOLO/images/val # 4952 images + +# number of classes +nc: 1 + +# class names +names: [ 'bird'] +#names: [ 'Construction' ] diff --git a/Y5_20221014/data/scripts/download_weights.sh b/Y5_20221014/data/scripts/download_weights.sh new file mode 100755 index 0000000..e9fa653 --- /dev/null +++ b/Y5_20221014/data/scripts/download_weights.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Download latest models from https://github.com/ultralytics/yolov5/releases +# Example usage: bash path/to/download_weights.sh +# parent +# └── yolov5 +# ├── yolov5s.pt ← downloads here +# ├── yolov5m.pt +# └── ... + +python - <= cls >= 0, f'incorrect class index {cls}' + + # Write YOLO label + if id not in shapes: + shapes[id] = Image.open(file).size + box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True) + with open((labels / id).with_suffix('.txt'), 'a') as f: + f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt + except Exception as e: + print(f'WARNING: skipping one label for {file}: {e}') + + + # Download manually from https://challenge.xviewdataset.org + dir = Path(yaml['path']) # dataset root dir + # urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels + # 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images + # 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels) + # download(urls, dir=dir, delete=False) + + # Convert labels + convert_labels(dir / 'xView_train.geojson') + + # Move images + images = Path(dir / 'images') + images.mkdir(parents=True, exist_ok=True) + Path(dir / 'train_images').rename(dir / 'images' / 'train') + Path(dir / 'val_images').rename(dir / 'images' / 'val') + + # Split + autosplit(dir / 'images' / 'train') diff --git a/Y5_20221014/models/__init__.py b/Y5_20221014/models/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/Y5_20221014/models/__pycache__/__init__.cpython-36.pyc b/Y5_20221014/models/__pycache__/__init__.cpython-36.pyc new file mode 100755 index 0000000..c169993 Binary files /dev/null and b/Y5_20221014/models/__pycache__/__init__.cpython-36.pyc differ diff --git a/Y5_20221014/models/__pycache__/__init__.cpython-37.pyc b/Y5_20221014/models/__pycache__/__init__.cpython-37.pyc new file mode 100755 index 0000000..7cc86e1 Binary files /dev/null and b/Y5_20221014/models/__pycache__/__init__.cpython-37.pyc differ diff --git a/Y5_20221014/models/__pycache__/__init__.cpython-38.pyc b/Y5_20221014/models/__pycache__/__init__.cpython-38.pyc new file mode 100755 index 0000000..3193edf Binary files /dev/null and b/Y5_20221014/models/__pycache__/__init__.cpython-38.pyc differ diff --git a/Y5_20221014/models/__pycache__/common.cpython-36.pyc b/Y5_20221014/models/__pycache__/common.cpython-36.pyc new file mode 100755 index 0000000..b23fa6e Binary files /dev/null and b/Y5_20221014/models/__pycache__/common.cpython-36.pyc differ diff --git a/Y5_20221014/models/__pycache__/common.cpython-37.pyc b/Y5_20221014/models/__pycache__/common.cpython-37.pyc new file mode 100755 index 0000000..c3724f4 Binary files /dev/null and b/Y5_20221014/models/__pycache__/common.cpython-37.pyc differ diff --git a/Y5_20221014/models/__pycache__/common.cpython-38.pyc b/Y5_20221014/models/__pycache__/common.cpython-38.pyc new file mode 100755 index 0000000..407713e Binary files /dev/null and b/Y5_20221014/models/__pycache__/common.cpython-38.pyc differ diff --git a/Y5_20221014/models/__pycache__/experimental.cpython-36.pyc b/Y5_20221014/models/__pycache__/experimental.cpython-36.pyc new file mode 100755 index 0000000..0b56adb Binary files /dev/null and b/Y5_20221014/models/__pycache__/experimental.cpython-36.pyc differ diff --git a/Y5_20221014/models/__pycache__/experimental.cpython-37.pyc b/Y5_20221014/models/__pycache__/experimental.cpython-37.pyc new file mode 100755 index 0000000..add642f Binary files /dev/null and b/Y5_20221014/models/__pycache__/experimental.cpython-37.pyc differ diff --git a/Y5_20221014/models/__pycache__/experimental.cpython-38.pyc b/Y5_20221014/models/__pycache__/experimental.cpython-38.pyc new file mode 100755 index 0000000..751503c Binary files /dev/null and b/Y5_20221014/models/__pycache__/experimental.cpython-38.pyc differ diff --git a/Y5_20221014/models/__pycache__/yolo.cpython-36.pyc b/Y5_20221014/models/__pycache__/yolo.cpython-36.pyc new file mode 100755 index 0000000..e21153c Binary files /dev/null and b/Y5_20221014/models/__pycache__/yolo.cpython-36.pyc differ diff --git a/Y5_20221014/models/__pycache__/yolo.cpython-37.pyc b/Y5_20221014/models/__pycache__/yolo.cpython-37.pyc new file mode 100755 index 0000000..f7aa26e Binary files /dev/null and b/Y5_20221014/models/__pycache__/yolo.cpython-37.pyc differ diff --git a/Y5_20221014/models/__pycache__/yolo.cpython-38.pyc b/Y5_20221014/models/__pycache__/yolo.cpython-38.pyc new file mode 100755 index 0000000..4f94aa9 Binary files /dev/null and b/Y5_20221014/models/__pycache__/yolo.cpython-38.pyc differ diff --git a/Y5_20221014/models/common.py b/Y5_20221014/models/common.py new file mode 100755 index 0000000..66467a0 --- /dev/null +++ b/Y5_20221014/models/common.py @@ -0,0 +1,738 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Common modules +""" + +import json +import math +import platform +import warnings +from collections import OrderedDict, namedtuple +from copy import copy +from pathlib import Path + +import cv2 +import numpy as np +import pandas as pd +import requests +import torch +import torch.nn as nn +import yaml +from PIL import Image +from torch.cuda import amp + +from utils.dataloaders import exif_transpose, letterbox +from utils.general import (LOGGER, check_requirements, check_suffix, check_version, colorstr, increment_path, + make_divisible, non_max_suppression, scale_coords, xywh2xyxy, xyxy2xywh) +from utils.plots import Annotator, colors, save_one_box +from utils.torch_utils import copy_attr, time_sync + + +def autopad(k, p=None): # kernel, padding + # Pad to 'same' + if p is None: + p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad + return p + + +class Conv(nn.Module): + # Standard convolution + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False) + self.bn = nn.BatchNorm2d(c2) + self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity()) + + def forward(self, x): + return self.act(self.bn(self.conv(x))) + + def forward_fuse(self, x): + return self.act(self.conv(x)) + + +class DWConv(Conv): + # Depth-wise convolution class + def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act) + + +class DWConvTranspose2d(nn.ConvTranspose2d): + # Depth-wise transpose convolution class + def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0): # ch_in, ch_out, kernel, stride, padding, padding_out + super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2)) + + +class TransformerLayer(nn.Module): + # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance) + def __init__(self, c, num_heads): + super().__init__() + self.q = nn.Linear(c, c, bias=False) + self.k = nn.Linear(c, c, bias=False) + self.v = nn.Linear(c, c, bias=False) + self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads) + self.fc1 = nn.Linear(c, c, bias=False) + self.fc2 = nn.Linear(c, c, bias=False) + + def forward(self, x): + x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x + x = self.fc2(self.fc1(x)) + x + return x + + +class TransformerBlock(nn.Module): + # Vision Transformer https://arxiv.org/abs/2010.11929 + def __init__(self, c1, c2, num_heads, num_layers): + super().__init__() + self.conv = None + if c1 != c2: + self.conv = Conv(c1, c2) + self.linear = nn.Linear(c2, c2) # learnable position embedding + self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers))) + self.c2 = c2 + + def forward(self, x): + if self.conv is not None: + x = self.conv(x) + b, _, w, h = x.shape + p = x.flatten(2).permute(2, 0, 1) + return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h) + + +class Bottleneck(nn.Module): + # Standard bottleneck + def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_, c2, 3, 1, g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x): + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) + + +class BottleneckCSP(nn.Module): + # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) + self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) + self.cv4 = Conv(2 * c_, c2, 1, 1) + self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) + self.act = nn.SiLU() + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) + + def forward(self, x): + y1 = self.cv3(self.m(self.cv1(x))) + y2 = self.cv2(x) + return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1)))) + + +class CrossConv(nn.Module): + # Cross Convolution Downsample + def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): + # ch_in, ch_out, kernel, stride, groups, expansion, shortcut + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, (1, k), (1, s)) + self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x): + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) + + +class C3(nn.Module): + # CSP Bottleneck with 3 convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c1, c_, 1, 1) + self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2) + self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) + + def forward(self, x): + return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)) + + +class C3x(C3): + # C3 module with cross-convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n))) + + +class C3TR(C3): + # C3 module with TransformerBlock() + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = TransformerBlock(c_, c_, 4, n) + + +class C3SPP(C3): + # C3 module with SPP() + def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) + self.m = SPP(c_, c_, k) + + +class C3Ghost(C3): + # C3 module with GhostBottleneck() + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): + super().__init__(c1, c2, n, shortcut, g, e) + c_ = int(c2 * e) # hidden channels + self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n))) + + +class SPP(nn.Module): + # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729 + def __init__(self, c1, c2, k=(5, 9, 13)): + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) + self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) + + def forward(self, x): + x = self.cv1(x) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning + return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) + + +class SPPF(nn.Module): + # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher + def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13)) + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_ * 4, c2, 1, 1) + self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) + + def forward(self, x): + x = self.cv1(x) + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning + y1 = self.m(x) + y2 = self.m(y1) + return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1)) + + +class Focus(nn.Module): + # Focus wh information into c-space + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.conv = Conv(c1 * 4, c2, k, s, p, g, act) + # self.contract = Contract(gain=2) + + def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) + return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1)) + # return self.conv(self.contract(x)) + + +class GhostConv(nn.Module): + # Ghost Convolution https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups + super().__init__() + c_ = c2 // 2 # hidden channels + self.cv1 = Conv(c1, c_, k, s, None, g, act) + self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) + + def forward(self, x): + y = self.cv1(x) + return torch.cat((y, self.cv2(y)), 1) + + +class GhostBottleneck(nn.Module): + # Ghost Bottleneck https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride + super().__init__() + c_ = c2 // 2 + self.conv = nn.Sequential( + GhostConv(c1, c_, 1, 1), # pw + DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw + GhostConv(c_, c2, 1, 1, act=False)) # pw-linear + self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, + act=False)) if s == 2 else nn.Identity() + + def forward(self, x): + return self.conv(x) + self.shortcut(x) + + +class Contract(nn.Module): + # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40) + def __init__(self, gain=2): + super().__init__() + self.gain = gain + + def forward(self, x): + b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain' + s = self.gain + x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2) + x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40) + return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40) + + +class Expand(nn.Module): + # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160) + def __init__(self, gain=2): + super().__init__() + self.gain = gain + + def forward(self, x): + b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain' + s = self.gain + x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80) + x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2) + return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160) + + +class Concat(nn.Module): + # Concatenate a list of tensors along dimension + def __init__(self, dimension=1): + super().__init__() + self.d = dimension + + def forward(self, x): + return torch.cat(x, self.d) + + +class DetectMultiBackend(nn.Module): + # YOLOv5 MultiBackend class for python inference on various backends + def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False): + # Usage: + # PyTorch: weights = *.pt + # TorchScript: *.torchscript + # ONNX Runtime: *.onnx + # ONNX OpenCV DNN: *.onnx with --dnn + # OpenVINO: *.xml + # CoreML: *.mlmodel + # TensorRT: *.engine + # TensorFlow SavedModel: *_saved_model + # TensorFlow GraphDef: *.pb + # TensorFlow Lite: *.tflite + # TensorFlow Edge TPU: *_edgetpu.tflite + from models.experimental import attempt_download, attempt_load # scoped to avoid circular import + + super().__init__() + w = str(weights[0] if isinstance(weights, list) else weights) + pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs = self.model_type(w) # get backend + w = attempt_download(w) # download if not local + fp16 &= (pt or jit or onnx or engine) and device.type != 'cpu' # FP16 + stride, names = 32, [f'class{i}' for i in range(1000)] # assign defaults + if data: # assign class names (optional) + with open(data, errors='ignore') as f: + names = yaml.safe_load(f)['names'] + + if pt: # PyTorch + model = attempt_load(weights if isinstance(weights, list) else w, device=device) + stride = max(int(model.stride.max()), 32) # model stride + names = model.module.names if hasattr(model, 'module') else model.names # get class names + model.half() if fp16 else model.float() + self.model = model # explicitly assign for to(), cpu(), cuda(), half() + elif jit: # TorchScript + LOGGER.info(f'Loading {w} for TorchScript inference...') + extra_files = {'config.txt': ''} # model metadata + model = torch.jit.load(w, _extra_files=extra_files) + model.half() if fp16 else model.float() + if extra_files['config.txt']: + d = json.loads(extra_files['config.txt']) # extra_files dict + stride, names = int(d['stride']), d['names'] + elif dnn: # ONNX OpenCV DNN + LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...') + check_requirements(('opencv-python>=4.5.4',)) + net = cv2.dnn.readNetFromONNX(w) + elif onnx: # ONNX Runtime + LOGGER.info(f'Loading {w} for ONNX Runtime inference...') + cuda = torch.cuda.is_available() + check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime')) + import onnxruntime + providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider'] + session = onnxruntime.InferenceSession(w, providers=providers) + meta = session.get_modelmeta().custom_metadata_map # metadata + if 'stride' in meta: + stride, names = int(meta['stride']), eval(meta['names']) + elif xml: # OpenVINO + LOGGER.info(f'Loading {w} for OpenVINO inference...') + check_requirements(('openvino',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/ + from openvino.runtime import Core + ie = Core() + if not Path(w).is_file(): # if not *.xml + w = next(Path(w).glob('*.xml')) # get *.xml file from *_openvino_model dir + network = ie.read_model(model=w, weights=Path(w).with_suffix('.bin')) + executable_network = ie.compile_model(model=network, device_name="CPU") + output_layer = next(iter(executable_network.outputs)) + meta = Path(w).with_suffix('.yaml') + if meta.exists(): + stride, names = self._load_metadata(meta) # load metadata + elif engine: # TensorRT + LOGGER.info(f'Loading {w} for TensorRT inference...') + import tensorrt as trt # https://developer.nvidia.com/nvidia-tensorrt-download + check_version(trt.__version__, '7.0.0', hard=True) # require tensorrt>=7.0.0 + Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr')) + logger = trt.Logger(trt.Logger.INFO) + with open(w, 'rb') as f, trt.Runtime(logger) as runtime: + model = runtime.deserialize_cuda_engine(f.read()) + bindings = OrderedDict() + fp16 = False # default updated below + for index in range(model.num_bindings): + name = model.get_binding_name(index) + dtype = trt.nptype(model.get_binding_dtype(index)) + shape = tuple(model.get_binding_shape(index)) + data = torch.from_numpy(np.empty(shape, dtype=np.dtype(dtype))).to(device) + bindings[name] = Binding(name, dtype, shape, data, int(data.data_ptr())) + if model.binding_is_input(index) and dtype == np.float16: + fp16 = True + binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items()) + context = model.create_execution_context() + batch_size = bindings['images'].shape[0] + elif coreml: # CoreML + LOGGER.info(f'Loading {w} for CoreML inference...') + import coremltools as ct + model = ct.models.MLModel(w) + else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU) + if saved_model: # SavedModel + LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...') + import tensorflow as tf + keras = False # assume TF1 saved_model + model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w) + elif pb: # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt + LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...') + import tensorflow as tf + + def wrap_frozen_graph(gd, inputs, outputs): + x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped + ge = x.graph.as_graph_element + return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs)) + + gd = tf.Graph().as_graph_def() # graph_def + with open(w, 'rb') as f: + gd.ParseFromString(f.read()) + frozen_func = wrap_frozen_graph(gd, inputs="x:0", outputs="Identity:0") + elif tflite or edgetpu: # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python + try: # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu + from tflite_runtime.interpreter import Interpreter, load_delegate + except ImportError: + import tensorflow as tf + Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate, + if edgetpu: # Edge TPU https://coral.ai/software/#edgetpu-runtime + LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...') + delegate = { + 'Linux': 'libedgetpu.so.1', + 'Darwin': 'libedgetpu.1.dylib', + 'Windows': 'edgetpu.dll'}[platform.system()] + interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)]) + else: # Lite + LOGGER.info(f'Loading {w} for TensorFlow Lite inference...') + interpreter = Interpreter(model_path=w) # load TFLite model + interpreter.allocate_tensors() # allocate + input_details = interpreter.get_input_details() # inputs + output_details = interpreter.get_output_details() # outputs + elif tfjs: + raise Exception('ERROR: YOLOv5 TF.js inference is not supported') + self.__dict__.update(locals()) # assign all variables to self + + def forward(self, im, augment=False, visualize=False, val=False): + # YOLOv5 MultiBackend inference + b, ch, h, w = im.shape # batch, channel, height, width + if self.pt: # PyTorch + y = self.model(im, augment=augment, visualize=visualize)[0] + elif self.jit: # TorchScript + y = self.model(im)[0] + elif self.dnn: # ONNX OpenCV DNN + im = im.cpu().numpy() # torch to numpy + self.net.setInput(im) + y = self.net.forward() + elif self.onnx: # ONNX Runtime + im = im.cpu().numpy() # torch to numpy + y = self.session.run([self.session.get_outputs()[0].name], {self.session.get_inputs()[0].name: im})[0] + elif self.xml: # OpenVINO + im = im.cpu().numpy() # FP32 + y = self.executable_network([im])[self.output_layer] + elif self.engine: # TensorRT + assert im.shape == self.bindings['images'].shape, (im.shape, self.bindings['images'].shape) + self.binding_addrs['images'] = int(im.data_ptr()) + self.context.execute_v2(list(self.binding_addrs.values())) + y = self.bindings['output'].data + elif self.coreml: # CoreML + im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3) + im = Image.fromarray((im[0] * 255).astype('uint8')) + # im = im.resize((192, 320), Image.ANTIALIAS) + y = self.model.predict({'image': im}) # coordinates are xywh normalized + if 'confidence' in y: + box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels + conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float) + y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1) + else: + k = 'var_' + str(sorted(int(k.replace('var_', '')) for k in y)[-1]) # output key + y = y[k] # output + else: # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU) + im = im.permute(0, 2, 3, 1).cpu().numpy() # torch BCHW to numpy BHWC shape(1,320,192,3) + if self.saved_model: # SavedModel + y = (self.model(im, training=False) if self.keras else self.model(im)).numpy() + elif self.pb: # GraphDef + y = self.frozen_func(x=self.tf.constant(im)).numpy() + else: # Lite or Edge TPU + input, output = self.input_details[0], self.output_details[0] + int8 = input['dtype'] == np.uint8 # is TFLite quantized uint8 model + if int8: + scale, zero_point = input['quantization'] + im = (im / scale + zero_point).astype(np.uint8) # de-scale + self.interpreter.set_tensor(input['index'], im) + self.interpreter.invoke() + y = self.interpreter.get_tensor(output['index']) + if int8: + scale, zero_point = output['quantization'] + y = (y.astype(np.float32) - zero_point) * scale # re-scale + y[..., :4] *= [w, h, w, h] # xywh normalized to pixels + + if isinstance(y, np.ndarray): + y = torch.tensor(y, device=self.device) + return (y, []) if val else y + + def warmup(self, imgsz=(1, 3, 640, 640)): + # Warmup model by running inference once + warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb + if any(warmup_types) and self.device.type != 'cpu': + im = torch.zeros(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device) # input + for _ in range(2 if self.jit else 1): # + self.forward(im) # warmup + + @staticmethod + def model_type(p='path/to/model.pt'): + # Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx + from export import export_formats + suffixes = list(export_formats().Suffix) + ['.xml'] # export suffixes + check_suffix(p, suffixes) # checks + p = Path(p).name # eliminate trailing separators + pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, xml2 = (s in p for s in suffixes) + xml |= xml2 # *_openvino_model or *.xml + tflite &= not edgetpu # *.tflite + return pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs + + @staticmethod + def _load_metadata(f='path/to/meta.yaml'): + # Load metadata from meta.yaml if it exists + with open(f, errors='ignore') as f: + d = yaml.safe_load(f) + return d['stride'], d['names'] # assign stride, names + + +class AutoShape(nn.Module): + # YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS + conf = 0.25 # NMS confidence threshold + iou = 0.45 # NMS IoU threshold + agnostic = False # NMS class-agnostic + multi_label = False # NMS multiple labels per box + classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs + max_det = 1000 # maximum number of detections per image + amp = False # Automatic Mixed Precision (AMP) inference + + def __init__(self, model, verbose=True): + super().__init__() + if verbose: + LOGGER.info('Adding AutoShape... ') + copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=()) # copy attributes + self.dmb = isinstance(model, DetectMultiBackend) # DetectMultiBackend() instance + self.pt = not self.dmb or model.pt # PyTorch model + self.model = model.eval() + + def _apply(self, fn): + # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers + self = super()._apply(fn) + if self.pt: + m = self.model.model.model[-1] if self.dmb else self.model.model[-1] # Detect() + m.stride = fn(m.stride) + m.grid = list(map(fn, m.grid)) + if isinstance(m.anchor_grid, list): + m.anchor_grid = list(map(fn, m.anchor_grid)) + return self + + @torch.no_grad() + def forward(self, imgs, size=640, augment=False, profile=False): + # Inference from various sources. For height=640, width=1280, RGB images example inputs are: + # file: imgs = 'data/images/zidane.jpg' # str or PosixPath + # URI: = 'https://ultralytics.com/images/zidane.jpg' + # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3) + # PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3) + # numpy: = np.zeros((640,1280,3)) # HWC + # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values) + # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images + + t = [time_sync()] + p = next(self.model.parameters()) if self.pt else torch.zeros(1, device=self.model.device) # for device, type + autocast = self.amp and (p.device.type != 'cpu') # Automatic Mixed Precision (AMP) inference + if isinstance(imgs, torch.Tensor): # torch + with amp.autocast(autocast): + return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference + + # Pre-process + n, imgs = (len(imgs), list(imgs)) if isinstance(imgs, (list, tuple)) else (1, [imgs]) # number, list of images + shape0, shape1, files = [], [], [] # image and inference shapes, filenames + for i, im in enumerate(imgs): + f = f'image{i}' # filename + if isinstance(im, (str, Path)): # filename or uri + im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im + im = np.asarray(exif_transpose(im)) + elif isinstance(im, Image.Image): # PIL Image + im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f + files.append(Path(f).with_suffix('.jpg').name) + if im.shape[0] < 5: # image in CHW + im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1) + im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3) # enforce 3ch input + s = im.shape[:2] # HWC + shape0.append(s) # image shape + g = (size / max(s)) # gain + shape1.append([y * g for y in s]) + imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update + shape1 = [make_divisible(x, self.stride) if self.pt else size for x in np.array(shape1).max(0)] # inf shape + x = [letterbox(im, shape1, auto=False)[0] for im in imgs] # pad + x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2))) # stack and BHWC to BCHW + x = torch.from_numpy(x).to(p.device).type_as(p) / 255 # uint8 to fp16/32 + t.append(time_sync()) + + with amp.autocast(autocast): + # Inference + y = self.model(x, augment, profile) # forward + t.append(time_sync()) + + # Post-process + y = non_max_suppression(y if self.dmb else y[0], + self.conf, + self.iou, + self.classes, + self.agnostic, + self.multi_label, + max_det=self.max_det) # NMS + for i in range(n): + scale_coords(shape1, y[i][:, :4], shape0[i]) + + t.append(time_sync()) + return Detections(imgs, y, files, t, self.names, x.shape) + + +class Detections: + # YOLOv5 detections class for inference results + def __init__(self, imgs, pred, files, times=(0, 0, 0, 0), names=None, shape=None): + super().__init__() + d = pred[0].device # device + gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in imgs] # normalizations + self.imgs = imgs # list of images as numpy arrays + self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls) + self.names = names # class names + self.files = files # image filenames + self.times = times # profiling times + self.xyxy = pred # xyxy pixels + self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels + self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized + self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized + self.n = len(self.pred) # number of images (batch size) + self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms) + self.s = shape # inference BCHW shape + + def display(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')): + crops = [] + for i, (im, pred) in enumerate(zip(self.imgs, self.pred)): + s = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string + if pred.shape[0]: + for c in pred[:, -1].unique(): + n = (pred[:, -1] == c).sum() # detections per class + s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string + if show or save or render or crop: + annotator = Annotator(im, example=str(self.names)) + for *box, conf, cls in reversed(pred): # xyxy, confidence, class + label = f'{self.names[int(cls)]} {conf:.2f}' + if crop: + file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None + crops.append({ + 'box': box, + 'conf': conf, + 'cls': cls, + 'label': label, + 'im': save_one_box(box, im, file=file, save=save)}) + else: # all others + annotator.box_label(box, label if labels else '', color=colors(cls)) + im = annotator.im + else: + s += '(no detections)' + + im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np + if pprint: + print(s.rstrip(', ')) + if show: + im.show(self.files[i]) # show + if save: + f = self.files[i] + im.save(save_dir / f) # save + if i == self.n - 1: + LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}") + if render: + self.imgs[i] = np.asarray(im) + if crop: + if save: + LOGGER.info(f'Saved results to {save_dir}\n') + return crops + + def print(self): + self.display(pprint=True) # print results + print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' % self.t) + + def show(self, labels=True): + self.display(show=True, labels=labels) # show results + + def save(self, labels=True, save_dir='runs/detect/exp'): + save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir + self.display(save=True, labels=labels, save_dir=save_dir) # save results + + def crop(self, save=True, save_dir='runs/detect/exp'): + save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) if save else None + return self.display(crop=True, save=save, save_dir=save_dir) # crop results + + def render(self, labels=True): + self.display(render=True, labels=labels) # render results + return self.imgs + + def pandas(self): + # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0]) + new = copy(self) # return copy + ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns + cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns + for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]): + a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update + setattr(new, k, [pd.DataFrame(x, columns=c) for x in a]) + return new + + def tolist(self): + # return a list of Detections objects, i.e. 'for result in results.tolist():' + r = range(self.n) # iterable + x = [Detections([self.imgs[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r] + # for d in x: + # for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']: + # setattr(d, k, getattr(d, k)[0]) # pop out of list + return x + + def __len__(self): + return self.n # override len(results) + + def __str__(self): + self.print() # override print(results) + return '' + + +class Classify(nn.Module): + # Classification head, i.e. x(b,c1,20,20) to x(b,c2) + def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1) + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1) + self.flat = nn.Flatten() + + def forward(self, x): + z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list + return self.flat(self.conv(z)) # flatten to x(b,c2) diff --git a/Y5_20221014/models/experimental.py b/Y5_20221014/models/experimental.py new file mode 100755 index 0000000..db8e5b8 --- /dev/null +++ b/Y5_20221014/models/experimental.py @@ -0,0 +1,104 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Experimental modules +""" +import math + +import numpy as np +import torch +import torch.nn as nn + +from models.common import Conv +from utils.downloads import attempt_download + + +class Sum(nn.Module): + # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 + def __init__(self, n, weight=False): # n: number of inputs + super().__init__() + self.weight = weight # apply weights boolean + self.iter = range(n - 1) # iter object + if weight: + self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights + + def forward(self, x): + y = x[0] # no weight + if self.weight: + w = torch.sigmoid(self.w) * 2 + for i in self.iter: + y = y + x[i + 1] * w[i] + else: + for i in self.iter: + y = y + x[i + 1] + return y + + +class MixConv2d(nn.Module): + # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595 + def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy + super().__init__() + n = len(k) # number of convolutions + if equal_ch: # equal c_ per group + i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices + c_ = [(i == g).sum() for g in range(n)] # intermediate channels + else: # equal weight.numel() per group + b = [c2] + [0] * n + a = np.eye(n + 1, n, k=-1) + a -= np.roll(a, 1, axis=1) + a *= np.array(k) ** 2 + a[0] = 1 + c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b + + self.m = nn.ModuleList([ + nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)]) + self.bn = nn.BatchNorm2d(c2) + self.act = nn.SiLU() + + def forward(self, x): + return self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) + + +class Ensemble(nn.ModuleList): + # Ensemble of models + def __init__(self): + super().__init__() + + def forward(self, x, augment=False, profile=False, visualize=False): + y = [module(x, augment, profile, visualize)[0] for module in self] + # y = torch.stack(y).max(0)[0] # max ensemble + # y = torch.stack(y).mean(0) # mean ensemble + y = torch.cat(y, 1) # nms ensemble + return y, None # inference, train output + + +def attempt_load(weights, device=None, inplace=True, fuse=True): + # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a + from models.yolo import Detect, Model + + model = Ensemble() + for w in weights if isinstance(weights, list) else [weights]: + ckpt = torch.load(attempt_download(w), map_location='cpu') # load + ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model + model.append(ckpt.fuse().eval() if fuse else ckpt.eval()) # fused or un-fused model in eval mode + + # Compatibility updates + for m in model.modules(): + t = type(m) + if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model): + m.inplace = inplace # torch 1.7.0 compatibility + if t is Detect and not isinstance(m.anchor_grid, list): + delattr(m, 'anchor_grid') + setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl) + elif t is Conv: + m._non_persistent_buffers_set = set() # torch 1.6.0 compatibility + elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'): + m.recompute_scale_factor = None # torch 1.11.0 compatibility + + if len(model) == 1: + return model[-1] # return model + print(f'Ensemble created with {weights}\n') + for k in 'names', 'nc', 'yaml': + setattr(model, k, getattr(model[0], k)) + model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride + assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}' + return model # return ensemble diff --git a/Y5_20221014/models/hub/anchors.yaml b/Y5_20221014/models/hub/anchors.yaml new file mode 100755 index 0000000..e4d7beb --- /dev/null +++ b/Y5_20221014/models/hub/anchors.yaml @@ -0,0 +1,59 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Default anchors for COCO data + + +# P5 ------------------------------------------------------------------------------------------------------------------- +# P5-640: +anchors_p5_640: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + + +# P6 ------------------------------------------------------------------------------------------------------------------- +# P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387 +anchors_p6_640: + - [9,11, 21,19, 17,41] # P3/8 + - [43,32, 39,70, 86,64] # P4/16 + - [65,131, 134,130, 120,265] # P5/32 + - [282,180, 247,354, 512,387] # P6/64 + +# P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792 +anchors_p6_1280: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187 +anchors_p6_1920: + - [28,41, 67,59, 57,141] # P3/8 + - [144,103, 129,227, 270,205] # P4/16 + - [209,452, 455,396, 358,812] # P5/32 + - [653,922, 1109,570, 1387,1187] # P6/64 + + +# P7 ------------------------------------------------------------------------------------------------------------------- +# P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372 +anchors_p7_640: + - [11,11, 13,30, 29,20] # P3/8 + - [30,46, 61,38, 39,92] # P4/16 + - [78,80, 146,66, 79,163] # P5/32 + - [149,150, 321,143, 157,303] # P6/64 + - [257,402, 359,290, 524,372] # P7/128 + +# P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818 +anchors_p7_1280: + - [19,22, 54,36, 32,77] # P3/8 + - [70,83, 138,71, 75,173] # P4/16 + - [165,159, 148,334, 375,151] # P5/32 + - [334,317, 251,626, 499,474] # P6/64 + - [750,326, 534,814, 1079,818] # P7/128 + +# P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227 +anchors_p7_1920: + - [29,34, 81,55, 47,115] # P3/8 + - [105,124, 207,107, 113,259] # P4/16 + - [247,238, 222,500, 563,227] # P5/32 + - [501,476, 376,939, 749,711] # P6/64 + - [1126,489, 801,1222, 1618,1227] # P7/128 diff --git a/Y5_20221014/models/hub/yolov3-spp.yaml b/Y5_20221014/models/hub/yolov3-spp.yaml new file mode 100755 index 0000000..c669821 --- /dev/null +++ b/Y5_20221014/models/hub/yolov3-spp.yaml @@ -0,0 +1,51 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# darknet53 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [32, 3, 1]], # 0 + [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 + [-1, 1, Bottleneck, [64]], + [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 + [-1, 2, Bottleneck, [128]], + [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 + [-1, 8, Bottleneck, [256]], + [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 + [-1, 8, Bottleneck, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 + [-1, 4, Bottleneck, [1024]], # 10 + ] + +# YOLOv3-SPP head +head: + [[-1, 1, Bottleneck, [1024, False]], + [-1, 1, SPP, [512, [5, 9, 13]]], + [-1, 1, Conv, [1024, 3, 1]], + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) + + [-2, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) + + [-2, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P3 + [-1, 1, Bottleneck, [256, False]], + [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) + + [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/models/hub/yolov3-tiny.yaml b/Y5_20221014/models/hub/yolov3-tiny.yaml new file mode 100755 index 0000000..b28b443 --- /dev/null +++ b/Y5_20221014/models/hub/yolov3-tiny.yaml @@ -0,0 +1,41 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,14, 23,27, 37,58] # P4/16 + - [81,82, 135,169, 344,319] # P5/32 + +# YOLOv3-tiny backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [16, 3, 1]], # 0 + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2 + [-1, 1, Conv, [32, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4 + [-1, 1, Conv, [64, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8 + [-1, 1, Conv, [128, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16 + [-1, 1, Conv, [256, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32 + [-1, 1, Conv, [512, 3, 1]], + [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11 + [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12 + ] + +# YOLOv3-tiny head +head: + [[-1, 1, Conv, [1024, 3, 1]], + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large) + + [-2, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium) + + [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5) + ] diff --git a/Y5_20221014/models/hub/yolov3.yaml b/Y5_20221014/models/hub/yolov3.yaml new file mode 100755 index 0000000..d1ef912 --- /dev/null +++ b/Y5_20221014/models/hub/yolov3.yaml @@ -0,0 +1,51 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# darknet53 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [32, 3, 1]], # 0 + [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 + [-1, 1, Bottleneck, [64]], + [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 + [-1, 2, Bottleneck, [128]], + [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 + [-1, 8, Bottleneck, [256]], + [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 + [-1, 8, Bottleneck, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 + [-1, 4, Bottleneck, [1024]], # 10 + ] + +# YOLOv3 head +head: + [[-1, 1, Bottleneck, [1024, False]], + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, Conv, [1024, 3, 1]], + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) + + [-2, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) + + [-2, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P3 + [-1, 1, Bottleneck, [256, False]], + [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) + + [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/models/hub/yolov5-bifpn.yaml b/Y5_20221014/models/hub/yolov5-bifpn.yaml new file mode 100755 index 0000000..504815f --- /dev/null +++ b/Y5_20221014/models/hub/yolov5-bifpn.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 BiFPN head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14, 6], 1, Concat, [1]], # cat P4 <--- BiFPN change + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/models/hub/yolov5-fpn.yaml b/Y5_20221014/models/hub/yolov5-fpn.yaml new file mode 100755 index 0000000..a23e9c6 --- /dev/null +++ b/Y5_20221014/models/hub/yolov5-fpn.yaml @@ -0,0 +1,42 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 FPN head +head: + [[-1, 3, C3, [1024, False]], # 10 (P5/32-large) + + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Conv, [512, 1, 1]], + [-1, 3, C3, [512, False]], # 14 (P4/16-medium) + + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 1, Conv, [256, 1, 1]], + [-1, 3, C3, [256, False]], # 18 (P3/8-small) + + [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/models/hub/yolov5-p2.yaml b/Y5_20221014/models/hub/yolov5-p2.yaml new file mode 100755 index 0000000..554117d --- /dev/null +++ b/Y5_20221014/models/hub/yolov5-p2.yaml @@ -0,0 +1,54 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head with (P2, P3, P4, P5) outputs +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 2], 1, Concat, [1]], # cat backbone P2 + [-1, 1, C3, [128, False]], # 21 (P2/4-xsmall) + + [-1, 1, Conv, [128, 3, 2]], + [[-1, 18], 1, Concat, [1]], # cat head P3 + [-1, 3, C3, [256, False]], # 24 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 27 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 30 (P5/32-large) + + [[21, 24, 27, 30], 1, Detect, [nc, anchors]], # Detect(P2, P3, P4, P5) + ] diff --git a/Y5_20221014/models/hub/yolov5-p34.yaml b/Y5_20221014/models/hub/yolov5-p34.yaml new file mode 100755 index 0000000..dbf0f85 --- /dev/null +++ b/Y5_20221014/models/hub/yolov5-p34.yaml @@ -0,0 +1,41 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [ [ -1, 1, Conv, [ 64, 6, 2, 2 ] ], # 0-P1/2 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 + [ -1, 3, C3, [ 128 ] ], + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 + [ -1, 6, C3, [ 256 ] ], + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 + [ -1, 9, C3, [ 512 ] ], + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32 + [ -1, 3, C3, [ 1024 ] ], + [ -1, 1, SPPF, [ 1024, 5 ] ], # 9 + ] + +# YOLOv5 v6.0 head with (P3, P4) outputs +head: + [ [ -1, 1, Conv, [ 512, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 + [ -1, 3, C3, [ 512, False ] ], # 13 + + [ -1, 1, Conv, [ 256, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 + [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small) + + [ -1, 1, Conv, [ 256, 3, 2 ] ], + [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4 + [ -1, 3, C3, [ 512, False ] ], # 20 (P4/16-medium) + + [ [ 17, 20 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4) + ] diff --git a/Y5_20221014/models/hub/yolov5-p6.yaml b/Y5_20221014/models/hub/yolov5-p6.yaml new file mode 100755 index 0000000..a17202f --- /dev/null +++ b/Y5_20221014/models/hub/yolov5-p6.yaml @@ -0,0 +1,56 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head with (P3, P4, P5, P6) outputs +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5_20221014/models/hub/yolov5-p7.yaml b/Y5_20221014/models/hub/yolov5-p7.yaml new file mode 100755 index 0000000..edd7d13 --- /dev/null +++ b/Y5_20221014/models/hub/yolov5-p7.yaml @@ -0,0 +1,67 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: 3 # AutoAnchor evolves 3 anchors per P output layer + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, Conv, [1280, 3, 2]], # 11-P7/128 + [-1, 3, C3, [1280]], + [-1, 1, SPPF, [1280, 5]], # 13 + ] + +# YOLOv5 v6.0 head with (P3, P4, P5, P6, P7) outputs +head: + [[-1, 1, Conv, [1024, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 10], 1, Concat, [1]], # cat backbone P6 + [-1, 3, C3, [1024, False]], # 17 + + [-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 21 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 25 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 29 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 26], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 32 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 22], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 35 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 18], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 38 (P6/64-xlarge) + + [-1, 1, Conv, [1024, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P7 + [-1, 3, C3, [1280, False]], # 41 (P7/128-xxlarge) + + [[29, 32, 35, 38, 41], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6, P7) + ] diff --git a/Y5_20221014/models/hub/yolov5-panet.yaml b/Y5_20221014/models/hub/yolov5-panet.yaml new file mode 100755 index 0000000..ccfbf90 --- /dev/null +++ b/Y5_20221014/models/hub/yolov5-panet.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 PANet head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/models/hub/yolov5l6.yaml b/Y5_20221014/models/hub/yolov5l6.yaml new file mode 100755 index 0000000..632c2cb --- /dev/null +++ b/Y5_20221014/models/hub/yolov5l6.yaml @@ -0,0 +1,60 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5_20221014/models/hub/yolov5m6.yaml b/Y5_20221014/models/hub/yolov5m6.yaml new file mode 100755 index 0000000..ecc53fd --- /dev/null +++ b/Y5_20221014/models/hub/yolov5m6.yaml @@ -0,0 +1,60 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.67 # model depth multiple +width_multiple: 0.75 # layer channel multiple +anchors: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5_20221014/models/hub/yolov5n6.yaml b/Y5_20221014/models/hub/yolov5n6.yaml new file mode 100755 index 0000000..0c0c71d --- /dev/null +++ b/Y5_20221014/models/hub/yolov5n6.yaml @@ -0,0 +1,60 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.25 # layer channel multiple +anchors: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5_20221014/models/hub/yolov5s-ghost.yaml b/Y5_20221014/models/hub/yolov5s-ghost.yaml new file mode 100755 index 0000000..ff9519c --- /dev/null +++ b/Y5_20221014/models/hub/yolov5s-ghost.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, GhostConv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3Ghost, [128]], + [-1, 1, GhostConv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3Ghost, [256]], + [-1, 1, GhostConv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3Ghost, [512]], + [-1, 1, GhostConv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3Ghost, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, GhostConv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3Ghost, [512, False]], # 13 + + [-1, 1, GhostConv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3Ghost, [256, False]], # 17 (P3/8-small) + + [-1, 1, GhostConv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3Ghost, [512, False]], # 20 (P4/16-medium) + + [-1, 1, GhostConv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3Ghost, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/models/hub/yolov5s-transformer.yaml b/Y5_20221014/models/hub/yolov5s-transformer.yaml new file mode 100755 index 0000000..100d7c4 --- /dev/null +++ b/Y5_20221014/models/hub/yolov5s-transformer.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3TR, [1024]], # 9 <--- C3TR() Transformer module + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/models/hub/yolov5s6.yaml b/Y5_20221014/models/hub/yolov5s6.yaml new file mode 100755 index 0000000..a28fb55 --- /dev/null +++ b/Y5_20221014/models/hub/yolov5s6.yaml @@ -0,0 +1,60 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5_20221014/models/hub/yolov5x6.yaml b/Y5_20221014/models/hub/yolov5x6.yaml new file mode 100755 index 0000000..ba795c4 --- /dev/null +++ b/Y5_20221014/models/hub/yolov5x6.yaml @@ -0,0 +1,60 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.33 # model depth multiple +width_multiple: 1.25 # layer channel multiple +anchors: + - [19,27, 44,40, 38,94] # P3/8 + - [96,68, 86,152, 180,137] # P4/16 + - [140,301, 303,264, 238,542] # P5/32 + - [436,615, 739,380, 925,792] # P6/64 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 + [-1, 3, C3, [768]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 11 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [768, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P5 + [-1, 3, C3, [768, False]], # 15 + + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 19 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 23 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 20], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 26 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 16], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [768, False]], # 29 (P5/32-large) + + [-1, 1, Conv, [768, 3, 2]], + [[-1, 12], 1, Concat, [1]], # cat head P6 + [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) + + [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5_20221014/models/tf.py b/Y5_20221014/models/tf.py new file mode 100755 index 0000000..b0d98cc --- /dev/null +++ b/Y5_20221014/models/tf.py @@ -0,0 +1,574 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +TensorFlow, Keras and TFLite versions of YOLOv5 +Authored by https://github.com/zldrobit in PR https://github.com/ultralytics/yolov5/pull/1127 + +Usage: + $ python models/tf.py --weights yolov5s.pt + +Export: + $ python path/to/export.py --weights yolov5s.pt --include saved_model pb tflite tfjs +""" + +import argparse +import sys +from copy import deepcopy +from pathlib import Path + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +# ROOT = ROOT.relative_to(Path.cwd()) # relative + +import numpy as np +import tensorflow as tf +import torch +import torch.nn as nn +from tensorflow import keras + +from models.common import (C3, SPP, SPPF, Bottleneck, BottleneckCSP, C3x, Concat, Conv, CrossConv, DWConv, + DWConvTranspose2d, Focus, autopad) +from models.experimental import MixConv2d, attempt_load +from models.yolo import Detect +from utils.activations import SiLU +from utils.general import LOGGER, make_divisible, print_args + + +class TFBN(keras.layers.Layer): + # TensorFlow BatchNormalization wrapper + def __init__(self, w=None): + super().__init__() + self.bn = keras.layers.BatchNormalization( + beta_initializer=keras.initializers.Constant(w.bias.numpy()), + gamma_initializer=keras.initializers.Constant(w.weight.numpy()), + moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()), + moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()), + epsilon=w.eps) + + def call(self, inputs): + return self.bn(inputs) + + +class TFPad(keras.layers.Layer): + # Pad inputs in spatial dimensions 1 and 2 + def __init__(self, pad): + super().__init__() + if isinstance(pad, int): + self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]]) + else: # tuple/list + self.pad = tf.constant([[0, 0], [pad[0], pad[0]], [pad[1], pad[1]], [0, 0]]) + + def call(self, inputs): + return tf.pad(inputs, self.pad, mode='constant', constant_values=0) + + +class TFConv(keras.layers.Layer): + # Standard convolution + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None): + # ch_in, ch_out, weights, kernel, stride, padding, groups + super().__init__() + assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument" + # TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding) + # see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch + conv = keras.layers.Conv2D( + filters=c2, + kernel_size=k, + strides=s, + padding='SAME' if s == 1 else 'VALID', + use_bias=not hasattr(w, 'bn'), + kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()), + bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy())) + self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv]) + self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity + self.act = activations(w.act) if act else tf.identity + + def call(self, inputs): + return self.act(self.bn(self.conv(inputs))) + + +class TFDWConv(keras.layers.Layer): + # Depthwise convolution + def __init__(self, c1, c2, k=1, s=1, p=None, act=True, w=None): + # ch_in, ch_out, weights, kernel, stride, padding, groups + super().__init__() + assert c2 % c1 == 0, f'TFDWConv() output={c2} must be a multiple of input={c1} channels' + conv = keras.layers.DepthwiseConv2D( + kernel_size=k, + depth_multiplier=c2 // c1, + strides=s, + padding='SAME' if s == 1 else 'VALID', + use_bias=not hasattr(w, 'bn'), + depthwise_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()), + bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy())) + self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv]) + self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity + self.act = activations(w.act) if act else tf.identity + + def call(self, inputs): + return self.act(self.bn(self.conv(inputs))) + + +class TFDWConvTranspose2d(keras.layers.Layer): + # Depthwise ConvTranspose2d + def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0, w=None): + # ch_in, ch_out, weights, kernel, stride, padding, groups + super().__init__() + assert c1 == c2, f'TFDWConv() output={c2} must be equal to input={c1} channels' + assert k == 4 and p1 == 1, 'TFDWConv() only valid for k=4 and p1=1' + weight, bias = w.weight.permute(2, 3, 1, 0).numpy(), w.bias.numpy() + self.c1 = c1 + self.conv = [ + keras.layers.Conv2DTranspose(filters=1, + kernel_size=k, + strides=s, + padding='VALID', + output_padding=p2, + use_bias=True, + kernel_initializer=keras.initializers.Constant(weight[..., i:i + 1]), + bias_initializer=keras.initializers.Constant(bias[i])) for i in range(c1)] + + def call(self, inputs): + return tf.concat([m(x) for m, x in zip(self.conv, tf.split(inputs, self.c1, 3))], 3)[:, 1:-1, 1:-1] + + +class TFFocus(keras.layers.Layer): + # Focus wh information into c-space + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None): + # ch_in, ch_out, kernel, stride, padding, groups + super().__init__() + self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv) + + def call(self, inputs): # x(b,w,h,c) -> y(b,w/2,h/2,4c) + # inputs = inputs / 255 # normalize 0-255 to 0-1 + inputs = [inputs[:, ::2, ::2, :], inputs[:, 1::2, ::2, :], inputs[:, ::2, 1::2, :], inputs[:, 1::2, 1::2, :]] + return self.conv(tf.concat(inputs, 3)) + + +class TFBottleneck(keras.layers.Layer): + # Standard bottleneck + def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None): # ch_in, ch_out, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2) + self.add = shortcut and c1 == c2 + + def call(self, inputs): + return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs)) + + +class TFCrossConv(keras.layers.Layer): + # Cross Convolution + def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False, w=None): + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, (1, k), (1, s), w=w.cv1) + self.cv2 = TFConv(c_, c2, (k, 1), (s, 1), g=g, w=w.cv2) + self.add = shortcut and c1 == c2 + + def call(self, inputs): + return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs)) + + +class TFConv2d(keras.layers.Layer): + # Substitution for PyTorch nn.Conv2D + def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None): + super().__init__() + assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument" + self.conv = keras.layers.Conv2D(filters=c2, + kernel_size=k, + strides=s, + padding='VALID', + use_bias=bias, + kernel_initializer=keras.initializers.Constant( + w.weight.permute(2, 3, 1, 0).numpy()), + bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None) + + def call(self, inputs): + return self.conv(inputs) + + +class TFBottleneckCSP(keras.layers.Layer): + # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None): + # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2) + self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3) + self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4) + self.bn = TFBN(w.bn) + self.act = lambda x: keras.activations.swish(x) + self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)]) + + def call(self, inputs): + y1 = self.cv3(self.m(self.cv1(inputs))) + y2 = self.cv2(inputs) + return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3)))) + + +class TFC3(keras.layers.Layer): + # CSP Bottleneck with 3 convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None): + # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2) + self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3) + self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)]) + + def call(self, inputs): + return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3)) + + +class TFC3x(keras.layers.Layer): + # 3 module with cross-convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None): + # ch_in, ch_out, number, shortcut, groups, expansion + super().__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2) + self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3) + self.m = keras.Sequential([ + TFCrossConv(c_, c_, k=3, s=1, g=g, e=1.0, shortcut=shortcut, w=w.m[j]) for j in range(n)]) + + def call(self, inputs): + return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3)) + + +class TFSPP(keras.layers.Layer): + # Spatial pyramid pooling layer used in YOLOv3-SPP + def __init__(self, c1, c2, k=(5, 9, 13), w=None): + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2) + self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding='SAME') for x in k] + + def call(self, inputs): + x = self.cv1(inputs) + return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3)) + + +class TFSPPF(keras.layers.Layer): + # Spatial pyramid pooling-Fast layer + def __init__(self, c1, c2, k=5, w=None): + super().__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1) + self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2) + self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding='SAME') + + def call(self, inputs): + x = self.cv1(inputs) + y1 = self.m(x) + y2 = self.m(y1) + return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3)) + + +class TFDetect(keras.layers.Layer): + # TF YOLOv5 Detect layer + def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None): # detection layer + super().__init__() + self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32) + self.nc = nc # number of classes + self.no = nc + 5 # number of outputs per anchor + self.nl = len(anchors) # number of detection layers + self.na = len(anchors[0]) // 2 # number of anchors + self.grid = [tf.zeros(1)] * self.nl # init grid + self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32) + self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]), [self.nl, 1, -1, 1, 2]) + self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)] + self.training = False # set to False after building model + self.imgsz = imgsz + for i in range(self.nl): + ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i] + self.grid[i] = self._make_grid(nx, ny) + + def call(self, inputs): + z = [] # inference output + x = [] + for i in range(self.nl): + x.append(self.m[i](inputs[i])) + # x(bs,20,20,255) to x(bs,3,20,20,85) + ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i] + x[i] = tf.reshape(x[i], [-1, ny * nx, self.na, self.no]) + + if not self.training: # inference + y = tf.sigmoid(x[i]) + grid = tf.transpose(self.grid[i], [0, 2, 1, 3]) - 0.5 + anchor_grid = tf.transpose(self.anchor_grid[i], [0, 2, 1, 3]) * 4 + xy = (y[..., 0:2] * 2 + grid) * self.stride[i] # xy + wh = y[..., 2:4] ** 2 * anchor_grid + # Normalize xywh to 0-1 to reduce calibration error + xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32) + wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32) + y = tf.concat([xy, wh, y[..., 4:]], -1) + z.append(tf.reshape(y, [-1, self.na * ny * nx, self.no])) + + return tf.transpose(x, [0, 2, 1, 3]) if self.training else (tf.concat(z, 1), x) + + @staticmethod + def _make_grid(nx=20, ny=20): + # yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) + # return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() + xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny)) + return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32) + + +class TFUpsample(keras.layers.Layer): + # TF version of torch.nn.Upsample() + def __init__(self, size, scale_factor, mode, w=None): # warning: all arguments needed including 'w' + super().__init__() + assert scale_factor == 2, "scale_factor must be 2" + self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * 2, x.shape[2] * 2), method=mode) + # self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode) + # with default arguments: align_corners=False, half_pixel_centers=False + # self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x, + # size=(x.shape[1] * 2, x.shape[2] * 2)) + + def call(self, inputs): + return self.upsample(inputs) + + +class TFConcat(keras.layers.Layer): + # TF version of torch.concat() + def __init__(self, dimension=1, w=None): + super().__init__() + assert dimension == 1, "convert only NCHW to NHWC concat" + self.d = 3 + + def call(self, inputs): + return tf.concat(inputs, self.d) + + +def parse_model(d, ch, model, imgsz): # model_dict, input_channels(3) + LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") + anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] + na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors + no = na * (nc + 5) # number of outputs = anchors * (classes + 5) + + layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out + for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args + m_str = m + m = eval(m) if isinstance(m, str) else m # eval strings + for j, a in enumerate(args): + try: + args[j] = eval(a) if isinstance(a, str) else a # eval strings + except NameError: + pass + + n = max(round(n * gd), 1) if n > 1 else n # depth gain + if m in [ + nn.Conv2d, Conv, DWConv, DWConvTranspose2d, Bottleneck, SPP, SPPF, MixConv2d, Focus, CrossConv, + BottleneckCSP, C3, C3x]: + c1, c2 = ch[f], args[0] + c2 = make_divisible(c2 * gw, 8) if c2 != no else c2 + + args = [c1, c2, *args[1:]] + if m in [BottleneckCSP, C3, C3x]: + args.insert(2, n) + n = 1 + elif m is nn.BatchNorm2d: + args = [ch[f]] + elif m is Concat: + c2 = sum(ch[-1 if x == -1 else x + 1] for x in f) + elif m is Detect: + args.append([ch[x + 1] for x in f]) + if isinstance(args[1], int): # number of anchors + args[1] = [list(range(args[1] * 2))] * len(f) + args.append(imgsz) + else: + c2 = ch[f] + + tf_m = eval('TF' + m_str.replace('nn.', '')) + m_ = keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)]) if n > 1 \ + else tf_m(*args, w=model.model[i]) # module + + torch_m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module + t = str(m)[8:-2].replace('__main__.', '') # module type + np = sum(x.numel() for x in torch_m_.parameters()) # number params + m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params + LOGGER.info(f'{i:>3}{str(f):>18}{str(n):>3}{np:>10} {t:<40}{str(args):<30}') # print + save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist + layers.append(m_) + ch.append(c2) + return keras.Sequential(layers), sorted(save) + + +class TFModel: + # TF YOLOv5 model + def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, model=None, imgsz=(640, 640)): # model, channels, classes + super().__init__() + if isinstance(cfg, dict): + self.yaml = cfg # model dict + else: # is *.yaml + import yaml # for torch hub + self.yaml_file = Path(cfg).name + with open(cfg) as f: + self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict + + # Define model + if nc and nc != self.yaml['nc']: + LOGGER.info(f"Overriding {cfg} nc={self.yaml['nc']} with nc={nc}") + self.yaml['nc'] = nc # override yaml value + self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz) + + def predict(self, + inputs, + tf_nms=False, + agnostic_nms=False, + topk_per_class=100, + topk_all=100, + iou_thres=0.45, + conf_thres=0.25): + y = [] # outputs + x = inputs + for m in self.model.layers: + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + + x = m(x) # run + y.append(x if m.i in self.savelist else None) # save output + + # Add TensorFlow NMS + if tf_nms: + boxes = self._xywh2xyxy(x[0][..., :4]) + probs = x[0][:, :, 4:5] + classes = x[0][:, :, 5:] + scores = probs * classes + if agnostic_nms: + nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres) + else: + boxes = tf.expand_dims(boxes, 2) + nms = tf.image.combined_non_max_suppression(boxes, + scores, + topk_per_class, + topk_all, + iou_thres, + conf_thres, + clip_boxes=False) + return nms, x[1] + return x[0] # output only first tensor [1,6300,85] = [xywh, conf, class0, class1, ...] + # x = x[0][0] # [x(1,6300,85), ...] to x(6300,85) + # xywh = x[..., :4] # x(6300,4) boxes + # conf = x[..., 4:5] # x(6300,1) confidences + # cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes + # return tf.concat([conf, cls, xywh], 1) + + @staticmethod + def _xywh2xyxy(xywh): + # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1) + return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1) + + +class AgnosticNMS(keras.layers.Layer): + # TF Agnostic NMS + def call(self, input, topk_all, iou_thres, conf_thres): + # wrap map_fn to avoid TypeSpec related error https://stackoverflow.com/a/65809989/3036450 + return tf.map_fn(lambda x: self._nms(x, topk_all, iou_thres, conf_thres), + input, + fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32), + name='agnostic_nms') + + @staticmethod + def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnostic NMS + boxes, classes, scores = x + class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32) + scores_inp = tf.reduce_max(scores, -1) + selected_inds = tf.image.non_max_suppression(boxes, + scores_inp, + max_output_size=topk_all, + iou_threshold=iou_thres, + score_threshold=conf_thres) + selected_boxes = tf.gather(boxes, selected_inds) + padded_boxes = tf.pad(selected_boxes, + paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]], + mode="CONSTANT", + constant_values=0.0) + selected_scores = tf.gather(scores_inp, selected_inds) + padded_scores = tf.pad(selected_scores, + paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]], + mode="CONSTANT", + constant_values=-1.0) + selected_classes = tf.gather(class_inds, selected_inds) + padded_classes = tf.pad(selected_classes, + paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]], + mode="CONSTANT", + constant_values=-1.0) + valid_detections = tf.shape(selected_inds)[0] + return padded_boxes, padded_scores, padded_classes, valid_detections + + +def activations(act=nn.SiLU): + # Returns TF activation from input PyTorch activation + if isinstance(act, nn.LeakyReLU): + return lambda x: keras.activations.relu(x, alpha=0.1) + elif isinstance(act, nn.Hardswish): + return lambda x: x * tf.nn.relu6(x + 3) * 0.166666667 + elif isinstance(act, (nn.SiLU, SiLU)): + return lambda x: keras.activations.swish(x) + else: + raise Exception(f'no matching TensorFlow activation found for PyTorch activation {act}') + + +def representative_dataset_gen(dataset, ncalib=100): + # Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays + for n, (path, img, im0s, vid_cap, string) in enumerate(dataset): + im = np.transpose(img, [1, 2, 0]) + im = np.expand_dims(im, axis=0).astype(np.float32) + im /= 255 + yield [im] + if n >= ncalib: + break + + +def run( + weights=ROOT / 'yolov5s.pt', # weights path + imgsz=(640, 640), # inference size h,w + batch_size=1, # batch size + dynamic=False, # dynamic batch size +): + # PyTorch model + im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image + model = attempt_load(weights, device=torch.device('cpu'), inplace=True, fuse=False) + _ = model(im) # inference + model.info() + + # TensorFlow model + im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image + tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz) + _ = tf_model.predict(im) # inference + + # Keras model + im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size) + keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im)) + keras_model.summary() + + LOGGER.info('PyTorch, TensorFlow and Keras models successfully verified.\nUse export.py for TF model export.') + + +def parse_opt(): + parser = argparse.ArgumentParser() + parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path') + parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w') + parser.add_argument('--batch-size', type=int, default=1, help='batch size') + parser.add_argument('--dynamic', action='store_true', help='dynamic batch size') + opt = parser.parse_args() + opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand + print_args(vars(opt)) + return opt + + +def main(opt): + run(**vars(opt)) + + +if __name__ == "__main__": + opt = parse_opt() + main(opt) diff --git a/Y5_20221014/models/yolo.py b/Y5_20221014/models/yolo.py new file mode 100755 index 0000000..02660e6 --- /dev/null +++ b/Y5_20221014/models/yolo.py @@ -0,0 +1,338 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +YOLO-specific modules + +Usage: + $ python path/to/models/yolo.py --cfg yolov5s.yaml +""" + +import argparse +import os +import platform +import sys +from copy import deepcopy +from pathlib import Path + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +if platform.system() != 'Windows': + ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative + +from models.common import * +from models.experimental import * +from utils.autoanchor import check_anchor_order +from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args +from utils.plots import feature_visualization +from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device, + time_sync) + +try: + import thop # for FLOPs computation +except ImportError: + thop = None + + +class Detect(nn.Module): + stride = None # strides computed during build + onnx_dynamic = False # ONNX export parameter + export = False # export mode + + def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer + super().__init__() + self.nc = nc # number of classes + self.no = nc + 5 # number of outputs per anchor + self.nl = len(anchors) # number of detection layers + self.na = len(anchors[0]) // 2 # number of anchors + self.grid = [torch.zeros(1)] * self.nl # init grid + self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid + self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2) + self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv + self.inplace = inplace # use in-place ops (e.g. slice assignment) + + def forward(self, x): + z = [] # inference output + for i in range(self.nl): + x[i] = self.m[i](x[i]) # conv + bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) + x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() + + if not self.training: # inference + if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]: + self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i) + + y = x[i].sigmoid() + if self.inplace: + y[..., 0:2] = (y[..., 0:2] * 2 + self.grid[i]) * self.stride[i] # xy + y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh + else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953 + xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0 + xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy + wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh + y = torch.cat((xy, wh, conf), 4) + z.append(y.view(bs, -1, self.no)) + + return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x) + + def _make_grid(self, nx=20, ny=20, i=0): + d = self.anchors[i].device + t = self.anchors[i].dtype + shape = 1, self.na, ny, nx, 2 # grid shape + y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t) + if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility + yv, xv = torch.meshgrid(y, x, indexing='ij') + else: + yv, xv = torch.meshgrid(y, x) + grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5 + anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape) + return grid, anchor_grid + + +class Model(nn.Module): + # YOLOv5 model + def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes + super().__init__() + if isinstance(cfg, dict): + self.yaml = cfg # model dict + else: # is *.yaml + import yaml # for torch hub + self.yaml_file = Path(cfg).name + with open(cfg, encoding='ascii', errors='ignore') as f: + self.yaml = yaml.safe_load(f) # model dict + + # Define model + ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels + if nc and nc != self.yaml['nc']: + LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") + self.yaml['nc'] = nc # override yaml value + if anchors: + LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}') + self.yaml['anchors'] = round(anchors) # override yaml value + self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist + self.names = [str(i) for i in range(self.yaml['nc'])] # default names + self.inplace = self.yaml.get('inplace', True) + + # Build strides, anchors + m = self.model[-1] # Detect() + if isinstance(m, Detect): + s = 256 # 2x min stride + m.inplace = self.inplace + m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward + check_anchor_order(m) # must be in pixel-space (not grid-space) + m.anchors /= m.stride.view(-1, 1, 1) + self.stride = m.stride + self._initialize_biases() # only run once + + # Init weights, biases + initialize_weights(self) + self.info() + LOGGER.info('') + + def forward(self, x, augment=False, profile=False, visualize=False): + if augment: + return self._forward_augment(x) # augmented inference, None + return self._forward_once(x, profile, visualize) # single-scale inference, train + + def _forward_augment(self, x): + img_size = x.shape[-2:] # height, width + s = [1, 0.83, 0.67] # scales + f = [None, 3, None] # flips (2-ud, 3-lr) + y = [] # outputs + for si, fi in zip(s, f): + xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) + yi = self._forward_once(xi)[0] # forward + # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save + yi = self._descale_pred(yi, fi, si, img_size) + y.append(yi) + y = self._clip_augmented(y) # clip augmented tails + return torch.cat(y, 1), None # augmented inference, train + + def _forward_once(self, x, profile=False, visualize=False): + y, dt = [], [] # outputs + for m in self.model: + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + if profile: + self._profile_one_layer(m, x, dt) + x = m(x) # run + y.append(x if m.i in self.save else None) # save output + if visualize: + feature_visualization(x, m.type, m.i, save_dir=visualize) + return x + + def _descale_pred(self, p, flips, scale, img_size): + # de-scale predictions following augmented inference (inverse operation) + if self.inplace: + p[..., :4] /= scale # de-scale + if flips == 2: + p[..., 1] = img_size[0] - p[..., 1] # de-flip ud + elif flips == 3: + p[..., 0] = img_size[1] - p[..., 0] # de-flip lr + else: + x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale + if flips == 2: + y = img_size[0] - y # de-flip ud + elif flips == 3: + x = img_size[1] - x # de-flip lr + p = torch.cat((x, y, wh, p[..., 4:]), -1) + return p + + def _clip_augmented(self, y): + # Clip YOLOv5 augmented inference tails + nl = self.model[-1].nl # number of detection layers (P3-P5) + g = sum(4 ** x for x in range(nl)) # grid points + e = 1 # exclude layer count + i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices + y[0] = y[0][:, :-i] # large + i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices + y[-1] = y[-1][:, i:] # small + return y + + def _profile_one_layer(self, m, x, dt): + c = isinstance(m, Detect) # is final layer, copy input as inplace fix + o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs + t = time_sync() + for _ in range(10): + m(x.copy() if c else x) + dt.append((time_sync() - t) * 100) + if m == self.model[0]: + LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module") + LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}') + if c: + LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total") + + def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency + # https://arxiv.org/abs/1708.02002 section 3.3 + # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. + m = self.model[-1] # Detect() module + for mi, s in zip(m.m, m.stride): # from + b = mi.bias.view(m.na, -1).detach() # conv.bias(255) to (3,85) + b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) + b[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls + mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) + + def _print_biases(self): + m = self.model[-1] # Detect() module + for mi in m.m: # from + b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) + LOGGER.info( + ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())) + + # def _print_weights(self): + # for m in self.model.modules(): + # if type(m) is Bottleneck: + # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights + + def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers + LOGGER.info('Fusing layers... ') + for m in self.model.modules(): + if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'): + m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv + delattr(m, 'bn') # remove batchnorm + m.forward = m.forward_fuse # update forward + self.info() + return self + + def info(self, verbose=False, img_size=640): # print model information + model_info(self, verbose, img_size) + + def _apply(self, fn): + # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers + self = super()._apply(fn) + m = self.model[-1] # Detect() + if isinstance(m, Detect): + m.stride = fn(m.stride) + m.grid = list(map(fn, m.grid)) + if isinstance(m.anchor_grid, list): + m.anchor_grid = list(map(fn, m.anchor_grid)) + return self + + +def parse_model(d, ch): # model_dict, input_channels(3) + LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") + anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] + na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors + no = na * (nc + 5) # number of outputs = anchors * (classes + 5) + + layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out + for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args + m = eval(m) if isinstance(m, str) else m # eval strings + for j, a in enumerate(args): + try: + args[j] = eval(a) if isinstance(a, str) else a # eval strings + except NameError: + pass + + n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain + if m in (Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, + BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x): + c1, c2 = ch[f], args[0] + if c2 != no: # if not output + c2 = make_divisible(c2 * gw, 8) + + args = [c1, c2, *args[1:]] + if m in [BottleneckCSP, C3, C3TR, C3Ghost, C3x]: + args.insert(2, n) # number of repeats + n = 1 + elif m is nn.BatchNorm2d: + args = [ch[f]] + elif m is Concat: + c2 = sum(ch[x] for x in f) + elif m is Detect: + args.append([ch[x] for x in f]) + if isinstance(args[1], int): # number of anchors + args[1] = [list(range(args[1] * 2))] * len(f) + elif m is Contract: + c2 = ch[f] * args[0] ** 2 + elif m is Expand: + c2 = ch[f] // args[0] ** 2 + else: + c2 = ch[f] + + m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module + t = str(m)[8:-2].replace('__main__.', '') # module type + np = sum(x.numel() for x in m_.parameters()) # number params + m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params + LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print + save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist + layers.append(m_) + if i == 0: + ch = [] + ch.append(c2) + return nn.Sequential(*layers), sorted(save) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') + parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs') + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--profile', action='store_true', help='profile model speed') + parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer') + parser.add_argument('--test', action='store_true', help='test all yolo*.yaml') + opt = parser.parse_args() + opt.cfg = check_yaml(opt.cfg) # check YAML + print_args(vars(opt)) + device = select_device(opt.device) + + # Create model + im = torch.rand(opt.batch_size, 3, 640, 640).to(device) + model = Model(opt.cfg).to(device) + + # Options + if opt.line_profile: # profile layer by layer + _ = model(im, profile=True) + + elif opt.profile: # profile forward-backward + results = profile(input=im, ops=[model], n=3) + + elif opt.test: # test all models + for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'): + try: + _ = Model(cfg) + except Exception as e: + print(f'Error in {cfg}: {e}') + + else: # report fused model summary + model.fuse() diff --git a/Y5_20221014/models/yolov5l.yaml b/Y5_20221014/models/yolov5l.yaml new file mode 100755 index 0000000..ce8a5de --- /dev/null +++ b/Y5_20221014/models/yolov5l.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/models/yolov5m.yaml b/Y5_20221014/models/yolov5m.yaml new file mode 100755 index 0000000..ad13ab3 --- /dev/null +++ b/Y5_20221014/models/yolov5m.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.67 # model depth multiple +width_multiple: 0.75 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/models/yolov5n.yaml b/Y5_20221014/models/yolov5n.yaml new file mode 100755 index 0000000..8a28a40 --- /dev/null +++ b/Y5_20221014/models/yolov5n.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.25 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/models/yolov5s.yaml b/Y5_20221014/models/yolov5s.yaml new file mode 100755 index 0000000..f35beab --- /dev/null +++ b/Y5_20221014/models/yolov5s.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/models/yolov5x.yaml b/Y5_20221014/models/yolov5x.yaml new file mode 100755 index 0000000..f617a02 --- /dev/null +++ b/Y5_20221014/models/yolov5x.yaml @@ -0,0 +1,48 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license + +# Parameters +nc: 80 # number of classes +depth_multiple: 1.33 # model depth multiple +width_multiple: 1.25 # layer channel multiple +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 v6.0 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 6, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 3, C3, [1024]], + [-1, 1, SPPF, [1024, 5]], # 9 + ] + +# YOLOv5 v6.0 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_20221014/utils/__init__.py b/Y5_20221014/utils/__init__.py new file mode 100755 index 0000000..da53a4d --- /dev/null +++ b/Y5_20221014/utils/__init__.py @@ -0,0 +1,36 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +utils/initialization +""" + + +def notebook_init(verbose=True): + # Check system software and hardware + print('Checking setup...') + + import os + import shutil + + from utils.general import check_requirements, emojis, is_colab + from utils.torch_utils import select_device # imports + + check_requirements(('psutil', 'IPython')) + import psutil + from IPython import display # to display images and clear console output + + if is_colab(): + shutil.rmtree('/content/sample_data', ignore_errors=True) # remove colab /sample_data directory + + # System info + if verbose: + gb = 1 << 30 # bytes to GiB (1024 ** 3) + ram = psutil.virtual_memory().total + total, used, free = shutil.disk_usage("/") + display.clear_output() + s = f'({os.cpu_count()} CPUs, {ram / gb:.1f} GB RAM, {(total - free) / gb:.1f}/{total / gb:.1f} GB disk)' + else: + s = '' + + select_device(newline=False) + print(emojis(f'Setup complete ✅ {s}')) + return display diff --git a/Y5_20221014/utils/__pycache__/__init__.cpython-36.pyc b/Y5_20221014/utils/__pycache__/__init__.cpython-36.pyc new file mode 100755 index 0000000..0d86262 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/__init__.cpython-36.pyc differ diff --git a/Y5_20221014/utils/__pycache__/__init__.cpython-37.pyc b/Y5_20221014/utils/__pycache__/__init__.cpython-37.pyc new file mode 100755 index 0000000..aeff774 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/__init__.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/__init__.cpython-38.pyc b/Y5_20221014/utils/__pycache__/__init__.cpython-38.pyc new file mode 100755 index 0000000..e91bfde Binary files /dev/null and b/Y5_20221014/utils/__pycache__/__init__.cpython-38.pyc differ diff --git a/Y5_20221014/utils/__pycache__/augmentations.cpython-36.pyc b/Y5_20221014/utils/__pycache__/augmentations.cpython-36.pyc new file mode 100755 index 0000000..dfec06c Binary files /dev/null and b/Y5_20221014/utils/__pycache__/augmentations.cpython-36.pyc differ diff --git a/Y5_20221014/utils/__pycache__/augmentations.cpython-37.pyc b/Y5_20221014/utils/__pycache__/augmentations.cpython-37.pyc new file mode 100755 index 0000000..e87d947 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/augmentations.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/augmentations.cpython-38.pyc b/Y5_20221014/utils/__pycache__/augmentations.cpython-38.pyc new file mode 100755 index 0000000..7e692cc Binary files /dev/null and b/Y5_20221014/utils/__pycache__/augmentations.cpython-38.pyc differ diff --git a/Y5_20221014/utils/__pycache__/autoanchor.cpython-36.pyc b/Y5_20221014/utils/__pycache__/autoanchor.cpython-36.pyc new file mode 100755 index 0000000..e284069 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/autoanchor.cpython-36.pyc differ diff --git a/Y5_20221014/utils/__pycache__/autoanchor.cpython-37.pyc b/Y5_20221014/utils/__pycache__/autoanchor.cpython-37.pyc new file mode 100755 index 0000000..51299a4 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/autoanchor.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/autoanchor.cpython-38.pyc b/Y5_20221014/utils/__pycache__/autoanchor.cpython-38.pyc new file mode 100755 index 0000000..e5d96db Binary files /dev/null and b/Y5_20221014/utils/__pycache__/autoanchor.cpython-38.pyc differ diff --git a/Y5_20221014/utils/__pycache__/autobatch.cpython-37.pyc b/Y5_20221014/utils/__pycache__/autobatch.cpython-37.pyc new file mode 100755 index 0000000..01ee9d8 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/autobatch.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/autobatch.cpython-38.pyc b/Y5_20221014/utils/__pycache__/autobatch.cpython-38.pyc new file mode 100755 index 0000000..0526e5e Binary files /dev/null and b/Y5_20221014/utils/__pycache__/autobatch.cpython-38.pyc differ diff --git a/Y5_20221014/utils/__pycache__/callbacks.cpython-37.pyc b/Y5_20221014/utils/__pycache__/callbacks.cpython-37.pyc new file mode 100755 index 0000000..ac75e6b Binary files /dev/null and b/Y5_20221014/utils/__pycache__/callbacks.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/callbacks.cpython-38.pyc b/Y5_20221014/utils/__pycache__/callbacks.cpython-38.pyc new file mode 100755 index 0000000..e2e8de1 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/callbacks.cpython-38.pyc differ diff --git a/Y5_20221014/utils/__pycache__/dataloaders.cpython-36.pyc b/Y5_20221014/utils/__pycache__/dataloaders.cpython-36.pyc new file mode 100755 index 0000000..cff8d9f Binary files /dev/null and b/Y5_20221014/utils/__pycache__/dataloaders.cpython-36.pyc differ diff --git a/Y5_20221014/utils/__pycache__/dataloaders.cpython-37.pyc b/Y5_20221014/utils/__pycache__/dataloaders.cpython-37.pyc new file mode 100755 index 0000000..c9953d6 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/dataloaders.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/dataloaders.cpython-38.pyc b/Y5_20221014/utils/__pycache__/dataloaders.cpython-38.pyc new file mode 100755 index 0000000..1b26c47 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/dataloaders.cpython-38.pyc differ diff --git a/Y5_20221014/utils/__pycache__/downloads.cpython-36.pyc b/Y5_20221014/utils/__pycache__/downloads.cpython-36.pyc new file mode 100755 index 0000000..bec40c1 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/downloads.cpython-36.pyc differ diff --git a/Y5_20221014/utils/__pycache__/downloads.cpython-37.pyc b/Y5_20221014/utils/__pycache__/downloads.cpython-37.pyc new file mode 100755 index 0000000..40d7cee Binary files /dev/null and b/Y5_20221014/utils/__pycache__/downloads.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/downloads.cpython-38.pyc b/Y5_20221014/utils/__pycache__/downloads.cpython-38.pyc new file mode 100755 index 0000000..6e63e19 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/downloads.cpython-38.pyc differ diff --git a/Y5_20221014/utils/__pycache__/general.cpython-36.pyc b/Y5_20221014/utils/__pycache__/general.cpython-36.pyc new file mode 100755 index 0000000..85079da Binary files /dev/null and b/Y5_20221014/utils/__pycache__/general.cpython-36.pyc differ diff --git a/Y5_20221014/utils/__pycache__/general.cpython-37.pyc b/Y5_20221014/utils/__pycache__/general.cpython-37.pyc new file mode 100755 index 0000000..02a903c Binary files /dev/null and b/Y5_20221014/utils/__pycache__/general.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/general.cpython-38.pyc b/Y5_20221014/utils/__pycache__/general.cpython-38.pyc new file mode 100755 index 0000000..809820f Binary files /dev/null and b/Y5_20221014/utils/__pycache__/general.cpython-38.pyc differ diff --git a/Y5_20221014/utils/__pycache__/loss.cpython-37.pyc b/Y5_20221014/utils/__pycache__/loss.cpython-37.pyc new file mode 100755 index 0000000..6cc1535 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/loss.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/loss.cpython-38.pyc b/Y5_20221014/utils/__pycache__/loss.cpython-38.pyc new file mode 100755 index 0000000..e08c356 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/loss.cpython-38.pyc differ diff --git a/Y5_20221014/utils/__pycache__/metrics.cpython-36.pyc b/Y5_20221014/utils/__pycache__/metrics.cpython-36.pyc new file mode 100755 index 0000000..8a933e1 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/metrics.cpython-36.pyc differ diff --git a/Y5_20221014/utils/__pycache__/metrics.cpython-37.pyc b/Y5_20221014/utils/__pycache__/metrics.cpython-37.pyc new file mode 100755 index 0000000..d5c4e2e Binary files /dev/null and b/Y5_20221014/utils/__pycache__/metrics.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/metrics.cpython-38.pyc b/Y5_20221014/utils/__pycache__/metrics.cpython-38.pyc new file mode 100755 index 0000000..bacf717 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/metrics.cpython-38.pyc differ diff --git a/Y5_20221014/utils/__pycache__/plots.cpython-36.pyc b/Y5_20221014/utils/__pycache__/plots.cpython-36.pyc new file mode 100755 index 0000000..275db1a Binary files /dev/null and b/Y5_20221014/utils/__pycache__/plots.cpython-36.pyc differ diff --git a/Y5_20221014/utils/__pycache__/plots.cpython-37.pyc b/Y5_20221014/utils/__pycache__/plots.cpython-37.pyc new file mode 100755 index 0000000..3b0b332 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/plots.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/plots.cpython-38.pyc b/Y5_20221014/utils/__pycache__/plots.cpython-38.pyc new file mode 100755 index 0000000..f8e5c64 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/plots.cpython-38.pyc differ diff --git a/Y5_20221014/utils/__pycache__/torch_utils.cpython-36.pyc b/Y5_20221014/utils/__pycache__/torch_utils.cpython-36.pyc new file mode 100755 index 0000000..6d23ea7 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/torch_utils.cpython-36.pyc differ diff --git a/Y5_20221014/utils/__pycache__/torch_utils.cpython-37.pyc b/Y5_20221014/utils/__pycache__/torch_utils.cpython-37.pyc new file mode 100755 index 0000000..923b782 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/torch_utils.cpython-37.pyc differ diff --git a/Y5_20221014/utils/__pycache__/torch_utils.cpython-38.pyc b/Y5_20221014/utils/__pycache__/torch_utils.cpython-38.pyc new file mode 100755 index 0000000..1cda605 Binary files /dev/null and b/Y5_20221014/utils/__pycache__/torch_utils.cpython-38.pyc differ diff --git a/Y5_20221014/utils/activations.py b/Y5_20221014/utils/activations.py new file mode 100755 index 0000000..084ce8c --- /dev/null +++ b/Y5_20221014/utils/activations.py @@ -0,0 +1,103 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Activation functions +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class SiLU(nn.Module): + # SiLU activation https://arxiv.org/pdf/1606.08415.pdf + @staticmethod + def forward(x): + return x * torch.sigmoid(x) + + +class Hardswish(nn.Module): + # Hard-SiLU activation + @staticmethod + def forward(x): + # return x * F.hardsigmoid(x) # for TorchScript and CoreML + return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0 # for TorchScript, CoreML and ONNX + + +class Mish(nn.Module): + # Mish activation https://github.com/digantamisra98/Mish + @staticmethod + def forward(x): + return x * F.softplus(x).tanh() + + +class MemoryEfficientMish(nn.Module): + # Mish activation memory-efficient + class F(torch.autograd.Function): + + @staticmethod + def forward(ctx, x): + ctx.save_for_backward(x) + return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) + + @staticmethod + def backward(ctx, grad_output): + x = ctx.saved_tensors[0] + sx = torch.sigmoid(x) + fx = F.softplus(x).tanh() + return grad_output * (fx + x * sx * (1 - fx * fx)) + + def forward(self, x): + return self.F.apply(x) + + +class FReLU(nn.Module): + # FReLU activation https://arxiv.org/abs/2007.11824 + def __init__(self, c1, k=3): # ch_in, kernel + super().__init__() + self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) + self.bn = nn.BatchNorm2d(c1) + + def forward(self, x): + return torch.max(x, self.bn(self.conv(x))) + + +class AconC(nn.Module): + r""" ACON activation (activate or not) + AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter + according to "Activate or Not: Learning Customized Activation" . + """ + + def __init__(self, c1): + super().__init__() + self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.beta = nn.Parameter(torch.ones(1, c1, 1, 1)) + + def forward(self, x): + dpx = (self.p1 - self.p2) * x + return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x + + +class MetaAconC(nn.Module): + r""" ACON activation (activate or not) + MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network + according to "Activate or Not: Learning Customized Activation" . + """ + + def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r + super().__init__() + c2 = max(r, c1 // r) + self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) + self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True) + self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True) + # self.bn1 = nn.BatchNorm2d(c2) + # self.bn2 = nn.BatchNorm2d(c1) + + def forward(self, x): + y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True) + # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891 + # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable + beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed + dpx = (self.p1 - self.p2) * x + return dpx * torch.sigmoid(beta * dpx) + self.p2 * x diff --git a/Y5_20221014/utils/augmentations.py b/Y5_20221014/utils/augmentations.py new file mode 100755 index 0000000..3f764c0 --- /dev/null +++ b/Y5_20221014/utils/augmentations.py @@ -0,0 +1,284 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Image augmentation functions +""" + +import math +import random + +import cv2 +import numpy as np + +from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box +from utils.metrics import bbox_ioa + + +class Albumentations: + # YOLOv5 Albumentations class (optional, only used if package is installed) + def __init__(self): + self.transform = None + try: + import albumentations as A + check_version(A.__version__, '1.0.3', hard=True) # version requirement + + T = [ + A.Blur(p=0.01), + A.MedianBlur(p=0.01), + A.ToGray(p=0.01), + A.CLAHE(p=0.01), + A.RandomBrightnessContrast(p=0.0), + A.RandomGamma(p=0.0), + A.ImageCompression(quality_lower=75, p=0.0)] # transforms + self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels'])) + + LOGGER.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p)) + except ImportError: # package not installed, skip + pass + except Exception as e: + LOGGER.info(colorstr('albumentations: ') + f'{e}') + + def __call__(self, im, labels, p=1.0): + if self.transform and random.random() < p: + new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed + im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])]) + return im, labels + + +def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5): + # HSV color-space augmentation + if hgain or sgain or vgain: + r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains + hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV)) + dtype = im.dtype # uint8 + + x = np.arange(0, 256, dtype=r.dtype) + lut_hue = ((x * r[0]) % 180).astype(dtype) + lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) + lut_val = np.clip(x * r[2], 0, 255).astype(dtype) + + im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) + cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed + + +def hist_equalize(im, clahe=True, bgr=False): + # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255 + yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV) + if clahe: + c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) + yuv[:, :, 0] = c.apply(yuv[:, :, 0]) + else: + yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram + return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB + + +def replicate(im, labels): + # Replicate labels + h, w = im.shape[:2] + boxes = labels[:, 1:].astype(int) + x1, y1, x2, y2 = boxes.T + s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels) + for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices + x1b, y1b, x2b, y2b = boxes[i] + bh, bw = y2b - y1b, x2b - x1b + yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y + x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh] + im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax] + labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0) + + return im, labels + + +def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32): + # Resize and pad image while meeting stride-multiple constraints + shape = im.shape[:2] # current shape [height, width] + if isinstance(new_shape, int): + new_shape = (new_shape, new_shape) + + # Scale ratio (new / old) + r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) + if not scaleup: # only scale down, do not scale up (for better val mAP) + r = min(r, 1.0) + + # Compute padding + ratio = r, r # width, height ratios + new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) + dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding + if auto: # minimum rectangle + dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding + elif scaleFill: # stretch + dw, dh = 0.0, 0.0 + new_unpad = (new_shape[1], new_shape[0]) + ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios + + dw /= 2 # divide padding into 2 sides + dh /= 2 + + if shape[::-1] != new_unpad: # resize + im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR) + top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) + left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) + im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border + return im, ratio, (dw, dh) + + +def random_perspective(im, + targets=(), + segments=(), + degrees=10, + translate=.1, + scale=.1, + shear=10, + perspective=0.0, + border=(0, 0)): + # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10)) + # targets = [cls, xyxy] + + height = im.shape[0] + border[0] * 2 # shape(h,w,c) + width = im.shape[1] + border[1] * 2 + + # Center + C = np.eye(3) + C[0, 2] = -im.shape[1] / 2 # x translation (pixels) + C[1, 2] = -im.shape[0] / 2 # y translation (pixels) + + # Perspective + P = np.eye(3) + P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y) + P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x) + + # Rotation and Scale + R = np.eye(3) + a = random.uniform(-degrees, degrees) + # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations + s = random.uniform(1 - scale, 1 + scale) + # s = 2 ** random.uniform(-scale, scale) + R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s) + + # Shear + S = np.eye(3) + S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg) + S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg) + + # Translation + T = np.eye(3) + T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels) + T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels) + + # Combined rotation matrix + M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT + if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed + if perspective: + im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114)) + else: # affine + im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114)) + + # Visualize + # import matplotlib.pyplot as plt + # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel() + # ax[0].imshow(im[:, :, ::-1]) # base + # ax[1].imshow(im2[:, :, ::-1]) # warped + + # Transform label coordinates + n = len(targets) + if n: + use_segments = any(x.any() for x in segments) + new = np.zeros((n, 4)) + if use_segments: # warp segments + segments = resample_segments(segments) # upsample + for i, segment in enumerate(segments): + xy = np.ones((len(segment), 3)) + xy[:, :2] = segment + xy = xy @ M.T # transform + xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine + + # clip + new[i] = segment2box(xy, width, height) + + else: # warp boxes + xy = np.ones((n * 4, 3)) + xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1 + xy = xy @ M.T # transform + xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine + + # create new boxes + x = xy[:, [0, 2, 4, 6]] + y = xy[:, [1, 3, 5, 7]] + new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T + + # clip + new[:, [0, 2]] = new[:, [0, 2]].clip(0, width) + new[:, [1, 3]] = new[:, [1, 3]].clip(0, height) + + # filter candidates + i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10) + targets = targets[i] + targets[:, 1:5] = new[i] + + return im, targets + + +def copy_paste(im, labels, segments, p=0.5): + # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy) + n = len(segments) + if p and n: + h, w, c = im.shape # height, width, channels + im_new = np.zeros(im.shape, np.uint8) + for j in random.sample(range(n), k=round(p * n)): + l, s = labels[j], segments[j] + box = w - l[3], l[2], w - l[1], l[4] + ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area + if (ioa < 0.30).all(): # allow 30% obscuration of existing labels + labels = np.concatenate((labels, [[l[0], *box]]), 0) + segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1)) + cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED) + + result = cv2.bitwise_and(src1=im, src2=im_new) + result = cv2.flip(result, 1) # augment segments (flip left-right) + i = result > 0 # pixels to replace + # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch + im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug + + return im, labels, segments + + +def cutout(im, labels, p=0.5): + # Applies image cutout augmentation https://arxiv.org/abs/1708.04552 + if random.random() < p: + h, w = im.shape[:2] + scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction + for s in scales: + mask_h = random.randint(1, int(h * s)) # create random masks + mask_w = random.randint(1, int(w * s)) + + # box + xmin = max(0, random.randint(0, w) - mask_w // 2) + ymin = max(0, random.randint(0, h) - mask_h // 2) + xmax = min(w, xmin + mask_w) + ymax = min(h, ymin + mask_h) + + # apply random color mask + im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)] + + # return unobscured labels + if len(labels) and s > 0.03: + box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32) + ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area + labels = labels[ioa < 0.60] # remove >60% obscured labels + + return labels + + +def mixup(im, labels, im2, labels2): + # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf + r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0 + im = (im * r + im2 * (1 - r)).astype(np.uint8) + labels = np.concatenate((labels, labels2), 0) + return im, labels + + +def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n) + # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio + w1, h1 = box1[2] - box1[0], box1[3] - box1[1] + w2, h2 = box2[2] - box2[0], box2[3] - box2[1] + ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio + return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates diff --git a/Y5_20221014/utils/autoanchor.py b/Y5_20221014/utils/autoanchor.py new file mode 100755 index 0000000..1a4c521 --- /dev/null +++ b/Y5_20221014/utils/autoanchor.py @@ -0,0 +1,170 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +AutoAnchor utils +""" + +import random + +import numpy as np +import torch +import yaml +from tqdm import tqdm + +from utils.general import LOGGER, colorstr, emojis + +PREFIX = colorstr('AutoAnchor: ') + + +def check_anchor_order(m): + # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary + a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer + da = a[-1] - a[0] # delta a + ds = m.stride[-1] - m.stride[0] # delta s + if da and (da.sign() != ds.sign()): # same order + LOGGER.info(f'{PREFIX}Reversing anchor order') + m.anchors[:] = m.anchors.flip(0) + + +def check_anchors(dataset, model, thr=4.0, imgsz=640): + # Check anchor fit to data, recompute if necessary + m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect() + shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True) + scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale + wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh + + def metric(k): # compute metric + r = wh[:, None] / k[None] + x = torch.min(r, 1 / r).min(2)[0] # ratio metric + best = x.max(1)[0] # best_x + aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold + bpr = (best > 1 / thr).float().mean() # best possible recall + return bpr, aat + + stride = m.stride.to(m.anchors.device).view(-1, 1, 1) # model strides + anchors = m.anchors.clone() * stride # current anchors + bpr, aat = metric(anchors.cpu().view(-1, 2)) + s = f'\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). ' + if bpr > 0.98: # threshold to recompute + LOGGER.info(emojis(f'{s}Current anchors are a good fit to dataset ✅')) + else: + LOGGER.info(emojis(f'{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...')) + na = m.anchors.numel() // 2 # number of anchors + try: + anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) + except Exception as e: + LOGGER.info(f'{PREFIX}ERROR: {e}') + new_bpr = metric(anchors)[0] + if new_bpr > bpr: # replace anchors + anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors) + m.anchors[:] = anchors.clone().view_as(m.anchors) + check_anchor_order(m) # must be in pixel-space (not grid-space) + m.anchors /= stride + s = f'{PREFIX}Done ✅ (optional: update model *.yaml to use these anchors in the future)' + else: + s = f'{PREFIX}Done ⚠️ (original anchors better than new anchors, proceeding with original anchors)' + LOGGER.info(emojis(s)) + + +def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): + """ Creates kmeans-evolved anchors from training dataset + + Arguments: + dataset: path to data.yaml, or a loaded dataset + n: number of anchors + img_size: image size used for training + thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0 + gen: generations to evolve anchors using genetic algorithm + verbose: print all results + + Return: + k: kmeans evolved anchors + + Usage: + from utils.autoanchor import *; _ = kmean_anchors() + """ + from scipy.cluster.vq import kmeans + + npr = np.random + thr = 1 / thr + + def metric(k, wh): # compute metrics + r = wh[:, None] / k[None] + x = torch.min(r, 1 / r).min(2)[0] # ratio metric + # x = wh_iou(wh, torch.tensor(k)) # iou metric + return x, x.max(1)[0] # x, best_x + + def anchor_fitness(k): # mutation fitness + _, best = metric(torch.tensor(k, dtype=torch.float32), wh) + return (best * (best > thr).float()).mean() # fitness + + def print_results(k, verbose=True): + k = k[np.argsort(k.prod(1))] # sort small to large + x, best = metric(k, wh0) + bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr + s = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n' \ + f'{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' \ + f'past_thr={x[x > thr].mean():.3f}-mean: ' + for x in k: + s += '%i,%i, ' % (round(x[0]), round(x[1])) + if verbose: + LOGGER.info(s[:-2]) + return k + + if isinstance(dataset, str): # *.yaml file + with open(dataset, errors='ignore') as f: + data_dict = yaml.safe_load(f) # model dict + from utils.dataloaders import LoadImagesAndLabels + dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) + + # Get label wh + shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) + wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh + + # Filter + i = (wh0 < 3.0).any(1).sum() + if i: + LOGGER.info(f'{PREFIX}WARNING: Extremely small objects found: {i} of {len(wh0)} labels are < 3 pixels in size') + wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels + # wh = wh * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 + + # Kmeans init + try: + LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...') + assert n <= len(wh) # apply overdetermined constraint + s = wh.std(0) # sigmas for whitening + k = kmeans(wh / s, n, iter=30)[0] * s # points + assert n == len(k) # kmeans may return fewer points than requested if wh is insufficient or too similar + except Exception: + LOGGER.warning(f'{PREFIX}WARNING: switching strategies from kmeans to random init') + k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size # random init + wh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0)) + k = print_results(k, verbose=False) + + # Plot + # k, d = [None] * 20, [None] * 20 + # for i in tqdm(range(1, 21)): + # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance + # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) + # ax = ax.ravel() + # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') + # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh + # ax[0].hist(wh[wh[:, 0]<100, 0],400) + # ax[1].hist(wh[wh[:, 1]<100, 1],400) + # fig.savefig('wh.png', dpi=200) + + # Evolve + f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma + pbar = tqdm(range(gen), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar + for _ in pbar: + v = np.ones(sh) + while (v == 1).all(): # mutate until a change occurs (prevent duplicates) + v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) + kg = (k.copy() * v).clip(min=2.0) + fg = anchor_fitness(kg) + if fg > f: + f, k = fg, kg.copy() + pbar.desc = f'{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' + if verbose: + print_results(k, verbose) + + return print_results(k) diff --git a/Y5_20221014/utils/autobatch.py b/Y5_20221014/utils/autobatch.py new file mode 100755 index 0000000..7c0ed03 --- /dev/null +++ b/Y5_20221014/utils/autobatch.py @@ -0,0 +1,66 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Auto-batch utils +""" + +from copy import deepcopy + +import numpy as np +import torch + +from utils.general import LOGGER, colorstr, emojis +from utils.torch_utils import profile + + +def check_train_batch_size(model, imgsz=640, amp=True): + # Check YOLOv5 training batch size + with torch.cuda.amp.autocast(amp): + return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size + + +def autobatch(model, imgsz=640, fraction=0.9, batch_size=16): + # Automatically estimate best batch size to use `fraction` of available CUDA memory + # Usage: + # import torch + # from utils.autobatch import autobatch + # model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False) + # print(autobatch(model)) + + # Check device + prefix = colorstr('AutoBatch: ') + LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}') + device = next(model.parameters()).device # get model device + if device.type == 'cpu': + LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}') + return batch_size + + # Inspect CUDA memory + gb = 1 << 30 # bytes to GiB (1024 ** 3) + d = str(device).upper() # 'CUDA:0' + properties = torch.cuda.get_device_properties(device) # device properties + t = properties.total_memory / gb # GiB total + r = torch.cuda.memory_reserved(device) / gb # GiB reserved + a = torch.cuda.memory_allocated(device) / gb # GiB allocated + f = t - (r + a) # GiB free + LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free') + + # Profile batch sizes + batch_sizes = [1, 2, 4, 8, 16] + try: + img = [torch.zeros(b, 3, imgsz, imgsz) for b in batch_sizes] + results = profile(img, model, n=3, device=device) + except Exception as e: + LOGGER.warning(f'{prefix}{e}') + + # Fit a solution + y = [x[2] for x in results if x] # memory [2] + p = np.polyfit(batch_sizes[:len(y)], y, deg=1) # first degree polynomial fit + b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size) + if None in results: # some sizes failed + i = results.index(None) # first fail index + if b >= batch_sizes[i]: # y intercept above failure point + b = batch_sizes[max(i - 1, 0)] # select prior safe point + + fraction = np.polyval(p, b) / t # actual fraction predicted + LOGGER.info(emojis(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅')) + return b diff --git a/Y5_20221014/utils/aws/__init__.py b/Y5_20221014/utils/aws/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/Y5_20221014/utils/aws/mime.sh b/Y5_20221014/utils/aws/mime.sh new file mode 100755 index 0000000..c319a83 --- /dev/null +++ b/Y5_20221014/utils/aws/mime.sh @@ -0,0 +1,26 @@ +# AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/ +# This script will run on every instance restart, not only on first start +# --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA --- + +Content-Type: multipart/mixed; boundary="//" +MIME-Version: 1.0 + +--// +Content-Type: text/cloud-config; charset="us-ascii" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Content-Disposition: attachment; filename="cloud-config.txt" + +#cloud-config +cloud_final_modules: +- [scripts-user, always] + +--// +Content-Type: text/x-shellscript; charset="us-ascii" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Content-Disposition: attachment; filename="userdata.txt" + +#!/bin/bash +# --- paste contents of userdata.sh here --- +--// diff --git a/Y5_20221014/utils/aws/resume.py b/Y5_20221014/utils/aws/resume.py new file mode 100755 index 0000000..b21731c --- /dev/null +++ b/Y5_20221014/utils/aws/resume.py @@ -0,0 +1,40 @@ +# Resume all interrupted trainings in yolov5/ dir including DDP trainings +# Usage: $ python utils/aws/resume.py + +import os +import sys +from pathlib import Path + +import torch +import yaml + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[2] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH + +port = 0 # --master_port +path = Path('').resolve() +for last in path.rglob('*/**/last.pt'): + ckpt = torch.load(last) + if ckpt['optimizer'] is None: + continue + + # Load opt.yaml + with open(last.parent.parent / 'opt.yaml', errors='ignore') as f: + opt = yaml.safe_load(f) + + # Get device count + d = opt['device'].split(',') # devices + nd = len(d) # number of devices + ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel + + if ddp: # multi-GPU + port += 1 + cmd = f'python -m torch.distributed.run --nproc_per_node {nd} --master_port {port} train.py --resume {last}' + else: # single-GPU + cmd = f'python train.py --resume {last}' + + cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread + print(cmd) + os.system(cmd) diff --git a/Y5_20221014/utils/aws/userdata.sh b/Y5_20221014/utils/aws/userdata.sh new file mode 100755 index 0000000..5fc1332 --- /dev/null +++ b/Y5_20221014/utils/aws/userdata.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html +# This script will run only once on first instance start (for a re-start script see mime.sh) +# /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir +# Use >300 GB SSD + +cd home/ubuntu +if [ ! -d yolov5 ]; then + echo "Running first-time script." # install dependencies, download COCO, pull Docker + git clone https://github.com/ultralytics/yolov5 -b master && sudo chmod -R 777 yolov5 + cd yolov5 + bash data/scripts/get_coco.sh && echo "COCO done." & + sudo docker pull ultralytics/yolov5:latest && echo "Docker done." & + python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." & + wait && echo "All tasks done." # finish background tasks +else + echo "Running re-start script." # resume interrupted runs + i=0 + list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour' + while IFS= read -r id; do + ((i++)) + echo "restarting container $i: $id" + sudo docker start $id + # sudo docker exec -it $id python train.py --resume # single-GPU + sudo docker exec -d $id python utils/aws/resume.py # multi-scenario + done <<<"$list" +fi diff --git a/Y5_20221014/utils/benchmarks.py b/Y5_20221014/utils/benchmarks.py new file mode 100755 index 0000000..d0f2a25 --- /dev/null +++ b/Y5_20221014/utils/benchmarks.py @@ -0,0 +1,148 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Run YOLOv5 benchmarks on all supported export formats + +Format | `export.py --include` | Model +--- | --- | --- +PyTorch | - | yolov5s.pt +TorchScript | `torchscript` | yolov5s.torchscript +ONNX | `onnx` | yolov5s.onnx +OpenVINO | `openvino` | yolov5s_openvino_model/ +TensorRT | `engine` | yolov5s.engine +CoreML | `coreml` | yolov5s.mlmodel +TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/ +TensorFlow GraphDef | `pb` | yolov5s.pb +TensorFlow Lite | `tflite` | yolov5s.tflite +TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite +TensorFlow.js | `tfjs` | yolov5s_web_model/ + +Requirements: + $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU + $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU + $ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT + +Usage: + $ python utils/benchmarks.py --weights yolov5s.pt --img 640 +""" + +import argparse +import sys +import time +from pathlib import Path + +import pandas as pd + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH +# ROOT = ROOT.relative_to(Path.cwd()) # relative + +import export +import val +from utils import notebook_init +from utils.general import LOGGER, check_yaml, print_args +from utils.torch_utils import select_device + + +def run( + weights=ROOT / 'yolov5s.pt', # weights path + imgsz=640, # inference size (pixels) + batch_size=1, # batch size + data=ROOT / 'data/coco128.yaml', # dataset.yaml path + device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu + half=False, # use FP16 half-precision inference + test=False, # test exports only + pt_only=False, # test PyTorch only +): + y, t = [], time.time() + device = select_device(device) + for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable) + try: + assert i != 9, 'Edge TPU not supported' + assert i != 10, 'TF.js not supported' + if device.type != 'cpu': + assert gpu, f'{name} inference not supported on GPU' + + # Export + if f == '-': + w = weights # PyTorch format + else: + w = export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # all others + assert suffix in str(w), 'export failed' + + # Validate + result = val.run(data, w, batch_size, imgsz, plots=False, device=device, task='benchmark', half=half) + metrics = result[0] # metrics (mp, mr, map50, map, *losses(box, obj, cls)) + speeds = result[2] # times (preprocess, inference, postprocess) + y.append([name, round(metrics[3], 4), round(speeds[1], 2)]) # mAP, t_inference + except Exception as e: + LOGGER.warning(f'WARNING: Benchmark failure for {name}: {e}') + y.append([name, None, None]) # mAP, t_inference + if pt_only and i == 0: + break # break after PyTorch + + # Print results + LOGGER.info('\n') + parse_opt() + notebook_init() # print system info + py = pd.DataFrame(y, columns=['Format', 'mAP@0.5:0.95', 'Inference time (ms)'] if map else ['Format', 'Export', '']) + LOGGER.info(f'\nBenchmarks complete ({time.time() - t:.2f}s)') + LOGGER.info(str(py if map else py.iloc[:, :2])) + return py + + +def test( + weights=ROOT / 'yolov5s.pt', # weights path + imgsz=640, # inference size (pixels) + batch_size=1, # batch size + data=ROOT / 'data/coco128.yaml', # dataset.yaml path + device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu + half=False, # use FP16 half-precision inference + test=False, # test exports only + pt_only=False, # test PyTorch only +): + y, t = [], time.time() + device = select_device(device) + for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable) + try: + w = weights if f == '-' else \ + export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1] # weights + assert suffix in str(w), 'export failed' + y.append([name, True]) + except Exception: + y.append([name, False]) # mAP, t_inference + + # Print results + LOGGER.info('\n') + parse_opt() + notebook_init() # print system info + py = pd.DataFrame(y, columns=['Format', 'Export']) + LOGGER.info(f'\nExports complete ({time.time() - t:.2f}s)') + LOGGER.info(str(py)) + return py + + +def parse_opt(): + parser = argparse.ArgumentParser() + parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path') + parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)') + parser.add_argument('--batch-size', type=int, default=1, help='batch size') + parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path') + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') + parser.add_argument('--test', action='store_true', help='test exports only') + parser.add_argument('--pt-only', action='store_true', help='test PyTorch only') + opt = parser.parse_args() + opt.data = check_yaml(opt.data) # check YAML + print_args(vars(opt)) + return opt + + +def main(opt): + test(**vars(opt)) if opt.test else run(**vars(opt)) + + +if __name__ == "__main__": + opt = parse_opt() + main(opt) diff --git a/Y5_20221014/utils/callbacks.py b/Y5_20221014/utils/callbacks.py new file mode 100755 index 0000000..2b32df0 --- /dev/null +++ b/Y5_20221014/utils/callbacks.py @@ -0,0 +1,71 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Callback utils +""" + + +class Callbacks: + """" + Handles all registered callbacks for YOLOv5 Hooks + """ + + def __init__(self): + # Define the available callbacks + self._callbacks = { + 'on_pretrain_routine_start': [], + 'on_pretrain_routine_end': [], + 'on_train_start': [], + 'on_train_epoch_start': [], + 'on_train_batch_start': [], + 'optimizer_step': [], + 'on_before_zero_grad': [], + 'on_train_batch_end': [], + 'on_train_epoch_end': [], + 'on_val_start': [], + 'on_val_batch_start': [], + 'on_val_image_end': [], + 'on_val_batch_end': [], + 'on_val_end': [], + 'on_fit_epoch_end': [], # fit = train + val + 'on_model_save': [], + 'on_train_end': [], + 'on_params_update': [], + 'teardown': [],} + self.stop_training = False # set True to interrupt training + + def register_action(self, hook, name='', callback=None): + """ + Register a new action to a callback hook + + Args: + hook: The callback hook name to register the action to + name: The name of the action for later reference + callback: The callback to fire + """ + assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}" + assert callable(callback), f"callback '{callback}' is not callable" + self._callbacks[hook].append({'name': name, 'callback': callback}) + + def get_registered_actions(self, hook=None): + """" + Returns all the registered actions by callback hook + + Args: + hook: The name of the hook to check, defaults to all + """ + return self._callbacks[hook] if hook else self._callbacks + + def run(self, hook, *args, **kwargs): + """ + Loop through the registered actions and fire all callbacks + + Args: + hook: The name of the hook to check, defaults to all + args: Arguments to receive from YOLOv5 + kwargs: Keyword Arguments to receive from YOLOv5 + """ + + assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}" + + for logger in self._callbacks[hook]: + logger['callback'](*args, **kwargs) diff --git a/Y5_20221014/utils/dataloaders.py b/Y5_20221014/utils/dataloaders.py new file mode 100755 index 0000000..4690f0c --- /dev/null +++ b/Y5_20221014/utils/dataloaders.py @@ -0,0 +1,1087 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Dataloaders and dataset utils +""" + +import glob +import hashlib +import json +import math +import os +import random +import shutil +import time +from itertools import repeat +from multiprocessing.pool import Pool, ThreadPool +from pathlib import Path +from threading import Thread +from urllib.parse import urlparse +from zipfile import ZipFile + +import numpy as np +import torch +import torch.nn.functional as F +import yaml +from PIL import ExifTags, Image, ImageOps +from torch.utils.data import DataLoader, Dataset, dataloader, distributed +from tqdm import tqdm + +from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective +from utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, check_dataset, check_requirements, check_yaml, clean_str, + cv2, segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn) +from utils.torch_utils import torch_distributed_zero_first + +# Parameters +HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data' +IMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp' # include image suffixes +VID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv' # include video suffixes +BAR_FORMAT = '{l_bar}{bar:10}{r_bar}{bar:-10b}' # tqdm bar format +LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html + +# Get orientation exif tag +for orientation in ExifTags.TAGS.keys(): + if ExifTags.TAGS[orientation] == 'Orientation': + break + + +def get_hash(paths): + # Returns a single hash value of a list of paths (files or dirs) + size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes + h = hashlib.md5(str(size).encode()) # hash sizes + h.update(''.join(paths).encode()) # hash paths + return h.hexdigest() # return hash + + +def exif_size(img): + # Returns exif-corrected PIL size + s = img.size # (width, height) + try: + rotation = dict(img._getexif().items())[orientation] + if rotation in [6, 8]: # rotation 270 or 90 + s = (s[1], s[0]) + except Exception: + pass + + return s + + +def exif_transpose(image): + """ + Transpose a PIL image accordingly if it has an EXIF Orientation tag. + Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose() + + :param image: The image to transpose. + :return: An image. + """ + exif = image.getexif() + orientation = exif.get(0x0112, 1) # default 1 + if orientation > 1: + method = { + 2: Image.FLIP_LEFT_RIGHT, + 3: Image.ROTATE_180, + 4: Image.FLIP_TOP_BOTTOM, + 5: Image.TRANSPOSE, + 6: Image.ROTATE_270, + 7: Image.TRANSVERSE, + 8: Image.ROTATE_90,}.get(orientation) + if method is not None: + image = image.transpose(method) + del exif[0x0112] + image.info["exif"] = exif.tobytes() + return image + + +def create_dataloader(path, + imgsz, + batch_size, + stride, + single_cls=False, + hyp=None, + augment=False, + cache=False, + pad=0.0, + rect=False, + rank=-1, + workers=8, + image_weights=False, + quad=False, + prefix='', + shuffle=False): + if rect and shuffle: + LOGGER.warning('WARNING: --rect is incompatible with DataLoader shuffle, setting shuffle=False') + shuffle = False + with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP + dataset = LoadImagesAndLabels( + path, + imgsz, + batch_size, + augment=augment, # augmentation + hyp=hyp, # hyperparameters + rect=rect, # rectangular batches + cache_images=cache, + single_cls=single_cls, + stride=int(stride), + pad=pad, + image_weights=image_weights, + prefix=prefix) + + batch_size = min(batch_size, len(dataset)) + nd = torch.cuda.device_count() # number of CUDA devices + nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers + sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle) + loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates + return loader(dataset, + batch_size=batch_size, + shuffle=shuffle and sampler is None, + num_workers=nw, + sampler=sampler, + pin_memory=True, + collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn), dataset + + +class InfiniteDataLoader(dataloader.DataLoader): + """ Dataloader that reuses workers + + Uses same syntax as vanilla DataLoader + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler)) + self.iterator = super().__iter__() + + def __len__(self): + return len(self.batch_sampler.sampler) + + def __iter__(self): + for _ in range(len(self)): + yield next(self.iterator) + + +class _RepeatSampler: + """ Sampler that repeats forever + + Args: + sampler (Sampler) + """ + + def __init__(self, sampler): + self.sampler = sampler + + def __iter__(self): + while True: + yield from iter(self.sampler) + + +class LoadImages: + # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4` + def __init__(self, path, img_size=640, stride=32, auto=True): + p = str(Path(path).resolve()) # os-agnostic absolute path + if '*' in p: + files = sorted(glob.glob(p, recursive=True)) # glob + elif os.path.isdir(p): + files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir + elif os.path.isfile(p): + files = [p] # files + else: + raise Exception(f'ERROR: {p} does not exist') + + images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS] + videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS] + ni, nv = len(images), len(videos) + + self.img_size = img_size + self.stride = stride + self.files = images + videos + self.nf = ni + nv # number of files + self.video_flag = [False] * ni + [True] * nv + self.mode = 'image' + self.auto = auto + if any(videos): + self.new_video(videos[0]) # new video + else: + self.cap = None + assert self.nf > 0, f'No images or videos found in {p}. ' \ + f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}' + + def __iter__(self): + self.count = 0 + return self + + def __next__(self): + if self.count == self.nf: + raise StopIteration + path = self.files[self.count] + + if self.video_flag[self.count]: + # Read video + self.mode = 'video' + ret_val, img0 = self.cap.read() + while not ret_val: + self.count += 1 + self.cap.release() + if self.count == self.nf: # last video + raise StopIteration + path = self.files[self.count] + self.new_video(path) + ret_val, img0 = self.cap.read() + + self.frame += 1 + s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ' + + else: + # Read image + self.count += 1 + img0 = cv2.imread(path) # BGR + assert img0 is not None, f'Image Not Found {path}' + s = f'image {self.count}/{self.nf} {path}: ' + + # Padded resize + img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0] + + # Convert + img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB + img = np.ascontiguousarray(img) + + return path, img, img0, self.cap, s + + def new_video(self, path): + self.frame = 0 + self.cap = cv2.VideoCapture(path) + self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) + + def __len__(self): + return self.nf # number of files + + +class LoadWebcam: # for inference + # YOLOv5 local webcam dataloader, i.e. `python detect.py --source 0` + def __init__(self, pipe='0', img_size=640, stride=32): + self.img_size = img_size + self.stride = stride + self.pipe = eval(pipe) if pipe.isnumeric() else pipe + self.cap = cv2.VideoCapture(self.pipe) # video capture object + self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size + + def __iter__(self): + self.count = -1 + return self + + def __next__(self): + self.count += 1 + if cv2.waitKey(1) == ord('q'): # q to quit + self.cap.release() + cv2.destroyAllWindows() + raise StopIteration + + # Read frame + ret_val, img0 = self.cap.read() + img0 = cv2.flip(img0, 1) # flip left-right + + # Print + assert ret_val, f'Camera Error {self.pipe}' + img_path = 'webcam.jpg' + s = f'webcam {self.count}: ' + + # Padded resize + img = letterbox(img0, self.img_size, stride=self.stride)[0] + + # Convert + img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB + img = np.ascontiguousarray(img) + + return img_path, img, img0, None, s + + def __len__(self): + return 0 + + +class LoadStreams: + # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP streams` + def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True): + self.mode = 'stream' + self.img_size = img_size + self.stride = stride + + if os.path.isfile(sources): + with open(sources) as f: + sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())] + else: + sources = [sources] + + n = len(sources) + self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n + self.sources = [clean_str(x) for x in sources] # clean source names for later + self.auto = auto + for i, s in enumerate(sources): # index, source + # Start thread to read frames from video stream + st = f'{i + 1}/{n}: {s}... ' + if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'): # if source is YouTube video + check_requirements(('pafy', 'youtube_dl==2020.12.2')) + import pafy + s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL + s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam + cap = cv2.VideoCapture(s) + assert cap.isOpened(), f'{st}Failed to open {s}' + w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + fps = cap.get(cv2.CAP_PROP_FPS) # warning: may return 0 or nan + self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback + self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30 # 30 FPS fallback + + _, self.imgs[i] = cap.read() # guarantee first frame + self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True) + LOGGER.info(f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)") + self.threads[i].start() + LOGGER.info('') # newline + + # check for common shapes + s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs]) + self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal + if not self.rect: + LOGGER.warning('WARNING: Stream shapes differ. For optimal performance supply similarly-shaped streams.') + + def update(self, i, cap, stream): + # Read stream `i` frames in daemon thread + n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame + while cap.isOpened() and n < f: + n += 1 + # _, self.imgs[index] = cap.read() + cap.grab() + if n % read == 0: + success, im = cap.retrieve() + if success: + self.imgs[i] = im + else: + LOGGER.warning('WARNING: Video stream unresponsive, please check your IP camera connection.') + self.imgs[i] = np.zeros_like(self.imgs[i]) + cap.open(stream) # re-open stream if signal was lost + time.sleep(1 / self.fps[i]) # wait time + + def __iter__(self): + self.count = -1 + return self + + def __next__(self): + self.count += 1 + if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit + cv2.destroyAllWindows() + raise StopIteration + + # Letterbox + img0 = self.imgs.copy() + img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0] + + # Stack + img = np.stack(img, 0) + + # Convert + img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW + img = np.ascontiguousarray(img) + + return self.sources, img, img0, None, '' + + def __len__(self): + return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years + + +def img2label_paths(img_paths): + # Define label paths as a function of image paths + sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}' # /images/, /labels/ substrings + return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths] + + +class LoadImagesAndLabels(Dataset): + # YOLOv5 train_loader/val_loader, loads images and labels for training and validation + cache_version = 0.6 # dataset labels *.cache version + rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4] + + def __init__(self, + path, + img_size=640, + batch_size=16, + augment=False, + hyp=None, + rect=False, + image_weights=False, + cache_images=False, + single_cls=False, + stride=32, + pad=0.0, + prefix=''): + self.img_size = img_size + self.augment = augment + self.hyp = hyp + self.image_weights = image_weights + self.rect = False if image_weights else rect + self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training) + self.mosaic_border = [-img_size // 2, -img_size // 2] + self.stride = stride + self.path = path + self.albumentations = Albumentations() if augment else None + + try: + f = [] # image files + for p in path if isinstance(path, list) else [path]: + p = Path(p) # os-agnostic + if p.is_dir(): # dir + f += glob.glob(str(p / '**' / '*.*'), recursive=True) + # f = list(p.rglob('*.*')) # pathlib + elif p.is_file(): # file + with open(p) as t: + t = t.read().strip().splitlines() + parent = str(p.parent) + os.sep + f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path + # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib) + else: + raise Exception(f'{prefix}{p} does not exist') + self.im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS) + # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib + assert self.im_files, f'{prefix}No images found' + except Exception as e: + raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}') + + # Check cache + self.label_files = img2label_paths(self.im_files) # labels + cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') + try: + cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict + assert cache['version'] == self.cache_version # same version + assert cache['hash'] == get_hash(self.label_files + self.im_files) # same hash + except Exception: + cache, exists = self.cache_labels(cache_path, prefix), False # cache + + # Display cache + nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupt, total + if exists and LOCAL_RANK in {-1, 0}: + d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupt" + tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=BAR_FORMAT) # display cache results + if cache['msgs']: + LOGGER.info('\n'.join(cache['msgs'])) # display warnings + assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}' + + # Read cache + [cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items + labels, shapes, self.segments = zip(*cache.values()) + self.labels = list(labels) + self.shapes = np.array(shapes, dtype=np.float64) + self.im_files = list(cache.keys()) # update + self.label_files = img2label_paths(cache.keys()) # update + n = len(shapes) # number of images + bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index + nb = bi[-1] + 1 # number of batches + self.batch = bi # batch index of image + self.n = n + self.indices = range(n) + + # Update labels + include_class = [] # filter labels to include only these classes (optional) + include_class_array = np.array(include_class).reshape(1, -1) + for i, (label, segment) in enumerate(zip(self.labels, self.segments)): + if include_class: + j = (label[:, 0:1] == include_class_array).any(1) + self.labels[i] = label[j] + if segment: + self.segments[i] = segment[j] + if single_cls: # single-class training, merge all classes into 0 + self.labels[i][:, 0] = 0 + if segment: + self.segments[i][:, 0] = 0 + + # Rectangular Training + if self.rect: + # Sort by aspect ratio + s = self.shapes # wh + ar = s[:, 1] / s[:, 0] # aspect ratio + irect = ar.argsort() + self.im_files = [self.im_files[i] for i in irect] + self.label_files = [self.label_files[i] for i in irect] + self.labels = [self.labels[i] for i in irect] + self.shapes = s[irect] # wh + ar = ar[irect] + + # Set training image shapes + shapes = [[1, 1]] * nb + for i in range(nb): + ari = ar[bi == i] + mini, maxi = ari.min(), ari.max() + if maxi < 1: + shapes[i] = [maxi, 1] + elif mini > 1: + shapes[i] = [1, 1 / mini] + + self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride + + # Cache images into RAM/disk for faster training (WARNING: large datasets may exceed system resources) + self.ims = [None] * n + self.npy_files = [Path(f).with_suffix('.npy') for f in self.im_files] + if cache_images: + gb = 0 # Gigabytes of cached images + self.im_hw0, self.im_hw = [None] * n, [None] * n + fcn = self.cache_images_to_disk if cache_images == 'disk' else self.load_image + results = ThreadPool(NUM_THREADS).imap(fcn, range(n)) + pbar = tqdm(enumerate(results), total=n, bar_format=BAR_FORMAT, disable=LOCAL_RANK > 0) + for i, x in pbar: + if cache_images == 'disk': + gb += self.npy_files[i].stat().st_size + else: # 'ram' + self.ims[i], self.im_hw0[i], self.im_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i) + gb += self.ims[i].nbytes + pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})' + pbar.close() + + def cache_labels(self, path=Path('./labels.cache'), prefix=''): + # Cache dataset labels, check images and read shapes + x = {} # dict + nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages + desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..." + with Pool(NUM_THREADS) as pool: + pbar = tqdm(pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix))), + desc=desc, + total=len(self.im_files), + bar_format=BAR_FORMAT) + for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar: + nm += nm_f + nf += nf_f + ne += ne_f + nc += nc_f + if im_file: + x[im_file] = [lb, shape, segments] + if msg: + msgs.append(msg) + pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupt" + + pbar.close() + if msgs: + LOGGER.info('\n'.join(msgs)) + if nf == 0: + LOGGER.warning(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}') + x['hash'] = get_hash(self.label_files + self.im_files) + x['results'] = nf, nm, ne, nc, len(self.im_files) + x['msgs'] = msgs # warnings + x['version'] = self.cache_version # cache version + try: + np.save(path, x) # save cache for next time + path.with_suffix('.cache.npy').rename(path) # remove .npy suffix + LOGGER.info(f'{prefix}New cache created: {path}') + except Exception as e: + LOGGER.warning(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # not writeable + return x + + def __len__(self): + return len(self.im_files) + + # def __iter__(self): + # self.count = -1 + # print('ran dataset iter') + # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF) + # return self + + def __getitem__(self, index): + index = self.indices[index] # linear, shuffled, or image_weights + + hyp = self.hyp + mosaic = self.mosaic and random.random() < hyp['mosaic'] + if mosaic: + # Load mosaic + img, labels = self.load_mosaic(index) + shapes = None + + # MixUp augmentation + if random.random() < hyp['mixup']: + img, labels = mixup(img, labels, *self.load_mosaic(random.randint(0, self.n - 1))) + + else: + # Load image + img, (h0, w0), (h, w) = self.load_image(index) + + # Letterbox + shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape + img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment) + shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling + + labels = self.labels[index].copy() + if labels.size: # normalized xywh to pixel xyxy format + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1]) + + if self.augment: + img, labels = random_perspective(img, + labels, + degrees=hyp['degrees'], + translate=hyp['translate'], + scale=hyp['scale'], + shear=hyp['shear'], + perspective=hyp['perspective']) + + nl = len(labels) # number of labels + if nl: + labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3) + + if self.augment: + # Albumentations + img, labels = self.albumentations(img, labels) + nl = len(labels) # update after albumentations + + # HSV color-space + augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v']) + + # Flip up-down + if random.random() < hyp['flipud']: + img = np.flipud(img) + if nl: + labels[:, 2] = 1 - labels[:, 2] + + # Flip left-right + if random.random() < hyp['fliplr']: + img = np.fliplr(img) + if nl: + labels[:, 1] = 1 - labels[:, 1] + + # Cutouts + # labels = cutout(img, labels, p=0.5) + # nl = len(labels) # update after cutout + + labels_out = torch.zeros((nl, 6)) + if nl: + labels_out[:, 1:] = torch.from_numpy(labels) + + # Convert + img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB + img = np.ascontiguousarray(img) + + return torch.from_numpy(img), labels_out, self.im_files[index], shapes + + def load_image(self, i): + # Loads 1 image from dataset index 'i', returns (im, original hw, resized hw) + im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i], + if im is None: # not cached in RAM + if fn.exists(): # load npy + im = np.load(fn) + else: # read image + im = cv2.imread(f) # BGR + assert im is not None, f'Image Not Found {f}' + h0, w0 = im.shape[:2] # orig hw + r = self.img_size / max(h0, w0) # ratio + if r != 1: # if sizes are not equal + interp = cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA + im = cv2.resize(im, (int(w0 * r), int(h0 * r)), interpolation=interp) + return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized + else: + return self.ims[i], self.im_hw0[i], self.im_hw[i] # im, hw_original, hw_resized + + def cache_images_to_disk(self, i): + # Saves an image as an *.npy file for faster loading + f = self.npy_files[i] + if not f.exists(): + np.save(f.as_posix(), cv2.imread(self.im_files[i])) + + def load_mosaic(self, index): + # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic + labels4, segments4 = [], [] + s = self.img_size + yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y + indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices + random.shuffle(indices) + for i, index in enumerate(indices): + # Load image + img, _, (h, w) = self.load_image(index) + + # place img in img4 + if i == 0: # top left + img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles + x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image) + x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image) + elif i == 1: # top right + x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc + x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h + elif i == 2: # bottom left + x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) + x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) + elif i == 3: # bottom right + x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) + x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) + + img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] + padw = x1a - x1b + padh = y1a - y1b + + # Labels + labels, segments = self.labels[index].copy(), self.segments[index].copy() + if labels.size: + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format + segments = [xyn2xy(x, w, h, padw, padh) for x in segments] + labels4.append(labels) + segments4.extend(segments) + + # Concat/clip labels + labels4 = np.concatenate(labels4, 0) + for x in (labels4[:, 1:], *segments4): + np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() + # img4, labels4 = replicate(img4, labels4) # replicate + + # Augment + img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste']) + img4, labels4 = random_perspective(img4, + labels4, + segments4, + degrees=self.hyp['degrees'], + translate=self.hyp['translate'], + scale=self.hyp['scale'], + shear=self.hyp['shear'], + perspective=self.hyp['perspective'], + border=self.mosaic_border) # border to remove + + return img4, labels4 + + def load_mosaic9(self, index): + # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic + labels9, segments9 = [], [] + s = self.img_size + indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices + random.shuffle(indices) + hp, wp = -1, -1 # height, width previous + for i, index in enumerate(indices): + # Load image + img, _, (h, w) = self.load_image(index) + + # place img in img9 + if i == 0: # center + img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles + h0, w0 = h, w + c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates + elif i == 1: # top + c = s, s - h, s + w, s + elif i == 2: # top right + c = s + wp, s - h, s + wp + w, s + elif i == 3: # right + c = s + w0, s, s + w0 + w, s + h + elif i == 4: # bottom right + c = s + w0, s + hp, s + w0 + w, s + hp + h + elif i == 5: # bottom + c = s + w0 - w, s + h0, s + w0, s + h0 + h + elif i == 6: # bottom left + c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h + elif i == 7: # left + c = s - w, s + h0 - h, s, s + h0 + elif i == 8: # top left + c = s - w, s + h0 - hp - h, s, s + h0 - hp + + padx, pady = c[:2] + x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords + + # Labels + labels, segments = self.labels[index].copy(), self.segments[index].copy() + if labels.size: + labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format + segments = [xyn2xy(x, w, h, padx, pady) for x in segments] + labels9.append(labels) + segments9.extend(segments) + + # Image + img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax] + hp, wp = h, w # height, width previous + + # Offset + yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y + img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s] + + # Concat/clip labels + labels9 = np.concatenate(labels9, 0) + labels9[:, [1, 3]] -= xc + labels9[:, [2, 4]] -= yc + c = np.array([xc, yc]) # centers + segments9 = [x - c for x in segments9] + + for x in (labels9[:, 1:], *segments9): + np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() + # img9, labels9 = replicate(img9, labels9) # replicate + + # Augment + img9, labels9 = random_perspective(img9, + labels9, + segments9, + degrees=self.hyp['degrees'], + translate=self.hyp['translate'], + scale=self.hyp['scale'], + shear=self.hyp['shear'], + perspective=self.hyp['perspective'], + border=self.mosaic_border) # border to remove + + return img9, labels9 + + @staticmethod + def collate_fn(batch): + im, label, path, shapes = zip(*batch) # transposed + for i, lb in enumerate(label): + lb[:, 0] = i # add target image index for build_targets() + return torch.stack(im, 0), torch.cat(label, 0), path, shapes + + @staticmethod + def collate_fn4(batch): + img, label, path, shapes = zip(*batch) # transposed + n = len(shapes) // 4 + im4, label4, path4, shapes4 = [], [], path[:n], shapes[:n] + + ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]]) + wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]]) + s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale + for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW + i *= 4 + if random.random() < 0.5: + im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2.0, mode='bilinear', + align_corners=False)[0].type(img[i].type()) + lb = label[i] + else: + im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2) + lb = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s + im4.append(im) + label4.append(lb) + + for i, lb in enumerate(label4): + lb[:, 0] = i # add target image index for build_targets() + + return torch.stack(im4, 0), torch.cat(label4, 0), path4, shapes4 + + +# Ancillary functions -------------------------------------------------------------------------------------------------- +def create_folder(path='./new'): + # Create folder + if os.path.exists(path): + shutil.rmtree(path) # delete output folder + os.makedirs(path) # make new output folder + + +def flatten_recursive(path=DATASETS_DIR / 'coco128'): + # Flatten a recursive directory by bringing all files to top level + new_path = Path(str(path) + '_flat') + create_folder(new_path) + for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)): + shutil.copyfile(file, new_path / Path(file).name) + + +def extract_boxes(path=DATASETS_DIR / 'coco128'): # from utils.dataloaders import *; extract_boxes() + # Convert detection dataset into classification dataset, with one directory per class + path = Path(path) # images dir + shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing + files = list(path.rglob('*.*')) + n = len(files) # number of files + for im_file in tqdm(files, total=n): + if im_file.suffix[1:] in IMG_FORMATS: + # image + im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB + h, w = im.shape[:2] + + # labels + lb_file = Path(img2label_paths([str(im_file)])[0]) + if Path(lb_file).exists(): + with open(lb_file) as f: + lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels + + for j, x in enumerate(lb): + c = int(x[0]) # class + f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename + if not f.parent.is_dir(): + f.parent.mkdir(parents=True) + + b = x[1:] * [w, h, w, h] # box + # b[2:] = b[2:].max() # rectangle to square + b[2:] = b[2:] * 1.2 + 3 # pad + b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) + + b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image + b[[1, 3]] = np.clip(b[[1, 3]], 0, h) + assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}' + + +def autosplit(path=DATASETS_DIR / 'coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False): + """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files + Usage: from utils.dataloaders import *; autosplit() + Arguments + path: Path to images directory + weights: Train, val, test weights (list, tuple) + annotated_only: Only use images with an annotated txt file + """ + path = Path(path) # images dir + files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) # image files only + n = len(files) # number of files + random.seed(0) # for reproducibility + indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split + + txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files + [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing + + print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only) + for i, img in tqdm(zip(indices, files), total=n): + if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label + with open(path.parent / txt[i], 'a') as f: + f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file + + +def verify_image_label(args): + # Verify one image-label pair + im_file, lb_file, prefix = args + nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments + try: + # verify images + im = Image.open(im_file) + im.verify() # PIL verify + shape = exif_size(im) # image size + assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels' + assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}' + if im.format.lower() in ('jpg', 'jpeg'): + with open(im_file, 'rb') as f: + f.seek(-2, 2) + if f.read() != b'\xff\xd9': # corrupt JPEG + ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100) + msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved' + + # verify labels + if os.path.isfile(lb_file): + nf = 1 # label found + with open(lb_file) as f: + lb = [x.split() for x in f.read().strip().splitlines() if len(x)] + if any(len(x) > 6 for x in lb): # is segment + classes = np.array([x[0] for x in lb], dtype=np.float32) + segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...) + lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh) + lb = np.array(lb, dtype=np.float32) + nl = len(lb) + if nl: + assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected' + assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}' + assert (lb[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}' + _, i = np.unique(lb, axis=0, return_index=True) + if len(i) < nl: # duplicate row check + lb = lb[i] # remove duplicates + if segments: + segments = segments[i] + msg = f'{prefix}WARNING: {im_file}: {nl - len(i)} duplicate labels removed' + else: + ne = 1 # label empty + lb = np.zeros((0, 5), dtype=np.float32) + else: + nm = 1 # label missing + lb = np.zeros((0, 5), dtype=np.float32) + return im_file, lb, shape, segments, nm, nf, ne, nc, msg + except Exception as e: + nc = 1 + msg = f'{prefix}WARNING: {im_file}: ignoring corrupt image/label: {e}' + return [None, None, None, None, nm, nf, ne, nc, msg] + + +def dataset_stats(path='coco128.yaml', autodownload=False, verbose=False, profile=False, hub=False): + """ Return dataset statistics dictionary with images and instances counts per split per class + To run in parent directory: export PYTHONPATH="$PWD/yolov5" + Usage1: from utils.dataloaders import *; dataset_stats('coco128.yaml', autodownload=True) + Usage2: from utils.dataloaders import *; dataset_stats('path/to/coco128_with_yaml.zip') + Arguments + path: Path to data.yaml or data.zip (with data.yaml inside data.zip) + autodownload: Attempt to download dataset if not found locally + verbose: Print stats dictionary + """ + + def _round_labels(labels): + # Update labels to integer class and 6 decimal place floats + return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels] + + def _find_yaml(dir): + # Return data.yaml file + files = list(dir.glob('*.yaml')) or list(dir.rglob('*.yaml')) # try root level first and then recursive + assert files, f'No *.yaml file found in {dir}' + if len(files) > 1: + files = [f for f in files if f.stem == dir.stem] # prefer *.yaml files that match dir name + assert files, f'Multiple *.yaml files found in {dir}, only 1 *.yaml file allowed' + assert len(files) == 1, f'Multiple *.yaml files found: {files}, only 1 *.yaml file allowed in {dir}' + return files[0] + + def _unzip(path): + # Unzip data.zip + if str(path).endswith('.zip'): # path is data.zip + assert Path(path).is_file(), f'Error unzipping {path}, file not found' + ZipFile(path).extractall(path=path.parent) # unzip + dir = path.with_suffix('') # dataset directory == zip name + assert dir.is_dir(), f'Error unzipping {path}, {dir} not found. path/to/abc.zip MUST unzip to path/to/abc/' + return True, str(dir), _find_yaml(dir) # zipped, data_dir, yaml_path + else: # path is data.yaml + return False, None, path + + def _hub_ops(f, max_dim=1920): + # HUB ops for 1 image 'f': resize and save at reduced quality in /dataset-hub for web/app viewing + f_new = im_dir / Path(f).name # dataset-hub image filename + try: # use PIL + im = Image.open(f) + r = max_dim / max(im.height, im.width) # ratio + if r < 1.0: # image too large + im = im.resize((int(im.width * r), int(im.height * r))) + im.save(f_new, 'JPEG', quality=75, optimize=True) # save + except Exception as e: # use OpenCV + print(f'WARNING: HUB ops PIL failure {f}: {e}') + im = cv2.imread(f) + im_height, im_width = im.shape[:2] + r = max_dim / max(im_height, im_width) # ratio + if r < 1.0: # image too large + im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA) + cv2.imwrite(str(f_new), im) + + zipped, data_dir, yaml_path = _unzip(Path(path)) + with open(check_yaml(yaml_path), errors='ignore') as f: + data = yaml.safe_load(f) # data dict + if zipped: + data['path'] = data_dir # TODO: should this be dir.resolve()? + check_dataset(data, autodownload) # download dataset if missing + hub_dir = Path(data['path'] + ('-hub' if hub else '')) + stats = {'nc': data['nc'], 'names': data['names']} # statistics dictionary + for split in 'train', 'val', 'test': + if data.get(split) is None: + stats[split] = None # i.e. no test set + continue + x = [] + dataset = LoadImagesAndLabels(data[split]) # load dataset + for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'): + x.append(np.bincount(label[:, 0].astype(int), minlength=data['nc'])) + x = np.array(x) # shape(128x80) + stats[split] = { + 'instance_stats': { + 'total': int(x.sum()), + 'per_class': x.sum(0).tolist()}, + 'image_stats': { + 'total': dataset.n, + 'unlabelled': int(np.all(x == 0, 1).sum()), + 'per_class': (x > 0).sum(0).tolist()}, + 'labels': [{ + str(Path(k).name): _round_labels(v.tolist())} for k, v in zip(dataset.im_files, dataset.labels)]} + + if hub: + im_dir = hub_dir / 'images' + im_dir.mkdir(parents=True, exist_ok=True) + for _ in tqdm(ThreadPool(NUM_THREADS).imap(_hub_ops, dataset.im_files), total=dataset.n, desc='HUB Ops'): + pass + + # Profile + stats_path = hub_dir / 'stats.json' + if profile: + for _ in range(1): + file = stats_path.with_suffix('.npy') + t1 = time.time() + np.save(file, stats) + t2 = time.time() + x = np.load(file, allow_pickle=True) + print(f'stats.npy times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write') + + file = stats_path.with_suffix('.json') + t1 = time.time() + with open(file, 'w') as f: + json.dump(stats, f) # save stats *.json + t2 = time.time() + with open(file) as f: + x = json.load(f) # load hyps dict + print(f'stats.json times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write') + + # Save, print and return + if hub: + print(f'Saving {stats_path.resolve()}...') + with open(stats_path, 'w') as f: + json.dump(stats, f) # save stats.json + if verbose: + print(json.dumps(stats, indent=2, sort_keys=False)) + return stats diff --git a/Y5_20221014/utils/docker/.dockerignore b/Y5_20221014/utils/docker/.dockerignore new file mode 100755 index 0000000..af51ccc --- /dev/null +++ b/Y5_20221014/utils/docker/.dockerignore @@ -0,0 +1,222 @@ +# Repo-specific DockerIgnore ------------------------------------------------------------------------------------------- +#.git +.cache +.idea +runs +output +coco +storage.googleapis.com + +data/samples/* +**/results*.csv +*.jpg + +# Neural Network weights ----------------------------------------------------------------------------------------------- +**/*.pt +**/*.pth +**/*.onnx +**/*.engine +**/*.mlmodel +**/*.torchscript +**/*.torchscript.pt +**/*.tflite +**/*.h5 +**/*.pb +*_saved_model/ +*_web_model/ +*_openvino_model/ + +# Below Copied From .gitignore ----------------------------------------------------------------------------------------- +# Below Copied From .gitignore ----------------------------------------------------------------------------------------- + + +# GitHub Python GitIgnore ---------------------------------------------------------------------------------------------- +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +wandb/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv* +venv*/ +ENV*/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + + +# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore ----------------------------------------------- + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon +Icon? + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + + +# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/* +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries +.html # Bokeh Plots +.pg # TensorFlow Frozen Graphs +.avi # videos + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ +cmake-build-release/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties diff --git a/Y5_20221014/utils/docker/Dockerfile b/Y5_20221014/utils/docker/Dockerfile new file mode 100755 index 0000000..a5fc7cb --- /dev/null +++ b/Y5_20221014/utils/docker/Dockerfile @@ -0,0 +1,68 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Builds ultralytics/yolov5:latest image on DockerHub https://hub.docker.com/r/ultralytics/yolov5 +# Image is CUDA-optimized for YOLOv5 single/multi-GPU training and inference + +# Start FROM NVIDIA PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch +FROM nvcr.io/nvidia/pytorch:22.05-py3 +RUN rm -rf /opt/pytorch # remove 1.2GB dir + +# Downloads to user config dir +ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/ + +# Install linux packages +RUN apt update && apt install --no-install-recommends -y zip htop screen libgl1-mesa-glx + +# Install pip packages +COPY requirements.txt . +RUN python -m pip install --upgrade pip +RUN pip uninstall -y torch torchvision torchtext Pillow +RUN pip install --no-cache -r requirements.txt albumentations wandb gsutil notebook Pillow>=9.1.0 \ + 'opencv-python<4.6.0.66' \ + --extra-index-url https://download.pytorch.org/whl/cu113 + +# Create working directory +RUN mkdir -p /usr/src/app +WORKDIR /usr/src/app + +# Copy contents +COPY . /usr/src/app +RUN git clone https://github.com/ultralytics/yolov5 /usr/src/yolov5 + +# Set environment variables +ENV OMP_NUM_THREADS=8 + + +# Usage Examples ------------------------------------------------------------------------------------------------------- + +# Build and Push +# t=ultralytics/yolov5:latest && sudo docker build -f utils/docker/Dockerfile -t $t . && sudo docker push $t + +# Pull and Run +# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t + +# Pull and Run with local directory access +# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/datasets:/usr/src/datasets $t + +# Kill all +# sudo docker kill $(sudo docker ps -q) + +# Kill all image-based +# sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest) + +# Bash into running container +# sudo docker exec -it 5a9b5863d93d bash + +# Bash into stopped container +# id=$(sudo docker ps -qa) && sudo docker start $id && sudo docker exec -it $id bash + +# Clean up +# docker system prune -a --volumes + +# Update Ubuntu drivers +# https://www.maketecheasier.com/install-nvidia-drivers-ubuntu/ + +# DDP test +# python -m torch.distributed.run --nproc_per_node 2 --master_port 1 train.py --epochs 3 + +# GCP VM from Image +# docker.io/ultralytics/yolov5:latest diff --git a/Y5_20221014/utils/docker/Dockerfile-arm64 b/Y5_20221014/utils/docker/Dockerfile-arm64 new file mode 100755 index 0000000..2e26105 --- /dev/null +++ b/Y5_20221014/utils/docker/Dockerfile-arm64 @@ -0,0 +1,42 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Builds ultralytics/yolov5:latest-arm64 image on DockerHub https://hub.docker.com/r/ultralytics/yolov5 +# Image is aarch64-compatible for Apple M1 and other ARM architectures i.e. Jetson Nano and Raspberry Pi + +# Start FROM Ubuntu image https://hub.docker.com/_/ubuntu +FROM arm64v8/ubuntu:20.04 + +# Downloads to user config dir +ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/ + +# Install linux packages +RUN apt update +RUN DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt install -y tzdata +RUN apt install --no-install-recommends -y python3-pip git zip curl htop gcc \ + libgl1-mesa-glx libglib2.0-0 libpython3.8-dev +# RUN alias python=python3 + +# Install pip packages +COPY requirements.txt . +RUN python3 -m pip install --upgrade pip +RUN pip install --no-cache -r requirements.txt gsutil notebook \ + tensorflow-aarch64 + # tensorflowjs \ + # onnx onnx-simplifier onnxruntime \ + # coremltools openvino-dev \ + +# Create working directory +RUN mkdir -p /usr/src/app +WORKDIR /usr/src/app + +# Copy contents +COPY . /usr/src/app +RUN git clone https://github.com/ultralytics/yolov5 /usr/src/yolov5 + + +# Usage Examples ------------------------------------------------------------------------------------------------------- + +# Build and Push +# t=ultralytics/yolov5:latest-M1 && sudo docker build --platform linux/arm64 -f utils/docker/Dockerfile-arm64 -t $t . && sudo docker push $t + +# Pull and Run +# t=ultralytics/yolov5:latest-M1 && sudo docker pull $t && sudo docker run -it --ipc=host -v "$(pwd)"/datasets:/usr/src/datasets $t diff --git a/Y5_20221014/utils/docker/Dockerfile-cpu b/Y5_20221014/utils/docker/Dockerfile-cpu new file mode 100755 index 0000000..c8aa8c6 --- /dev/null +++ b/Y5_20221014/utils/docker/Dockerfile-cpu @@ -0,0 +1,39 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +# Builds ultralytics/yolov5:latest-cpu image on DockerHub https://hub.docker.com/r/ultralytics/yolov5 +# Image is CPU-optimized for ONNX, OpenVINO and PyTorch YOLOv5 deployments + +# Start FROM Ubuntu image https://hub.docker.com/_/ubuntu +FROM ubuntu:20.04 + +# Downloads to user config dir +ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/ + +# Install linux packages +RUN apt update +RUN DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt install -y tzdata +RUN apt install --no-install-recommends -y python3-pip git zip curl htop libgl1-mesa-glx libglib2.0-0 libpython3.8-dev +# RUN alias python=python3 + +# Install pip packages +COPY requirements.txt . +RUN python3 -m pip install --upgrade pip +RUN pip install --no-cache -r requirements.txt albumentations gsutil notebook \ + coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu tensorflowjs \ + --extra-index-url https://download.pytorch.org/whl/cpu + +# Create working directory +RUN mkdir -p /usr/src/app +WORKDIR /usr/src/app + +# Copy contents +COPY . /usr/src/app +RUN git clone https://github.com/ultralytics/yolov5 /usr/src/yolov5 + + +# Usage Examples ------------------------------------------------------------------------------------------------------- + +# Build and Push +# t=ultralytics/yolov5:latest-cpu && sudo docker build -f utils/docker/Dockerfile-cpu -t $t . && sudo docker push $t + +# Pull and Run +# t=ultralytics/yolov5:latest-cpu && sudo docker pull $t && sudo docker run -it --ipc=host -v "$(pwd)"/datasets:/usr/src/datasets $t diff --git a/Y5_20221014/utils/downloads.py b/Y5_20221014/utils/downloads.py new file mode 100755 index 0000000..ebe5bd3 --- /dev/null +++ b/Y5_20221014/utils/downloads.py @@ -0,0 +1,178 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Download utils +""" + +import logging +import os +import platform +import subprocess +import time +import urllib +from pathlib import Path +from zipfile import ZipFile + +import requests +import torch + + +def is_url(url): + # Check if online file exists + try: + r = urllib.request.urlopen(url) # response + return r.getcode() == 200 + except urllib.request.HTTPError: + return False + + +def gsutil_getsize(url=''): + # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du + s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8') + return eval(s.split(' ')[0]) if len(s) else 0 # bytes + + +def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''): + # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes + from utils.general import LOGGER + + file = Path(file) + assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}" + try: # url1 + LOGGER.info(f'Downloading {url} to {file}...') + torch.hub.download_url_to_file(url, str(file), progress=LOGGER.level <= logging.INFO) + assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check + except Exception as e: # url2 + file.unlink(missing_ok=True) # remove partial downloads + LOGGER.info(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...') + os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail + finally: + if not file.exists() or file.stat().st_size < min_bytes: # check + file.unlink(missing_ok=True) # remove partial downloads + LOGGER.info(f"ERROR: {assert_msg}\n{error_msg}") + LOGGER.info('') + + +def attempt_download(file, repo='ultralytics/yolov5', release='v6.1'): + # Attempt file download from GitHub release assets if not found locally. release = 'latest', 'v6.1', etc. + from utils.general import LOGGER + + def github_assets(repository, version='latest'): + # Return GitHub repo tag (i.e. 'v6.1') and assets (i.e. ['yolov5s.pt', 'yolov5m.pt', ...]) + if version != 'latest': + version = f'tags/{version}' # i.e. tags/v6.1 + response = requests.get(f'https://api.github.com/repos/{repository}/releases/{version}').json() # github api + return response['tag_name'], [x['name'] for x in response['assets']] # tag, assets + + file = Path(str(file).strip().replace("'", '')) + if not file.exists(): + # URL specified + name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc. + if str(file).startswith(('http:/', 'https:/')): # download + url = str(file).replace(':/', '://') # Pathlib turns :// -> :/ + file = name.split('?')[0] # parse authentication https://url.com/file.txt?auth... + if Path(file).is_file(): + LOGGER.info(f'Found {url} locally at {file}') # file already exists + else: + safe_download(file=file, url=url, min_bytes=1E5) + return file + + # GitHub assets + assets = [ + 'yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov5n6.pt', 'yolov5s6.pt', + 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] + try: + tag, assets = github_assets(repo, release) + except Exception: + try: + tag, assets = github_assets(repo) # latest release + except Exception: + try: + tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] + except Exception: + tag = release + + file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required) + if name in assets: + url3 = 'https://drive.google.com/drive/folders/1EFQTEUeXWSFww0luse2jB9M1QNZQGwNl' # backup gdrive mirror + safe_download( + file, + url=f'https://github.com/{repo}/releases/download/{tag}/{name}', + url2=f'https://storage.googleapis.com/{repo}/{tag}/{name}', # backup url (optional) + min_bytes=1E5, + error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/{tag} or {url3}') + + return str(file) + + +def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'): + # Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download() + t = time.time() + file = Path(file) + cookie = Path('cookie') # gdrive cookie + print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='') + file.unlink(missing_ok=True) # remove existing file + cookie.unlink(missing_ok=True) # remove existing cookie + + # Attempt file download + out = "NUL" if platform.system() == "Windows" else "/dev/null" + os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}') + if os.path.exists('cookie'): # large file + s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}' + else: # small file + s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"' + r = os.system(s) # execute, capture return + cookie.unlink(missing_ok=True) # remove existing cookie + + # Error check + if r != 0: + file.unlink(missing_ok=True) # remove partial + print('Download error ') # raise Exception('Download error') + return r + + # Unzip if archive + if file.suffix == '.zip': + print('unzipping... ', end='') + ZipFile(file).extractall(path=file.parent) # unzip + file.unlink() # remove zip + + print(f'Done ({time.time() - t:.1f}s)') + return r + + +def get_token(cookie="./cookie"): + with open(cookie) as f: + for line in f: + if "download" in line: + return line.split()[-1] + return "" + + +# Google utils: https://cloud.google.com/storage/docs/reference/libraries ---------------------------------------------- +# +# +# def upload_blob(bucket_name, source_file_name, destination_blob_name): +# # Uploads a file to a bucket +# # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python +# +# storage_client = storage.Client() +# bucket = storage_client.get_bucket(bucket_name) +# blob = bucket.blob(destination_blob_name) +# +# blob.upload_from_filename(source_file_name) +# +# print('File {} uploaded to {}.'.format( +# source_file_name, +# destination_blob_name)) +# +# +# def download_blob(bucket_name, source_blob_name, destination_file_name): +# # Uploads a blob from a bucket +# storage_client = storage.Client() +# bucket = storage_client.get_bucket(bucket_name) +# blob = bucket.blob(source_blob_name) +# +# blob.download_to_filename(destination_file_name) +# +# print('Blob {} downloaded to {}.'.format( +# source_blob_name, +# destination_file_name)) diff --git a/Y5_20221014/utils/flask_rest_api/README.md b/Y5_20221014/utils/flask_rest_api/README.md new file mode 100755 index 0000000..a726acb --- /dev/null +++ b/Y5_20221014/utils/flask_rest_api/README.md @@ -0,0 +1,73 @@ +# Flask REST API + +[REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are +commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API +created using Flask to expose the YOLOv5s model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/). + +## Requirements + +[Flask](https://palletsprojects.com/p/flask/) is required. Install with: + +```shell +$ pip install Flask +``` + +## Run + +After Flask installation run: + +```shell +$ python3 restapi.py --port 5000 +``` + +Then use [curl](https://curl.se/) to perform a request: + +```shell +$ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s' +``` + +The model inference results are returned as a JSON response: + +```json +[ + { + "class": 0, + "confidence": 0.8900438547, + "height": 0.9318675399, + "name": "person", + "width": 0.3264600933, + "xcenter": 0.7438579798, + "ycenter": 0.5207948685 + }, + { + "class": 0, + "confidence": 0.8440024257, + "height": 0.7155083418, + "name": "person", + "width": 0.6546785235, + "xcenter": 0.427829951, + "ycenter": 0.6334488392 + }, + { + "class": 27, + "confidence": 0.3771208823, + "height": 0.3902671337, + "name": "tie", + "width": 0.0696444362, + "xcenter": 0.3675483763, + "ycenter": 0.7991207838 + }, + { + "class": 27, + "confidence": 0.3527112305, + "height": 0.1540903747, + "name": "tie", + "width": 0.0336618312, + "xcenter": 0.7814827561, + "ycenter": 0.5065554976 + } +] +``` + +An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given +in `example_request.py` diff --git a/Y5_20221014/utils/flask_rest_api/example_request.py b/Y5_20221014/utils/flask_rest_api/example_request.py new file mode 100755 index 0000000..773ad89 --- /dev/null +++ b/Y5_20221014/utils/flask_rest_api/example_request.py @@ -0,0 +1,19 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Perform test request +""" + +import pprint + +import requests + +DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s" +IMAGE = "zidane.jpg" + +# Read image +with open(IMAGE, "rb") as f: + image_data = f.read() + +response = requests.post(DETECTION_URL, files={"image": image_data}).json() + +pprint.pprint(response) diff --git a/Y5_20221014/utils/flask_rest_api/restapi.py b/Y5_20221014/utils/flask_rest_api/restapi.py new file mode 100755 index 0000000..08036dd --- /dev/null +++ b/Y5_20221014/utils/flask_rest_api/restapi.py @@ -0,0 +1,46 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Run a Flask REST API exposing a YOLOv5s model +""" + +import argparse +import io + +import torch +from flask import Flask, request +from PIL import Image + +app = Flask(__name__) + +DETECTION_URL = "/v1/object-detection/yolov5s" + + +@app.route(DETECTION_URL, methods=["POST"]) +def predict(): + if request.method != "POST": + return + + if request.files.get("image"): + # Method 1 + # with request.files["image"] as f: + # im = Image.open(io.BytesIO(f.read())) + + # Method 2 + im_file = request.files["image"] + im_bytes = im_file.read() + im = Image.open(io.BytesIO(im_bytes)) + + results = model(im, size=640) # reduce size=320 for faster inference + return results.pandas().xyxy[0].to_json(orient="records") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model") + parser.add_argument("--port", default=5000, type=int, help="port number") + opt = parser.parse_args() + + # Fix known issue urllib.error.HTTPError 403: rate limit exceeded https://github.com/ultralytics/yolov5/pull/7210 + torch.hub._validate_not_a_forked_repo = lambda a, b, c: True + + model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache + app.run(host="0.0.0.0", port=opt.port) # debug=True causes Restarting with stat diff --git a/Y5_20221014/utils/general.py b/Y5_20221014/utils/general.py new file mode 100755 index 0000000..9fc7349 --- /dev/null +++ b/Y5_20221014/utils/general.py @@ -0,0 +1,1018 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +General utils +""" + +import contextlib +import glob +import inspect +import logging +import math +import os +import platform +import random +import re +import shutil +import signal +import threading +import time +import urllib +from datetime import datetime +from itertools import repeat +from multiprocessing.pool import ThreadPool +from pathlib import Path +from subprocess import check_output +from typing import Optional +from zipfile import ZipFile + +import cv2 +import numpy as np +import pandas as pd +import pkg_resources as pkg +import torch +import torchvision +import yaml + +from utils.downloads import gsutil_getsize +from utils.metrics import box_iou, fitness + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[1] # YOLOv5 root directory +RANK = int(os.getenv('RANK', -1)) + +# Settings +DATASETS_DIR = ROOT.parent / 'datasets' # YOLOv5 datasets directory +NUM_THREADS = min(8, max(1, os.cpu_count() - 1)) # number of YOLOv5 multiprocessing threads +AUTOINSTALL = str(os.getenv('YOLOv5_AUTOINSTALL', True)).lower() == 'true' # global auto-install mode +VERBOSE = str(os.getenv('YOLOv5_VERBOSE', True)).lower() == 'true' # global verbose mode +FONT = 'Arial.ttf' # https://ultralytics.com/assets/Arial.ttf + +torch.set_printoptions(linewidth=320, precision=5, profile='long') +np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5 +pd.options.display.max_columns = 10 +cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader) +os.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS) # NumExpr max threads +os.environ['OMP_NUM_THREADS'] = str(NUM_THREADS) # OpenMP max threads (PyTorch and SciPy) + + +def is_kaggle(): + # Is environment a Kaggle Notebook? + try: + assert os.environ.get('PWD') == '/kaggle/working' + assert os.environ.get('KAGGLE_URL_BASE') == 'https://www.kaggle.com' + return True + except AssertionError: + return False + + +def is_writeable(dir, test=False): + # Return True if directory has write permissions, test opening a file with write permissions if test=True + if not test: + return os.access(dir, os.R_OK) # possible issues on Windows + file = Path(dir) / 'tmp.txt' + try: + with open(file, 'w'): # open file with write permissions + pass + file.unlink() # remove file + return True + except OSError: + return False + + +def set_logging(name=None, verbose=VERBOSE): + # Sets level and returns logger + if is_kaggle(): + for h in logging.root.handlers: + logging.root.removeHandler(h) # remove all handlers associated with the root logger object + rank = int(os.getenv('RANK', -1)) # rank in world for Multi-GPU trainings + level = logging.INFO if verbose and rank in {-1, 0} else logging.WARNING + log = logging.getLogger(name) + log.setLevel(level) + handler = logging.StreamHandler() + handler.setFormatter(logging.Formatter("%(message)s")) + handler.setLevel(level) + log.addHandler(handler) + + +set_logging() # run before defining LOGGER +LOGGER = logging.getLogger("yolov5") # define globally (used in train.py, val.py, detect.py, etc.) + + +def user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'): + # Return path of user configuration directory. Prefer environment variable if exists. Make dir if required. + env = os.getenv(env_var) + if env: + path = Path(env) # use environment variable + else: + cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'} # 3 OS dirs + path = Path.home() / cfg.get(platform.system(), '') # OS-specific config dir + path = (path if is_writeable(path) else Path('/tmp')) / dir # GCP and AWS lambda fix, only /tmp is writeable + path.mkdir(exist_ok=True) # make if required + return path + + +CONFIG_DIR = user_config_dir() # Ultralytics settings dir + + +class Profile(contextlib.ContextDecorator): + # Usage: @Profile() decorator or 'with Profile():' context manager + def __enter__(self): + self.start = time.time() + + def __exit__(self, type, value, traceback): + print(f'Profile results: {time.time() - self.start:.5f}s') + + +class Timeout(contextlib.ContextDecorator): + # Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager + def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True): + self.seconds = int(seconds) + self.timeout_message = timeout_msg + self.suppress = bool(suppress_timeout_errors) + + def _timeout_handler(self, signum, frame): + raise TimeoutError(self.timeout_message) + + def __enter__(self): + if platform.system() != 'Windows': # not supported on Windows + signal.signal(signal.SIGALRM, self._timeout_handler) # Set handler for SIGALRM + signal.alarm(self.seconds) # start countdown for SIGALRM to be raised + + def __exit__(self, exc_type, exc_val, exc_tb): + if platform.system() != 'Windows': + signal.alarm(0) # Cancel SIGALRM if it's scheduled + if self.suppress and exc_type is TimeoutError: # Suppress TimeoutError + return True + + +class WorkingDirectory(contextlib.ContextDecorator): + # Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager + def __init__(self, new_dir): + self.dir = new_dir # new dir + self.cwd = Path.cwd().resolve() # current dir + + def __enter__(self): + os.chdir(self.dir) + + def __exit__(self, exc_type, exc_val, exc_tb): + os.chdir(self.cwd) + + +def try_except(func): + # try-except function. Usage: @try_except decorator + def handler(*args, **kwargs): + try: + func(*args, **kwargs) + except Exception as e: + print(e) + + return handler + + +def threaded(func): + # Multi-threads a target function and returns thread. Usage: @threaded decorator + def wrapper(*args, **kwargs): + thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True) + thread.start() + return thread + + return wrapper + + +def methods(instance): + # Get class/instance methods + return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")] + + +def print_args(args: Optional[dict] = None, show_file=True, show_fcn=False): + # Print function arguments (optional args dict) + x = inspect.currentframe().f_back # previous frame + file, _, fcn, _, _ = inspect.getframeinfo(x) + if args is None: # get args automatically + args, _, _, frm = inspect.getargvalues(x) + args = {k: v for k, v in frm.items() if k in args} + s = (f'{Path(file).stem}: ' if show_file else '') + (f'{fcn}: ' if show_fcn else '') + LOGGER.info(colorstr(s) + ', '.join(f'{k}={v}' for k, v in args.items())) + + +def init_seeds(seed=0): + # Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html + # cudnn seed 0 settings are slower and more reproducible, else faster and less reproducible + import torch.backends.cudnn as cudnn + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + cudnn.benchmark, cudnn.deterministic = (False, True) if seed == 0 else (True, False) + + +def intersect_dicts(da, db, exclude=()): + # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values + return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape} + + +def get_latest_run(search_dir='.'): + # Return path to most recent 'last.pt' in /runs (i.e. to --resume from) + last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True) + return max(last_list, key=os.path.getctime) if last_list else '' + + +def is_docker(): + # Is environment a Docker container? + return Path('/workspace').exists() # or Path('/.dockerenv').exists() + + +def is_colab(): + # Is environment a Google Colab instance? + try: + import google.colab + return True + except ImportError: + return False + + +def is_pip(): + # Is file in a pip package? + return 'site-packages' in Path(__file__).resolve().parts + + +def is_ascii(s=''): + # Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7) + s = str(s) # convert list, tuple, None, etc. to str + return len(s.encode().decode('ascii', 'ignore')) == len(s) + + +def is_chinese(s='人工智能'): + # Is string composed of any Chinese characters? + return bool(re.search('[\u4e00-\u9fff]', str(s))) + + +def emojis(str=''): + # Return platform-dependent emoji-safe version of string + return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str + + +def file_age(path=__file__): + # Return days since last file update + dt = (datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime)) # delta + return dt.days # + dt.seconds / 86400 # fractional days + + +def file_date(path=__file__): + # Return human-readable file modification date, i.e. '2021-3-26' + t = datetime.fromtimestamp(Path(path).stat().st_mtime) + return f'{t.year}-{t.month}-{t.day}' + + +def file_size(path): + # Return file/dir size (MB) + mb = 1 << 20 # bytes to MiB (1024 ** 2) + path = Path(path) + if path.is_file(): + return path.stat().st_size / mb + elif path.is_dir(): + return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / mb + else: + return 0.0 + + +def check_online(): + # Check internet connectivity + import socket + try: + socket.create_connection(("1.1.1.1", 443), 5) # check host accessibility + return True + except OSError: + return False + + +def git_describe(path=ROOT): # path must be a directory + # Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe + try: + assert (Path(path) / '.git').is_dir() + return check_output(f'git -C {path} describe --tags --long --always', shell=True).decode()[:-1] + except Exception: + return '' + + +@try_except +@WorkingDirectory(ROOT) +def check_git_status(): + # Recommend 'git pull' if code is out of date + msg = ', for updates see https://github.com/ultralytics/yolov5' + s = colorstr('github: ') # string + assert Path('.git').exists(), s + 'skipping check (not a git repository)' + msg + assert not is_docker(), s + 'skipping check (Docker image)' + msg + assert check_online(), s + 'skipping check (offline)' + msg + + cmd = 'git fetch && git config --get remote.origin.url' + url = check_output(cmd, shell=True, timeout=5).decode().strip().rstrip('.git') # git fetch + branch = check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out + n = int(check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind + if n > 0: + s += f"⚠️ YOLOv5 is out of date by {n} commit{'s' * (n > 1)}. Use `git pull` or `git clone {url}` to update." + else: + s += f'up to date with {url} ✅' + LOGGER.info(emojis(s)) # emoji-safe + + +def check_python(minimum='3.7.0'): + # Check current python version vs. required python version + check_version(platform.python_version(), minimum, name='Python ', hard=True) + + +def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False): + # Check version vs. required version + current, minimum = (pkg.parse_version(x) for x in (current, minimum)) + result = (current == minimum) if pinned else (current >= minimum) # bool + s = f'{name}{minimum} required by YOLOv5, but {name}{current} is currently installed' # string + if hard: + assert result, s # assert min requirements met + if verbose and not result: + LOGGER.warning(s) + return result + + +@try_except +def check_requirements(requirements=ROOT / 'requirements.txt', exclude=(), install=True, cmds=()): + # Check installed dependencies meet requirements (pass *.txt file or list of packages) + prefix = colorstr('red', 'bold', 'requirements:') + check_python() # check python version + if isinstance(requirements, (str, Path)): # requirements.txt file + file = Path(requirements) + assert file.exists(), f"{prefix} {file.resolve()} not found, check failed." + with file.open() as f: + requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(f) if x.name not in exclude] + else: # list or tuple of packages + requirements = [x for x in requirements if x not in exclude] + + n = 0 # number of packages updates + for i, r in enumerate(requirements): + try: + pkg.require(r) + except Exception: # DistributionNotFound or VersionConflict if requirements not met + s = f"{prefix} {r} not found and is required by YOLOv5" + if install and AUTOINSTALL: # check environment variable + LOGGER.info(f"{s}, attempting auto-update...") + try: + assert check_online(), f"'pip install {r}' skipped (offline)" + LOGGER.info(check_output(f'pip install "{r}" {cmds[i] if cmds else ""}', shell=True).decode()) + n += 1 + except Exception as e: + LOGGER.warning(f'{prefix} {e}') + else: + LOGGER.info(f'{s}. Please install and rerun your command.') + + if n: # if packages updated + source = file.resolve() if 'file' in locals() else requirements + s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \ + f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n" + LOGGER.info(emojis(s)) + + +def check_img_size(imgsz, s=32, floor=0): + # Verify image size is a multiple of stride s in each dimension + if isinstance(imgsz, int): # integer i.e. img_size=640 + new_size = max(make_divisible(imgsz, int(s)), floor) + else: # list i.e. img_size=[640, 480] + imgsz = list(imgsz) # convert to list if tuple + new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz] + if new_size != imgsz: + LOGGER.warning(f'WARNING: --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}') + return new_size + + +def check_imshow(): + # Check if environment supports image displays + try: + assert not is_docker(), 'cv2.imshow() is disabled in Docker environments' + assert not is_colab(), 'cv2.imshow() is disabled in Google Colab environments' + cv2.imshow('test', np.zeros((1, 1, 3))) + cv2.waitKey(1) + cv2.destroyAllWindows() + cv2.waitKey(1) + return True + except Exception as e: + LOGGER.warning(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}') + return False + + +def check_suffix(file='yolov5s.pt', suffix=('.pt',), msg=''): + # Check file(s) for acceptable suffix + if file and suffix: + if isinstance(suffix, str): + suffix = [suffix] + for f in file if isinstance(file, (list, tuple)) else [file]: + s = Path(f).suffix.lower() # file suffix + if len(s): + assert s in suffix, f"{msg}{f} acceptable suffix is {suffix}" + + +def check_yaml(file, suffix=('.yaml', '.yml')): + # Search/download YAML file (if necessary) and return path, checking suffix + return check_file(file, suffix) + + +def check_file(file, suffix=''): + # Search/download file (if necessary) and return path + check_suffix(file, suffix) # optional + file = str(file) # convert to str() + if Path(file).is_file() or not file: # exists + return file + elif file.startswith(('http:/', 'https:/')): # download + url = file # warning: Pathlib turns :// -> :/ + file = Path(urllib.parse.unquote(file).split('?')[0]).name # '%2F' to '/', split https://url.com/file.txt?auth + if Path(file).is_file(): + LOGGER.info(f'Found {url} locally at {file}') # file already exists + else: + LOGGER.info(f'Downloading {url} to {file}...') + torch.hub.download_url_to_file(url, file) + assert Path(file).exists() and Path(file).stat().st_size > 0, f'File download failed: {url}' # check + return file + else: # search + files = [] + for d in 'data', 'models', 'utils': # search directories + files.extend(glob.glob(str(ROOT / d / '**' / file), recursive=True)) # find file + assert len(files), f'File not found: {file}' # assert file was found + assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique + return files[0] # return file + + +def check_font(font=FONT, progress=False): + # Download font to CONFIG_DIR if necessary + font = Path(font) + file = CONFIG_DIR / font.name + if not font.exists() and not file.exists(): + url = "https://ultralytics.com/assets/" + font.name + LOGGER.info(f'Downloading {url} to {file}...') + torch.hub.download_url_to_file(url, str(file), progress=progress) + + +def check_dataset(data, autodownload=True): + # Download, check and/or unzip dataset if not found locally + + # Download (optional) + extract_dir = '' + if isinstance(data, (str, Path)) and str(data).endswith('.zip'): # i.e. gs://bucket/dir/coco128.zip + download(data, dir=DATASETS_DIR, unzip=True, delete=False, curl=False, threads=1) + data = next((DATASETS_DIR / Path(data).stem).rglob('*.yaml')) + extract_dir, autodownload = data.parent, False + + # Read yaml (optional) + if isinstance(data, (str, Path)): + with open(data, errors='ignore') as f: + data = yaml.safe_load(f) # dictionary + + # Checks + for k in 'train', 'val', 'nc': + assert k in data, emojis(f"data.yaml '{k}:' field missing ❌") + if 'names' not in data: + LOGGER.warning(emojis("data.yaml 'names:' field missing ⚠, assigning default names 'class0', 'class1', etc.")) + data['names'] = [f'class{i}' for i in range(data['nc'])] # default names + + # Resolve paths + path = Path(extract_dir or data.get('path') or '') # optional 'path' default to '.' + if not path.is_absolute(): + path = (ROOT / path).resolve() + for k in 'train', 'val', 'test': + if data.get(k): # prepend path + data[k] = str(path / data[k]) if isinstance(data[k], str) else [str(path / x) for x in data[k]] + + # Parse yaml + train, val, test, s = (data.get(x) for x in ('train', 'val', 'test', 'download')) + if val: + val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path + if not all(x.exists() for x in val): + LOGGER.info(emojis('\nDataset not found ⚠, missing paths %s' % [str(x) for x in val if not x.exists()])) + if not s or not autodownload: + raise Exception(emojis('Dataset not found ❌')) + t = time.time() + root = path.parent if 'path' in data else '..' # unzip directory i.e. '../' + if s.startswith('http') and s.endswith('.zip'): # URL + f = Path(s).name # filename + LOGGER.info(f'Downloading {s} to {f}...') + torch.hub.download_url_to_file(s, f) + Path(root).mkdir(parents=True, exist_ok=True) # create root + ZipFile(f).extractall(path=root) # unzip + Path(f).unlink() # remove zip + r = None # success + elif s.startswith('bash '): # bash script + LOGGER.info(f'Running {s} ...') + r = os.system(s) + else: # python script + r = exec(s, {'yaml': data}) # return None + dt = f'({round(time.time() - t, 1)}s)' + s = f"success ✅ {dt}, saved to {colorstr('bold', root)}" if r in (0, None) else f"failure {dt} ❌" + LOGGER.info(emojis(f"Dataset download {s}")) + check_font('Arial.ttf' if is_ascii(data['names']) else 'Arial.Unicode.ttf', progress=True) # download fonts + return data # dictionary + + +def check_amp(model): + # Check PyTorch Automatic Mixed Precision (AMP) functionality. Return True on correct operation + from models.common import AutoShape, DetectMultiBackend + + def amp_allclose(model, im): + # All close FP32 vs AMP results + m = AutoShape(model, verbose=False) # model + a = m(im).xywhn[0] # FP32 inference + m.amp = True + b = m(im).xywhn[0] # AMP inference + return a.shape == b.shape and torch.allclose(a, b, atol=0.1) # close to 10% absolute tolerance + + prefix = colorstr('AMP: ') + device = next(model.parameters()).device # get model device + if device.type == 'cpu': + return False # AMP disabled on CPU + f = ROOT / 'data' / 'images' / 'bus.jpg' # image to check + im = f if f.exists() else 'https://ultralytics.com/images/bus.jpg' if check_online() else np.ones((640, 640, 3)) + try: + assert amp_allclose(model, im) or amp_allclose(DetectMultiBackend('yolov5n.pt', device), im) + LOGGER.info(emojis(f'{prefix}checks passed ✅')) + return True + except Exception: + help_url = 'https://github.com/ultralytics/yolov5/issues/7908' + LOGGER.warning(emojis(f'{prefix}checks failed ❌, disabling Automatic Mixed Precision. See {help_url}')) + return False + + +def url2file(url): + # Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt + url = str(Path(url)).replace(':/', '://') # Pathlib turns :// -> :/ + return Path(urllib.parse.unquote(url)).name.split('?')[0] # '%2F' to '/', split https://url.com/file.txt?auth + + +def download(url, dir='.', unzip=True, delete=True, curl=False, threads=1, retry=3): + # Multi-threaded file download and unzip function, used in data.yaml for autodownload + def download_one(url, dir): + # Download 1 file + success = True + f = dir / Path(url).name # filename + if Path(url).is_file(): # exists in current path + Path(url).rename(f) # move to dir + elif not f.exists(): + LOGGER.info(f'Downloading {url} to {f}...') + for i in range(retry + 1): + if curl: + s = 'sS' if threads > 1 else '' # silent + r = os.system(f'curl -{s}L "{url}" -o "{f}" --retry 9 -C -') # curl download with retry, continue + success = r == 0 + else: + torch.hub.download_url_to_file(url, f, progress=threads == 1) # torch download + success = f.is_file() + if success: + break + elif i < retry: + LOGGER.warning(f'Download failure, retrying {i + 1}/{retry} {url}...') + else: + LOGGER.warning(f'Failed to download {url}...') + + if unzip and success and f.suffix in ('.zip', '.gz'): + LOGGER.info(f'Unzipping {f}...') + if f.suffix == '.zip': + ZipFile(f).extractall(path=dir) # unzip + elif f.suffix == '.gz': + os.system(f'tar xfz {f} --directory {f.parent}') # unzip + if delete: + f.unlink() # remove zip + + dir = Path(dir) + dir.mkdir(parents=True, exist_ok=True) # make directory + if threads > 1: + pool = ThreadPool(threads) + pool.imap(lambda x: download_one(*x), zip(url, repeat(dir))) # multi-threaded + pool.close() + pool.join() + else: + for u in [url] if isinstance(url, (str, Path)) else url: + download_one(u, dir) + + +def make_divisible(x, divisor): + # Returns nearest x divisible by divisor + if isinstance(divisor, torch.Tensor): + divisor = int(divisor.max()) # to int + return math.ceil(x / divisor) * divisor + + +def clean_str(s): + # Cleans a string by replacing special characters with underscore _ + return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s) + + +def one_cycle(y1=0.0, y2=1.0, steps=100): + # lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf + return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1 + + +def colorstr(*input): + # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world') + *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string + colors = { + 'black': '\033[30m', # basic colors + 'red': '\033[31m', + 'green': '\033[32m', + 'yellow': '\033[33m', + 'blue': '\033[34m', + 'magenta': '\033[35m', + 'cyan': '\033[36m', + 'white': '\033[37m', + 'bright_black': '\033[90m', # bright colors + 'bright_red': '\033[91m', + 'bright_green': '\033[92m', + 'bright_yellow': '\033[93m', + 'bright_blue': '\033[94m', + 'bright_magenta': '\033[95m', + 'bright_cyan': '\033[96m', + 'bright_white': '\033[97m', + 'end': '\033[0m', # misc + 'bold': '\033[1m', + 'underline': '\033[4m'} + return ''.join(colors[x] for x in args) + f'{string}' + colors['end'] + + +def labels_to_class_weights(labels, nc=80): + # Get class weights (inverse frequency) from training labels + if labels[0] is None: # no labels loaded + return torch.Tensor() + + labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO + classes = labels[:, 0].astype(np.int) # labels = [class xywh] + weights = np.bincount(classes, minlength=nc) # occurrences per class + + # Prepend gridpoint count (for uCE training) + # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image + # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start + + weights[weights == 0] = 1 # replace empty bins with 1 + weights = 1 / weights # number of targets per class + weights /= weights.sum() # normalize + return torch.from_numpy(weights) + + +def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)): + # Produces image weights based on class_weights and image contents + # Usage: index = random.choices(range(n), weights=image_weights, k=1) # weighted image sample + class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels]) + return (class_weights.reshape(1, nc) * class_counts).sum(1) + + +def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper) + # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/ + # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n') + # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n') + # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco + # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet + return [ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, + 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90] + + +def xyxy2xywh(x): + # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center + y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center + y[:, 2] = x[:, 2] - x[:, 0] # width + y[:, 3] = x[:, 3] - x[:, 1] # height + return y + + +def xywh2xyxy(x): + # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x + y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y + y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x + y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y + return y + + +def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0): + # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x + y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y + y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x + y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y + return y + + +def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0): + # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right + if clip: + clip_coords(x, (h - eps, w - eps)) # warning: inplace clip + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = ((x[:, 0] + x[:, 2]) / 2) / w # x center + y[:, 1] = ((x[:, 1] + x[:, 3]) / 2) / h # y center + y[:, 2] = (x[:, 2] - x[:, 0]) / w # width + y[:, 3] = (x[:, 3] - x[:, 1]) / h # height + return y + + +def xyn2xy(x, w=640, h=640, padw=0, padh=0): + # Convert normalized segments into pixel segments, shape (n,2) + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = w * x[:, 0] + padw # top left x + y[:, 1] = h * x[:, 1] + padh # top left y + return y + + +def segment2box(segment, width=640, height=640): + # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy) + x, y = segment.T # segment xy + inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height) + x, y, = x[inside], y[inside] + return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy + + +def segments2boxes(segments): + # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh) + boxes = [] + for s in segments: + x, y = s.T # segment xy + boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy + return xyxy2xywh(np.array(boxes)) # cls, xywh + + +def resample_segments(segments, n=1000): + # Up-sample an (n,2) segment + for i, s in enumerate(segments): + s = np.concatenate((s, s[0:1, :]), axis=0) + x = np.linspace(0, len(s) - 1, n) + xp = np.arange(len(s)) + segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy + return segments + + +def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None): + # Rescale coords (xyxy) from img1_shape to img0_shape + if ratio_pad is None: # calculate from img0_shape + gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new + pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding + else: + gain = ratio_pad[0][0] + pad = ratio_pad[1] + + coords[:, [0, 2]] -= pad[0] # x padding + coords[:, [1, 3]] -= pad[1] # y padding + coords[:, :4] /= gain + clip_coords(coords, img0_shape) + return coords + + +def clip_coords(boxes, shape): + # Clip bounding xyxy bounding boxes to image shape (height, width) + if isinstance(boxes, torch.Tensor): # faster individually + boxes[:, 0].clamp_(0, shape[1]) # x1 + boxes[:, 1].clamp_(0, shape[0]) # y1 + boxes[:, 2].clamp_(0, shape[1]) # x2 + boxes[:, 3].clamp_(0, shape[0]) # y2 + else: # np.array (faster grouped) + boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2 + boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2 + + +def non_max_suppression(prediction, + conf_thres=0.25, + iou_thres=0.45, + classes=None, + agnostic=False, + multi_label=False, + labels=(), + max_det=300): + """Non-Maximum Suppression (NMS) on inference results to reject overlapping bounding boxes + + Returns: + list of detections, on (n,6) tensor per image [xyxy, conf, cls] + """ + + bs = prediction.shape[0] # batch size + nc = prediction.shape[2] - 5 # number of classes + xc = prediction[..., 4] > conf_thres # candidates + + # Checks + assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0' + assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0' + + # Settings + # min_wh = 2 # (pixels) minimum box width and height + max_wh = 7680 # (pixels) maximum box width and height + max_nms = 30000 # maximum number of boxes into torchvision.ops.nms() + time_limit = 0.3 + 0.03 * bs # seconds to quit after + redundant = True # require redundant detections + multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img) + merge = False # use merge-NMS + + t = time.time() + output = [torch.zeros((0, 6), device=prediction.device)] * bs + for xi, x in enumerate(prediction): # image index, image inference + # Apply constraints + # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height + x = x[xc[xi]] # confidence + + # Cat apriori labels if autolabelling + if labels and len(labels[xi]): + lb = labels[xi] + v = torch.zeros((len(lb), nc + 5), device=x.device) + v[:, :4] = lb[:, 1:5] # box + v[:, 4] = 1.0 # conf + v[range(len(lb)), lb[:, 0].long() + 5] = 1.0 # cls + x = torch.cat((x, v), 0) + + # If none remain process next image + if not x.shape[0]: + continue + + # Compute conf + x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf + + # Box (center x, center y, width, height) to (x1, y1, x2, y2) + box = xywh2xyxy(x[:, :4]) + + # Detections matrix nx6 (xyxy, conf, cls) + if multi_label: + i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T + x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1) + else: # best class only + conf, j = x[:, 5:].max(1, keepdim=True) + x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres] + + # Filter by class + if classes is not None: + x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] + + # Apply finite constraint + # if not torch.isfinite(x).all(): + # x = x[torch.isfinite(x).all(1)] + + # Check shape + n = x.shape[0] # number of boxes + if not n: # no boxes + continue + elif n > max_nms: # excess boxes + x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence + + # Batched NMS + c = x[:, 5:6] * (0 if agnostic else max_wh) # classes + boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores + i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS + if i.shape[0] > max_det: # limit detections + i = i[:max_det] + if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean) + # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4) + iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix + weights = iou * scores[None] # box weights + x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes + if redundant: + i = i[iou.sum(1) > 1] # require redundancy + + output[xi] = x[i] + if (time.time() - t) > time_limit: + LOGGER.warning(f'WARNING: NMS time limit {time_limit:.3f}s exceeded') + break # time limit exceeded + + return output + + +def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer() + # Strip optimizer from 'f' to finalize training, optionally save as 's' + x = torch.load(f, map_location=torch.device('cpu')) + if x.get('ema'): + x['model'] = x['ema'] # replace model with ema + for k in 'optimizer', 'best_fitness', 'wandb_id', 'ema', 'updates': # keys + x[k] = None + x['epoch'] = -1 + x['model'].half() # to FP16 + for p in x['model'].parameters(): + p.requires_grad = False + torch.save(x, s or f) + mb = os.path.getsize(s or f) / 1E6 # filesize + LOGGER.info(f"Optimizer stripped from {f},{f' saved as {s},' if s else ''} {mb:.1f}MB") + + +def print_mutation(results, hyp, save_dir, bucket, prefix=colorstr('evolve: ')): + evolve_csv = save_dir / 'evolve.csv' + evolve_yaml = save_dir / 'hyp_evolve.yaml' + keys = ('metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', 'val/box_loss', + 'val/obj_loss', 'val/cls_loss') + tuple(hyp.keys()) # [results + hyps] + keys = tuple(x.strip() for x in keys) + vals = results + tuple(hyp.values()) + n = len(keys) + + # Download (optional) + if bucket: + url = f'gs://{bucket}/evolve.csv' + if gsutil_getsize(url) > (evolve_csv.stat().st_size if evolve_csv.exists() else 0): + os.system(f'gsutil cp {url} {save_dir}') # download evolve.csv if larger than local + + # Log to evolve.csv + s = '' if evolve_csv.exists() else (('%20s,' * n % keys).rstrip(',') + '\n') # add header + with open(evolve_csv, 'a') as f: + f.write(s + ('%20.5g,' * n % vals).rstrip(',') + '\n') + + # Save yaml + with open(evolve_yaml, 'w') as f: + data = pd.read_csv(evolve_csv) + data = data.rename(columns=lambda x: x.strip()) # strip keys + i = np.argmax(fitness(data.values[:, :4])) # + generations = len(data) + f.write('# YOLOv5 Hyperparameter Evolution Results\n' + f'# Best generation: {i}\n' + + f'# Last generation: {generations - 1}\n' + '# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) + + '\n' + '# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n') + yaml.safe_dump(data.loc[i][7:].to_dict(), f, sort_keys=False) + + # Print to screen + LOGGER.info(prefix + f'{generations} generations finished, current result:\n' + prefix + + ', '.join(f'{x.strip():>20s}' for x in keys) + '\n' + prefix + ', '.join(f'{x:20.5g}' + for x in vals) + '\n\n') + + if bucket: + os.system(f'gsutil cp {evolve_csv} {evolve_yaml} gs://{bucket}') # upload + + +def apply_classifier(x, model, img, im0): + # Apply a second stage classifier to YOLO outputs + # Example model = torchvision.models.__dict__['efficientnet_b0'](pretrained=True).to(device).eval() + im0 = [im0] if isinstance(im0, np.ndarray) else im0 + for i, d in enumerate(x): # per image + if d is not None and len(d): + d = d.clone() + + # Reshape and pad cutouts + b = xyxy2xywh(d[:, :4]) # boxes + b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square + b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad + d[:, :4] = xywh2xyxy(b).long() + + # Rescale boxes from img_size to im0 size + scale_coords(img.shape[2:], d[:, :4], im0[i].shape) + + # Classes + pred_cls1 = d[:, 5].long() + ims = [] + for a in d: + cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])] + im = cv2.resize(cutout, (224, 224)) # BGR + + im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 + im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32 + im /= 255 # 0 - 255 to 0.0 - 1.0 + ims.append(im) + + pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction + x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections + + return x + + +def increment_path(path, exist_ok=False, sep='', mkdir=False): + # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc. + path = Path(path) # os-agnostic + if path.exists() and not exist_ok: + path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '') + + # Method 1 + for n in range(2, 9999): + p = f'{path}{sep}{n}{suffix}' # increment path + if not os.path.exists(p): # + break + path = Path(p) + + # Method 2 (deprecated) + # dirs = glob.glob(f"{path}{sep}*") # similar paths + # matches = [re.search(rf"{path.stem}{sep}(\d+)", d) for d in dirs] + # i = [int(m.groups()[0]) for m in matches if m] # indices + # n = max(i) + 1 if i else 2 # increment number + # path = Path(f"{path}{sep}{n}{suffix}") # increment path + + if mkdir: + path.mkdir(parents=True, exist_ok=True) # make directory + + return path + + +# OpenCV Chinese-friendly functions ------------------------------------------------------------------------------------ +imshow_ = cv2.imshow # copy to avoid recursion errors + + +def imread(path, flags=cv2.IMREAD_COLOR): + return cv2.imdecode(np.fromfile(path, np.uint8), flags) + + +def imwrite(path, im): + try: + cv2.imencode(Path(path).suffix, im)[1].tofile(path) + return True + except Exception: + return False + + +def imshow(path, im): + imshow_(path.encode('unicode_escape').decode(), im) + + +cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow # redefine + +# Variables ------------------------------------------------------------------------------------------------------------ +NCOLS = 0 if is_docker() else shutil.get_terminal_size().columns # terminal window size for tqdm diff --git a/Y5_20221014/utils/google_app_engine/Dockerfile b/Y5_20221014/utils/google_app_engine/Dockerfile new file mode 100755 index 0000000..0155618 --- /dev/null +++ b/Y5_20221014/utils/google_app_engine/Dockerfile @@ -0,0 +1,25 @@ +FROM gcr.io/google-appengine/python + +# Create a virtualenv for dependencies. This isolates these packages from +# system-level packages. +# Use -p python3 or -p python3.7 to select python version. Default is version 2. +RUN virtualenv /env -p python3 + +# Setting these environment variables are the same as running +# source /env/bin/activate. +ENV VIRTUAL_ENV /env +ENV PATH /env/bin:$PATH + +RUN apt-get update && apt-get install -y python-opencv + +# Copy the application's requirements.txt and run pip to install all +# dependencies into the virtualenv. +ADD requirements.txt /app/requirements.txt +RUN pip install -r /app/requirements.txt + +# Add the application source code. +ADD . /app + +# Run a WSGI server to serve the application. gunicorn must be declared as +# a dependency in requirements.txt. +CMD gunicorn -b :$PORT main:app diff --git a/Y5_20221014/utils/google_app_engine/additional_requirements.txt b/Y5_20221014/utils/google_app_engine/additional_requirements.txt new file mode 100755 index 0000000..42d7ffc --- /dev/null +++ b/Y5_20221014/utils/google_app_engine/additional_requirements.txt @@ -0,0 +1,4 @@ +# add these requirements in your app on top of the existing ones +pip==21.1 +Flask==1.0.2 +gunicorn==19.9.0 diff --git a/Y5_20221014/utils/google_app_engine/app.yaml b/Y5_20221014/utils/google_app_engine/app.yaml new file mode 100755 index 0000000..5056b7c --- /dev/null +++ b/Y5_20221014/utils/google_app_engine/app.yaml @@ -0,0 +1,14 @@ +runtime: custom +env: flex + +service: yolov5app + +liveness_check: + initial_delay_sec: 600 + +manual_scaling: + instances: 1 +resources: + cpu: 1 + memory_gb: 4 + disk_size_gb: 20 diff --git a/Y5_20221014/utils/loggers/__init__.py b/Y5_20221014/utils/loggers/__init__.py new file mode 100755 index 0000000..42b696b --- /dev/null +++ b/Y5_20221014/utils/loggers/__init__.py @@ -0,0 +1,187 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Logging utils +""" + +import os +import warnings + +import pkg_resources as pkg +import torch +from torch.utils.tensorboard import SummaryWriter + +from utils.general import colorstr, cv2, emojis +from utils.loggers.wandb.wandb_utils import WandbLogger +from utils.plots import plot_images, plot_results +from utils.torch_utils import de_parallel + +LOGGERS = ('csv', 'tb', 'wandb') # text-file, TensorBoard, Weights & Biases +RANK = int(os.getenv('RANK', -1)) + +try: + import wandb + + assert hasattr(wandb, '__version__') # verify package import not local dir + if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.2') and RANK in {0, -1}: + try: + wandb_login_success = wandb.login(timeout=30) + except wandb.errors.UsageError: # known non-TTY terminal issue + wandb_login_success = False + if not wandb_login_success: + wandb = None +except (ImportError, AssertionError): + wandb = None + + +class Loggers(): + # YOLOv5 Loggers class + def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS): + self.save_dir = save_dir + self.weights = weights + self.opt = opt + self.hyp = hyp + self.logger = logger # for printing results to console + self.include = include + self.keys = [ + 'train/box_loss', + 'train/obj_loss', + 'train/cls_loss', # train loss + 'metrics/precision', + 'metrics/recall', + 'metrics/mAP_0.5', + 'metrics/mAP_0.5:0.95', # metrics + 'val/box_loss', + 'val/obj_loss', + 'val/cls_loss', # val loss + 'x/lr0', + 'x/lr1', + 'x/lr2'] # params + self.best_keys = ['best/epoch', 'best/precision', 'best/recall', 'best/mAP_0.5', 'best/mAP_0.5:0.95'] + for k in LOGGERS: + setattr(self, k, None) # init empty logger dictionary + self.csv = True # always log to csv + + # Message + if not wandb: + prefix = colorstr('Weights & Biases: ') + s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)" + self.logger.info(emojis(s)) + + # TensorBoard + s = self.save_dir + if 'tb' in self.include and not self.opt.evolve: + prefix = colorstr('TensorBoard: ') + self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/") + self.tb = SummaryWriter(str(s)) + + # W&B + if wandb and 'wandb' in self.include: + wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://') + run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None + self.opt.hyp = self.hyp # add hyperparameters + self.wandb = WandbLogger(self.opt, run_id) + # temp warn. because nested artifacts not supported after 0.12.10 + if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.11'): + self.logger.warning( + "YOLOv5 temporarily requires wandb version 0.12.10 or below. Some features may not work as expected." + ) + else: + self.wandb = None + + def on_train_start(self): + # Callback runs on train start + pass + + def on_pretrain_routine_end(self): + # Callback runs on pre-train routine end + paths = self.save_dir.glob('*labels*.jpg') # training labels + if self.wandb: + self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]}) + + def on_train_batch_end(self, ni, model, imgs, targets, paths, plots): + # Callback runs on train batch end + if plots: + if ni == 0: + if not self.opt.sync_bn: # --sync known issue https://github.com/ultralytics/yolov5/issues/3754 + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress jit trace warning + self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), []) + if ni < 3: + f = self.save_dir / f'train_batch{ni}.jpg' # filename + plot_images(imgs, targets, paths, f) + if self.wandb and ni == 10: + files = sorted(self.save_dir.glob('train*.jpg')) + self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]}) + + def on_train_epoch_end(self, epoch): + # Callback runs on train epoch end + if self.wandb: + self.wandb.current_epoch = epoch + 1 + + def on_val_image_end(self, pred, predn, path, names, im): + # Callback runs on val image end + if self.wandb: + self.wandb.val_one_image(pred, predn, path, names, im) + + def on_val_end(self): + # Callback runs on val end + if self.wandb: + files = sorted(self.save_dir.glob('val*.jpg')) + self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]}) + + def on_fit_epoch_end(self, vals, epoch, best_fitness, fi): + # Callback runs at the end of each fit (train+val) epoch + x = dict(zip(self.keys, vals)) + if self.csv: + file = self.save_dir / 'results.csv' + n = len(x) + 1 # number of cols + s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n') # add header + with open(file, 'a') as f: + f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n') + + if self.tb: + for k, v in x.items(): + self.tb.add_scalar(k, v, epoch) + + if self.wandb: + if best_fitness == fi: + best_results = [epoch] + vals[3:7] + for i, name in enumerate(self.best_keys): + self.wandb.wandb_run.summary[name] = best_results[i] # log best results in the summary + self.wandb.log(x) + self.wandb.end_epoch(best_result=best_fitness == fi) + + def on_model_save(self, last, epoch, final_epoch, best_fitness, fi): + # Callback runs on model save event + if self.wandb: + if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1: + self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi) + + def on_train_end(self, last, best, plots, epoch, results): + # Callback runs on training end + if plots: + plot_results(file=self.save_dir / 'results.csv') # save results.png + files = ['results.png', 'confusion_matrix.png', *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))] + files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter + self.logger.info(f"Results saved to {colorstr('bold', self.save_dir)}") + + if self.tb: + for f in files: + self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC') + + if self.wandb: + self.wandb.log(dict(zip(self.keys[3:10], results))) + self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]}) + # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model + if not self.opt.evolve: + wandb.log_artifact(str(best if best.exists() else last), + type='model', + name=f'run_{self.wandb.wandb_run.id}_model', + aliases=['latest', 'best', 'stripped']) + self.wandb.finish_run() + + def on_params_update(self, params): + # Update hyperparams or configs of the experiment + # params: A dict containing {param: value} pairs + if self.wandb: + self.wandb.wandb_run.config.update(params, allow_val_change=True) diff --git a/Y5_20221014/utils/loggers/__pycache__/__init__.cpython-37.pyc b/Y5_20221014/utils/loggers/__pycache__/__init__.cpython-37.pyc new file mode 100755 index 0000000..e4da763 Binary files /dev/null and b/Y5_20221014/utils/loggers/__pycache__/__init__.cpython-37.pyc differ diff --git a/Y5_20221014/utils/loggers/__pycache__/__init__.cpython-38.pyc b/Y5_20221014/utils/loggers/__pycache__/__init__.cpython-38.pyc new file mode 100755 index 0000000..11501e5 Binary files /dev/null and b/Y5_20221014/utils/loggers/__pycache__/__init__.cpython-38.pyc differ diff --git a/Y5_20221014/utils/loggers/wandb/README.md b/Y5_20221014/utils/loggers/wandb/README.md new file mode 100755 index 0000000..d78324b --- /dev/null +++ b/Y5_20221014/utils/loggers/wandb/README.md @@ -0,0 +1,162 @@ +📚 This guide explains how to use **Weights & Biases** (W&B) with YOLOv5 🚀. UPDATED 29 September 2021. + +- [About Weights & Biases](#about-weights-&-biases) +- [First-Time Setup](#first-time-setup) +- [Viewing runs](#viewing-runs) +- [Disabling wandb](#disabling-wandb) +- [Advanced Usage: Dataset Versioning and Evaluation](#advanced-usage) +- [Reports: Share your work with the world!](#reports) + +## About Weights & Biases + +Think of [W&B](https://wandb.ai/site?utm_campaign=repo_yolo_wandbtutorial) like GitHub for machine learning models. With a few lines of code, save everything you need to debug, compare and reproduce your models — architecture, hyperparameters, git commits, model weights, GPU usage, and even datasets and predictions. + +Used by top researchers including teams at OpenAI, Lyft, Github, and MILA, W&B is part of the new standard of best practices for machine learning. How W&B can help you optimize your machine learning workflows: + +- [Debug](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Free-2) model performance in real time +- [GPU usage](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#System-4) visualized automatically +- [Custom charts](https://wandb.ai/wandb/customizable-charts/reports/Powerful-Custom-Charts-To-Debug-Model-Peformance--VmlldzoyNzY4ODI) for powerful, extensible visualization +- [Share insights](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Share-8) interactively with collaborators +- [Optimize hyperparameters](https://docs.wandb.com/sweeps) efficiently +- [Track](https://docs.wandb.com/artifacts) datasets, pipelines, and production models + +## First-Time Setup + +
+ Toggle Details +When you first train, W&B will prompt you to create a new account and will generate an **API key** for you. If you are an existing user you can retrieve your key from https://wandb.ai/authorize. This key is used to tell W&B where to log your data. You only need to supply your key once, and then it is remembered on the same device. + +W&B will create a cloud **project** (default is 'YOLOv5') for your training runs, and each new training run will be provided a unique run **name** within that project as project/name. You can also manually set your project and run name as: + +```shell +$ python train.py --project ... --name ... +``` + +YOLOv5 notebook example: Open In Colab Open In Kaggle +Screen Shot 2021-09-29 at 10 23 13 PM + +
+ +## Viewing Runs + +
+ Toggle Details +Run information streams from your environment to the W&B cloud console as you train. This allows you to monitor and even cancel runs in realtime . All important information is logged: + +- Training & Validation losses +- Metrics: Precision, Recall, mAP@0.5, mAP@0.5:0.95 +- Learning Rate over time +- A bounding box debugging panel, showing the training progress over time +- GPU: Type, **GPU Utilization**, power, temperature, **CUDA memory usage** +- System: Disk I/0, CPU utilization, RAM memory usage +- Your trained model as W&B Artifact +- Environment: OS and Python types, Git repository and state, **training command** + +

Weights & Biases dashboard

+
+ +## Disabling wandb + +- training after running `wandb disabled` inside that directory creates no wandb run + ![Screenshot (84)](https://user-images.githubusercontent.com/15766192/143441777-c780bdd7-7cb4-4404-9559-b4316030a985.png) + +- To enable wandb again, run `wandb online` + ![Screenshot (85)](https://user-images.githubusercontent.com/15766192/143441866-7191b2cb-22f0-4e0f-ae64-2dc47dc13078.png) + +## Advanced Usage + +You can leverage W&B artifacts and Tables integration to easily visualize and manage your datasets, models and training evaluations. Here are some quick examples to get you started. + +
+

1: Train and Log Evaluation simultaneousy

+ This is an extension of the previous section, but it'll also training after uploading the dataset. This also evaluation Table + Evaluation table compares your predictions and ground truths across the validation set for each epoch. It uses the references to the already uploaded datasets, + so no images will be uploaded from your system more than once. +
+ Usage + Code $ python train.py --upload_data val + +![Screenshot from 2021-11-21 17-40-06](https://user-images.githubusercontent.com/15766192/142761183-c1696d8c-3f38-45ab-991a-bb0dfd98ae7d.png) + +
+ +

2. Visualize and Version Datasets

+ Log, visualize, dynamically query, and understand your data with W&B Tables. You can use the following command to log your dataset as a W&B Table. This will generate a {dataset}_wandb.yaml file which can be used to train from dataset artifact. +
+ Usage + Code $ python utils/logger/wandb/log_dataset.py --project ... --name ... --data .. + +![Screenshot (64)](https://user-images.githubusercontent.com/15766192/128486078-d8433890-98a3-4d12-8986-b6c0e3fc64b9.png) + +
+ +

3: Train using dataset artifact

+ When you upload a dataset as described in the first section, you get a new config file with an added `_wandb` to its name. This file contains the information that + can be used to train a model directly from the dataset artifact. This also logs evaluation +
+ Usage + Code $ python train.py --data {data}_wandb.yaml + +![Screenshot (72)](https://user-images.githubusercontent.com/15766192/128979739-4cf63aeb-a76f-483f-8861-1c0100b938a5.png) + +
+ +

4: Save model checkpoints as artifacts

+ To enable saving and versioning checkpoints of your experiment, pass `--save_period n` with the base cammand, where `n` represents checkpoint interval. + You can also log both the dataset and model checkpoints simultaneously. If not passed, only the final model will be logged + +
+ Usage + Code $ python train.py --save_period 1 + +![Screenshot (68)](https://user-images.githubusercontent.com/15766192/128726138-ec6c1f60-639d-437d-b4ee-3acd9de47ef3.png) + +
+ +
+ +

5: Resume runs from checkpoint artifacts.

+Any run can be resumed using artifacts if the --resume argument starts with wandb-artifact:// prefix followed by the run path, i.e, wandb-artifact://username/project/runid . This doesn't require the model checkpoint to be present on the local system. + +
+ Usage + Code $ python train.py --resume wandb-artifact://{run_path} + +![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png) + +
+ +

6: Resume runs from dataset artifact & checkpoint artifacts.

+ Local dataset or model checkpoints are not required. This can be used to resume runs directly on a different device + The syntax is same as the previous section, but you'll need to lof both the dataset and model checkpoints as artifacts, i.e, set bot --upload_dataset or + train from _wandb.yaml file and set --save_period + +
+ Usage + Code $ python train.py --resume wandb-artifact://{run_path} + +![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png) + +
+ + + +

Reports

+W&B Reports can be created from your saved runs for sharing online. Once a report is created you will receive a link you can use to publically share your results. Here is an example report created from the COCO128 tutorial trainings of all four YOLOv5 models ([link](https://wandb.ai/glenn-jocher/yolov5_tutorial/reports/YOLOv5-COCO128-Tutorial-Results--VmlldzozMDI5OTY)). + +Weights & Biases Reports + +## Environments + +YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled): + +- **Google Colab and Kaggle** notebooks with free GPU: Open In Colab Open In Kaggle +- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) +- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart) +- **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) Docker Pulls + +## Status + +![CI CPU testing](https://github.com/ultralytics/yolov5/workflows/CI%20CPU%20testing/badge.svg) + +If this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), validation ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on macOS, Windows, and Ubuntu every 24 hours and on every commit. diff --git a/Y5_20221014/utils/loggers/wandb/__init__.py b/Y5_20221014/utils/loggers/wandb/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/Y5_20221014/utils/loggers/wandb/__pycache__/__init__.cpython-37.pyc b/Y5_20221014/utils/loggers/wandb/__pycache__/__init__.cpython-37.pyc new file mode 100755 index 0000000..6455f79 Binary files /dev/null and b/Y5_20221014/utils/loggers/wandb/__pycache__/__init__.cpython-37.pyc differ diff --git a/Y5_20221014/utils/loggers/wandb/__pycache__/__init__.cpython-38.pyc b/Y5_20221014/utils/loggers/wandb/__pycache__/__init__.cpython-38.pyc new file mode 100755 index 0000000..30760d4 Binary files /dev/null and b/Y5_20221014/utils/loggers/wandb/__pycache__/__init__.cpython-38.pyc differ diff --git a/Y5_20221014/utils/loggers/wandb/__pycache__/wandb_utils.cpython-37.pyc b/Y5_20221014/utils/loggers/wandb/__pycache__/wandb_utils.cpython-37.pyc new file mode 100755 index 0000000..169b2a4 Binary files /dev/null and b/Y5_20221014/utils/loggers/wandb/__pycache__/wandb_utils.cpython-37.pyc differ diff --git a/Y5_20221014/utils/loggers/wandb/__pycache__/wandb_utils.cpython-38.pyc b/Y5_20221014/utils/loggers/wandb/__pycache__/wandb_utils.cpython-38.pyc new file mode 100755 index 0000000..159cb2a Binary files /dev/null and b/Y5_20221014/utils/loggers/wandb/__pycache__/wandb_utils.cpython-38.pyc differ diff --git a/Y5_20221014/utils/loggers/wandb/log_dataset.py b/Y5_20221014/utils/loggers/wandb/log_dataset.py new file mode 100755 index 0000000..06e81fb --- /dev/null +++ b/Y5_20221014/utils/loggers/wandb/log_dataset.py @@ -0,0 +1,27 @@ +import argparse + +from wandb_utils import WandbLogger + +from utils.general import LOGGER + +WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' + + +def create_dataset_artifact(opt): + logger = WandbLogger(opt, None, job_type='Dataset Creation') # TODO: return value unused + if not logger.wandb: + LOGGER.info("install wandb using `pip install wandb` to log the dataset") + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path') + parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') + parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project') + parser.add_argument('--entity', default=None, help='W&B entity') + parser.add_argument('--name', type=str, default='log dataset', help='name of W&B run') + + opt = parser.parse_args() + opt.resume = False # Explicitly disallow resume check for dataset upload job + + create_dataset_artifact(opt) diff --git a/Y5_20221014/utils/loggers/wandb/sweep.py b/Y5_20221014/utils/loggers/wandb/sweep.py new file mode 100755 index 0000000..d49ea6f --- /dev/null +++ b/Y5_20221014/utils/loggers/wandb/sweep.py @@ -0,0 +1,41 @@ +import sys +from pathlib import Path + +import wandb + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[3] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH + +from train import parse_opt, train +from utils.callbacks import Callbacks +from utils.general import increment_path +from utils.torch_utils import select_device + + +def sweep(): + wandb.init() + # Get hyp dict from sweep agent. Copy because train() modifies parameters which confused wandb. + hyp_dict = vars(wandb.config).get("_items").copy() + + # Workaround: get necessary opt args + opt = parse_opt(known=True) + opt.batch_size = hyp_dict.get("batch_size") + opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve)) + opt.epochs = hyp_dict.get("epochs") + opt.nosave = True + opt.data = hyp_dict.get("data") + opt.weights = str(opt.weights) + opt.cfg = str(opt.cfg) + opt.data = str(opt.data) + opt.hyp = str(opt.hyp) + opt.project = str(opt.project) + device = select_device(opt.device, batch_size=opt.batch_size) + + # train + train(hyp_dict, opt, device, callbacks=Callbacks()) + + +if __name__ == "__main__": + sweep() diff --git a/Y5_20221014/utils/loggers/wandb/sweep.yaml b/Y5_20221014/utils/loggers/wandb/sweep.yaml new file mode 100755 index 0000000..688b1ea --- /dev/null +++ b/Y5_20221014/utils/loggers/wandb/sweep.yaml @@ -0,0 +1,143 @@ +# Hyperparameters for training +# To set range- +# Provide min and max values as: +# parameter: +# +# min: scalar +# max: scalar +# OR +# +# Set a specific list of search space- +# parameter: +# values: [scalar1, scalar2, scalar3...] +# +# You can use grid, bayesian and hyperopt search strategy +# For more info on configuring sweeps visit - https://docs.wandb.ai/guides/sweeps/configuration + +program: utils/loggers/wandb/sweep.py +method: random +metric: + name: metrics/mAP_0.5 + goal: maximize + +parameters: + # hyperparameters: set either min, max range or values list + data: + value: "data/coco128.yaml" + batch_size: + values: [64] + epochs: + values: [10] + + lr0: + distribution: uniform + min: 1e-5 + max: 1e-1 + lrf: + distribution: uniform + min: 0.01 + max: 1.0 + momentum: + distribution: uniform + min: 0.6 + max: 0.98 + weight_decay: + distribution: uniform + min: 0.0 + max: 0.001 + warmup_epochs: + distribution: uniform + min: 0.0 + max: 5.0 + warmup_momentum: + distribution: uniform + min: 0.0 + max: 0.95 + warmup_bias_lr: + distribution: uniform + min: 0.0 + max: 0.2 + box: + distribution: uniform + min: 0.02 + max: 0.2 + cls: + distribution: uniform + min: 0.2 + max: 4.0 + cls_pw: + distribution: uniform + min: 0.5 + max: 2.0 + obj: + distribution: uniform + min: 0.2 + max: 4.0 + obj_pw: + distribution: uniform + min: 0.5 + max: 2.0 + iou_t: + distribution: uniform + min: 0.1 + max: 0.7 + anchor_t: + distribution: uniform + min: 2.0 + max: 8.0 + fl_gamma: + distribution: uniform + min: 0.0 + max: 4.0 + hsv_h: + distribution: uniform + min: 0.0 + max: 0.1 + hsv_s: + distribution: uniform + min: 0.0 + max: 0.9 + hsv_v: + distribution: uniform + min: 0.0 + max: 0.9 + degrees: + distribution: uniform + min: 0.0 + max: 45.0 + translate: + distribution: uniform + min: 0.0 + max: 0.9 + scale: + distribution: uniform + min: 0.0 + max: 0.9 + shear: + distribution: uniform + min: 0.0 + max: 10.0 + perspective: + distribution: uniform + min: 0.0 + max: 0.001 + flipud: + distribution: uniform + min: 0.0 + max: 1.0 + fliplr: + distribution: uniform + min: 0.0 + max: 1.0 + mosaic: + distribution: uniform + min: 0.0 + max: 1.0 + mixup: + distribution: uniform + min: 0.0 + max: 1.0 + copy_paste: + distribution: uniform + min: 0.0 + max: 1.0 diff --git a/Y5_20221014/utils/loggers/wandb/wandb_utils.py b/Y5_20221014/utils/loggers/wandb/wandb_utils.py new file mode 100755 index 0000000..04521bf --- /dev/null +++ b/Y5_20221014/utils/loggers/wandb/wandb_utils.py @@ -0,0 +1,577 @@ +"""Utilities and tools for tracking runs with Weights & Biases.""" + +import logging +import os +import sys +from contextlib import contextmanager +from pathlib import Path +from typing import Dict + +import yaml +from tqdm import tqdm + +FILE = Path(__file__).resolve() +ROOT = FILE.parents[3] # YOLOv5 root directory +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH + +from utils.dataloaders import LoadImagesAndLabels, img2label_paths +from utils.general import LOGGER, check_dataset, check_file + +try: + import wandb + + assert hasattr(wandb, '__version__') # verify package import not local dir +except (ImportError, AssertionError): + wandb = None + +RANK = int(os.getenv('RANK', -1)) +WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' + + +def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX): + return from_string[len(prefix):] + + +def check_wandb_config_file(data_config_file): + wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path + if Path(wandb_config).is_file(): + return wandb_config + return data_config_file + + +def check_wandb_dataset(data_file): + is_trainset_wandb_artifact = False + is_valset_wandb_artifact = False + if check_file(data_file) and data_file.endswith('.yaml'): + with open(data_file, errors='ignore') as f: + data_dict = yaml.safe_load(f) + is_trainset_wandb_artifact = isinstance(data_dict['train'], + str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX) + is_valset_wandb_artifact = isinstance(data_dict['val'], + str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX) + if is_trainset_wandb_artifact or is_valset_wandb_artifact: + return data_dict + else: + return check_dataset(data_file) + + +def get_run_info(run_path): + run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX)) + run_id = run_path.stem + project = run_path.parent.stem + entity = run_path.parent.parent.stem + model_artifact_name = 'run_' + run_id + '_model' + return entity, project, run_id, model_artifact_name + + +def check_wandb_resume(opt): + process_wandb_config_ddp_mode(opt) if RANK not in [-1, 0] else None + if isinstance(opt.resume, str): + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + if RANK not in [-1, 0]: # For resuming DDP runs + entity, project, run_id, model_artifact_name = get_run_info(opt.resume) + api = wandb.Api() + artifact = api.artifact(entity + '/' + project + '/' + model_artifact_name + ':latest') + modeldir = artifact.download() + opt.weights = str(Path(modeldir) / "last.pt") + return True + return None + + +def process_wandb_config_ddp_mode(opt): + with open(check_file(opt.data), errors='ignore') as f: + data_dict = yaml.safe_load(f) # data dict + train_dir, val_dir = None, None + if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX): + api = wandb.Api() + train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias) + train_dir = train_artifact.download() + train_path = Path(train_dir) / 'data/images/' + data_dict['train'] = str(train_path) + + if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX): + api = wandb.Api() + val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias) + val_dir = val_artifact.download() + val_path = Path(val_dir) / 'data/images/' + data_dict['val'] = str(val_path) + if train_dir or val_dir: + ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml') + with open(ddp_data_path, 'w') as f: + yaml.safe_dump(data_dict, f) + opt.data = ddp_data_path + + +class WandbLogger(): + """Log training runs, datasets, models, and predictions to Weights & Biases. + + This logger sends information to W&B at wandb.ai. By default, this information + includes hyperparameters, system configuration and metrics, model metrics, + and basic data metrics and analyses. + + By providing additional command line arguments to train.py, datasets, + models and predictions can also be logged. + + For more on how this logger is used, see the Weights & Biases documentation: + https://docs.wandb.com/guides/integrations/yolov5 + """ + + def __init__(self, opt, run_id=None, job_type='Training'): + """ + - Initialize WandbLogger instance + - Upload dataset if opt.upload_dataset is True + - Setup trainig processes if job_type is 'Training' + + arguments: + opt (namespace) -- Commandline arguments for this run + run_id (str) -- Run ID of W&B run to be resumed + job_type (str) -- To set the job_type for this run + + """ + # Pre-training routine -- + self.job_type = job_type + self.wandb, self.wandb_run = wandb, None if not wandb else wandb.run + self.val_artifact, self.train_artifact = None, None + self.train_artifact_path, self.val_artifact_path = None, None + self.result_artifact = None + self.val_table, self.result_table = None, None + self.bbox_media_panel_images = [] + self.val_table_path_map = None + self.max_imgs_to_log = 16 + self.wandb_artifact_data_dict = None + self.data_dict = None + # It's more elegant to stick to 1 wandb.init call, + # but useful config data is overwritten in the WandbLogger's wandb.init call + if isinstance(opt.resume, str): # checks resume from artifact + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + entity, project, run_id, model_artifact_name = get_run_info(opt.resume) + model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name + assert wandb, 'install wandb to resume wandb runs' + # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config + self.wandb_run = wandb.init(id=run_id, + project=project, + entity=entity, + resume='allow', + allow_val_change=True) + opt.resume = model_artifact_name + elif self.wandb: + self.wandb_run = wandb.init(config=opt, + resume="allow", + project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem, + entity=opt.entity, + name=opt.name if opt.name != 'exp' else None, + job_type=job_type, + id=run_id, + allow_val_change=True) if not wandb.run else wandb.run + if self.wandb_run: + if self.job_type == 'Training': + if opt.upload_dataset: + if not opt.resume: + self.wandb_artifact_data_dict = self.check_and_upload_dataset(opt) + + if opt.resume: + # resume from artifact + if isinstance(opt.resume, str) and opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + self.data_dict = dict(self.wandb_run.config.data_dict) + else: # local resume + self.data_dict = check_wandb_dataset(opt.data) + else: + self.data_dict = check_wandb_dataset(opt.data) + self.wandb_artifact_data_dict = self.wandb_artifact_data_dict or self.data_dict + + # write data_dict to config. useful for resuming from artifacts. Do this only when not resuming. + self.wandb_run.config.update({'data_dict': self.wandb_artifact_data_dict}, allow_val_change=True) + self.setup_training(opt) + + if self.job_type == 'Dataset Creation': + self.wandb_run.config.update({"upload_dataset": True}) + self.data_dict = self.check_and_upload_dataset(opt) + + def check_and_upload_dataset(self, opt): + """ + Check if the dataset format is compatible and upload it as W&B artifact + + arguments: + opt (namespace)-- Commandline arguments for current run + + returns: + Updated dataset info dictionary where local dataset paths are replaced by WAND_ARFACT_PREFIX links. + """ + assert wandb, 'Install wandb to upload dataset' + config_path = self.log_dataset_artifact(opt.data, opt.single_cls, + 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem) + with open(config_path, errors='ignore') as f: + wandb_data_dict = yaml.safe_load(f) + return wandb_data_dict + + def setup_training(self, opt): + """ + Setup the necessary processes for training YOLO models: + - Attempt to download model checkpoint and dataset artifacts if opt.resume stats with WANDB_ARTIFACT_PREFIX + - Update data_dict, to contain info of previous run if resumed and the paths of dataset artifact if downloaded + - Setup log_dict, initialize bbox_interval + + arguments: + opt (namespace) -- commandline arguments for this run + + """ + self.log_dict, self.current_epoch = {}, 0 + self.bbox_interval = opt.bbox_interval + if isinstance(opt.resume, str): + modeldir, _ = self.download_model_artifact(opt) + if modeldir: + self.weights = Path(modeldir) / "last.pt" + config = self.wandb_run.config + opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp, opt.imgsz = str( + self.weights), config.save_period, config.batch_size, config.bbox_interval, config.epochs,\ + config.hyp, config.imgsz + data_dict = self.data_dict + if self.val_artifact is None: # If --upload_dataset is set, use the existing artifact, don't download + self.train_artifact_path, self.train_artifact = self.download_dataset_artifact( + data_dict.get('train'), opt.artifact_alias) + self.val_artifact_path, self.val_artifact = self.download_dataset_artifact( + data_dict.get('val'), opt.artifact_alias) + + if self.train_artifact_path is not None: + train_path = Path(self.train_artifact_path) / 'data/images/' + data_dict['train'] = str(train_path) + if self.val_artifact_path is not None: + val_path = Path(self.val_artifact_path) / 'data/images/' + data_dict['val'] = str(val_path) + + if self.val_artifact is not None: + self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") + columns = ["epoch", "id", "ground truth", "prediction"] + columns.extend(self.data_dict['names']) + self.result_table = wandb.Table(columns) + self.val_table = self.val_artifact.get("val") + if self.val_table_path_map is None: + self.map_val_table_path() + if opt.bbox_interval == -1: + self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1 + if opt.evolve or opt.noplots: + self.bbox_interval = opt.bbox_interval = opt.epochs + 1 # disable bbox_interval + train_from_artifact = self.train_artifact_path is not None and self.val_artifact_path is not None + # Update the the data_dict to point to local artifacts dir + if train_from_artifact: + self.data_dict = data_dict + + def download_dataset_artifact(self, path, alias): + """ + download the model checkpoint artifact if the path starts with WANDB_ARTIFACT_PREFIX + + arguments: + path -- path of the dataset to be used for training + alias (str)-- alias of the artifact to be download/used for training + + returns: + (str, wandb.Artifact) -- path of the downladed dataset and it's corresponding artifact object if dataset + is found otherwise returns (None, None) + """ + if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX): + artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias) + dataset_artifact = wandb.use_artifact(artifact_path.as_posix().replace("\\", "/")) + assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'" + datadir = dataset_artifact.download() + return datadir, dataset_artifact + return None, None + + def download_model_artifact(self, opt): + """ + download the model checkpoint artifact if the resume path starts with WANDB_ARTIFACT_PREFIX + + arguments: + opt (namespace) -- Commandline arguments for this run + """ + if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): + model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest") + assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist' + modeldir = model_artifact.download() + # epochs_trained = model_artifact.metadata.get('epochs_trained') + total_epochs = model_artifact.metadata.get('total_epochs') + is_finished = total_epochs is None + assert not is_finished, 'training is finished, can only resume incomplete runs.' + return modeldir, model_artifact + return None, None + + def log_model(self, path, opt, epoch, fitness_score, best_model=False): + """ + Log the model checkpoint as W&B artifact + + arguments: + path (Path) -- Path of directory containing the checkpoints + opt (namespace) -- Command line arguments for this run + epoch (int) -- Current epoch number + fitness_score (float) -- fitness score for current epoch + best_model (boolean) -- Boolean representing if the current checkpoint is the best yet. + """ + model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', + type='model', + metadata={ + 'original_url': str(path), + 'epochs_trained': epoch + 1, + 'save period': opt.save_period, + 'project': opt.project, + 'total_epochs': opt.epochs, + 'fitness_score': fitness_score}) + model_artifact.add_file(str(path / 'last.pt'), name='last.pt') + wandb.log_artifact(model_artifact, + aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 'best' if best_model else '']) + LOGGER.info(f"Saving model artifact on epoch {epoch + 1}") + + def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False): + """ + Log the dataset as W&B artifact and return the new data file with W&B links + + arguments: + data_file (str) -- the .yaml file with information about the dataset like - path, classes etc. + single_class (boolean) -- train multi-class data as single-class + project (str) -- project name. Used to construct the artifact path + overwrite_config (boolean) -- overwrites the data.yaml file if set to true otherwise creates a new + file with _wandb postfix. Eg -> data_wandb.yaml + + returns: + the new .yaml file with artifact links. it can be used to start training directly from artifacts + """ + upload_dataset = self.wandb_run.config.upload_dataset + log_val_only = isinstance(upload_dataset, str) and upload_dataset == 'val' + self.data_dict = check_dataset(data_file) # parse and check + data = dict(self.data_dict) + nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names']) + names = {k: v for k, v in enumerate(names)} # to index dictionary + + # log train set + if not log_val_only: + self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(data['train'], rect=True, batch_size=1), + names, + name='train') if data.get('train') else None + if data.get('train'): + data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train') + + self.val_artifact = self.create_dataset_table( + LoadImagesAndLabels(data['val'], rect=True, batch_size=1), names, name='val') if data.get('val') else None + if data.get('val'): + data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val') + + path = Path(data_file) + # create a _wandb.yaml file with artifacts links if both train and test set are logged + if not log_val_only: + path = (path.stem if overwrite_config else path.stem + '_wandb') + '.yaml' # updated data.yaml path + path = ROOT / 'data' / path + data.pop('download', None) + data.pop('path', None) + with open(path, 'w') as f: + yaml.safe_dump(data, f) + LOGGER.info(f"Created dataset config file {path}") + + if self.job_type == 'Training': # builds correct artifact pipeline graph + if not log_val_only: + self.wandb_run.log_artifact( + self.train_artifact) # calling use_artifact downloads the dataset. NOT NEEDED! + self.wandb_run.use_artifact(self.val_artifact) + self.val_artifact.wait() + self.val_table = self.val_artifact.get('val') + self.map_val_table_path() + else: + self.wandb_run.log_artifact(self.train_artifact) + self.wandb_run.log_artifact(self.val_artifact) + return path + + def map_val_table_path(self): + """ + Map the validation dataset Table like name of file -> it's id in the W&B Table. + Useful for - referencing artifacts for evaluation. + """ + self.val_table_path_map = {} + LOGGER.info("Mapping dataset") + for i, data in enumerate(tqdm(self.val_table.data)): + self.val_table_path_map[data[3]] = data[0] + + def create_dataset_table(self, dataset: LoadImagesAndLabels, class_to_id: Dict[int, str], name: str = 'dataset'): + """ + Create and return W&B artifact containing W&B Table of the dataset. + + arguments: + dataset -- instance of LoadImagesAndLabels class used to iterate over the data to build Table + class_to_id -- hash map that maps class ids to labels + name -- name of the artifact + + returns: + dataset artifact to be logged or used + """ + # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging + artifact = wandb.Artifact(name=name, type="dataset") + img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None + img_files = tqdm(dataset.im_files) if not img_files else img_files + for img_file in img_files: + if Path(img_file).is_dir(): + artifact.add_dir(img_file, name='data/images') + labels_path = 'labels'.join(dataset.path.rsplit('images', 1)) + artifact.add_dir(labels_path, name='data/labels') + else: + artifact.add_file(img_file, name='data/images/' + Path(img_file).name) + label_file = Path(img2label_paths([img_file])[0]) + artifact.add_file(str(label_file), name='data/labels/' + + label_file.name) if label_file.exists() else None + table = wandb.Table(columns=["id", "train_image", "Classes", "name"]) + class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()]) + for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)): + box_data, img_classes = [], {} + for cls, *xywh in labels[:, 1:].tolist(): + cls = int(cls) + box_data.append({ + "position": { + "middle": [xywh[0], xywh[1]], + "width": xywh[2], + "height": xywh[3]}, + "class_id": cls, + "box_caption": "%s" % (class_to_id[cls])}) + img_classes[cls] = class_to_id[cls] + boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space + table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), list(img_classes.values()), + Path(paths).name) + artifact.add(table, name) + return artifact + + def log_training_progress(self, predn, path, names): + """ + Build evaluation Table. Uses reference from validation dataset table. + + arguments: + predn (list): list of predictions in the native space in the format - [xmin, ymin, xmax, ymax, confidence, class] + path (str): local path of the current evaluation image + names (dict(int, str)): hash map that maps class ids to labels + """ + class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()]) + box_data = [] + avg_conf_per_class = [0] * len(self.data_dict['names']) + pred_class_count = {} + for *xyxy, conf, cls in predn.tolist(): + if conf >= 0.25: + cls = int(cls) + box_data.append({ + "position": { + "minX": xyxy[0], + "minY": xyxy[1], + "maxX": xyxy[2], + "maxY": xyxy[3]}, + "class_id": cls, + "box_caption": f"{names[cls]} {conf:.3f}", + "scores": { + "class_score": conf}, + "domain": "pixel"}) + avg_conf_per_class[cls] += conf + + if cls in pred_class_count: + pred_class_count[cls] += 1 + else: + pred_class_count[cls] = 1 + + for pred_class in pred_class_count.keys(): + avg_conf_per_class[pred_class] = avg_conf_per_class[pred_class] / pred_class_count[pred_class] + + boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space + id = self.val_table_path_map[Path(path).name] + self.result_table.add_data(self.current_epoch, id, self.val_table.data[id][1], + wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set), + *avg_conf_per_class) + + def val_one_image(self, pred, predn, path, names, im): + """ + Log validation data for one image. updates the result Table if validation dataset is uploaded and log bbox media panel + + arguments: + pred (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class] + predn (list): list of predictions in the native space - [xmin, ymin, xmax, ymax, confidence, class] + path (str): local path of the current evaluation image + """ + if self.val_table and self.result_table: # Log Table if Val dataset is uploaded as artifact + self.log_training_progress(predn, path, names) + + if len(self.bbox_media_panel_images) < self.max_imgs_to_log and self.current_epoch > 0: + if self.current_epoch % self.bbox_interval == 0: + box_data = [{ + "position": { + "minX": xyxy[0], + "minY": xyxy[1], + "maxX": xyxy[2], + "maxY": xyxy[3]}, + "class_id": int(cls), + "box_caption": f"{names[int(cls)]} {conf:.3f}", + "scores": { + "class_score": conf}, + "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()] + boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space + self.bbox_media_panel_images.append(wandb.Image(im, boxes=boxes, caption=path.name)) + + def log(self, log_dict): + """ + save the metrics to the logging dictionary + + arguments: + log_dict (Dict) -- metrics/media to be logged in current step + """ + if self.wandb_run: + for key, value in log_dict.items(): + self.log_dict[key] = value + + def end_epoch(self, best_result=False): + """ + commit the log_dict, model artifacts and Tables to W&B and flush the log_dict. + + arguments: + best_result (boolean): Boolean representing if the result of this evaluation is best or not + """ + if self.wandb_run: + with all_logging_disabled(): + if self.bbox_media_panel_images: + self.log_dict["BoundingBoxDebugger"] = self.bbox_media_panel_images + try: + wandb.log(self.log_dict) + except BaseException as e: + LOGGER.info( + f"An error occurred in wandb logger. The training will proceed without interruption. More info\n{e}" + ) + self.wandb_run.finish() + self.wandb_run = None + + self.log_dict = {} + self.bbox_media_panel_images = [] + if self.result_artifact: + self.result_artifact.add(self.result_table, 'result') + wandb.log_artifact(self.result_artifact, + aliases=[ + 'latest', 'last', 'epoch ' + str(self.current_epoch), + ('best' if best_result else '')]) + + wandb.log({"evaluation": self.result_table}) + columns = ["epoch", "id", "ground truth", "prediction"] + columns.extend(self.data_dict['names']) + self.result_table = wandb.Table(columns) + self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") + + def finish_run(self): + """ + Log metrics if any and finish the current W&B run + """ + if self.wandb_run: + if self.log_dict: + with all_logging_disabled(): + wandb.log(self.log_dict) + wandb.run.finish() + + +@contextmanager +def all_logging_disabled(highest_level=logging.CRITICAL): + """ source - https://gist.github.com/simon-weber/7853144 + A context manager that will prevent any logging messages triggered during the body from being processed. + :param highest_level: the maximum logging level in use. + This would only need to be changed if a custom level greater than CRITICAL is defined. + """ + previous_level = logging.root.manager.disable + logging.disable(highest_level) + try: + yield + finally: + logging.disable(previous_level) diff --git a/Y5_20221014/utils/loss.py b/Y5_20221014/utils/loss.py new file mode 100755 index 0000000..9b9c3d9 --- /dev/null +++ b/Y5_20221014/utils/loss.py @@ -0,0 +1,234 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Loss functions +""" + +import torch +import torch.nn as nn + +from utils.metrics import bbox_iou +from utils.torch_utils import de_parallel + + +def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441 + # return positive, negative label smoothing BCE targets + return 1.0 - 0.5 * eps, 0.5 * eps + + +class BCEBlurWithLogitsLoss(nn.Module): + # BCEwithLogitLoss() with reduced missing label effects. + def __init__(self, alpha=0.05): + super().__init__() + self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss() + self.alpha = alpha + + def forward(self, pred, true): + loss = self.loss_fcn(pred, true) + pred = torch.sigmoid(pred) # prob from logits + dx = pred - true # reduce only missing label effects + # dx = (pred - true).abs() # reduce missing label and false label effects + alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4)) + loss *= alpha_factor + return loss.mean() + + +class FocalLoss(nn.Module): + # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) + def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): + super().__init__() + self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() + self.gamma = gamma + self.alpha = alpha + self.reduction = loss_fcn.reduction + self.loss_fcn.reduction = 'none' # required to apply FL to each element + + def forward(self, pred, true): + loss = self.loss_fcn(pred, true) + # p_t = torch.exp(-loss) + # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability + + # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py + pred_prob = torch.sigmoid(pred) # prob from logits + p_t = true * pred_prob + (1 - true) * (1 - pred_prob) + alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) + modulating_factor = (1.0 - p_t) ** self.gamma + loss *= alpha_factor * modulating_factor + + if self.reduction == 'mean': + return loss.mean() + elif self.reduction == 'sum': + return loss.sum() + else: # 'none' + return loss + + +class QFocalLoss(nn.Module): + # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) + def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): + super().__init__() + self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() + self.gamma = gamma + self.alpha = alpha + self.reduction = loss_fcn.reduction + self.loss_fcn.reduction = 'none' # required to apply FL to each element + + def forward(self, pred, true): + loss = self.loss_fcn(pred, true) + + pred_prob = torch.sigmoid(pred) # prob from logits + alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) + modulating_factor = torch.abs(true - pred_prob) ** self.gamma + loss *= alpha_factor * modulating_factor + + if self.reduction == 'mean': + return loss.mean() + elif self.reduction == 'sum': + return loss.sum() + else: # 'none' + return loss + + +class ComputeLoss: + sort_obj_iou = False + + # Compute losses + def __init__(self, model, autobalance=False): + device = next(model.parameters()).device # get model device + h = model.hyp # hyperparameters + + # Define criteria + BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device)) + BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device)) + + # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3 + self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets + + # Focal loss + g = h['fl_gamma'] # focal loss gamma + if g > 0: + BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g) + + m = de_parallel(model).model[-1] # Detect() module + self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7 + self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index + self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance + self.na = m.na # number of anchors + self.nc = m.nc # number of classes + self.nl = m.nl # number of layers + self.anchors = m.anchors + self.device = device + + def __call__(self, p, targets): # predictions, targets + lcls = torch.zeros(1, device=self.device) # class loss + lbox = torch.zeros(1, device=self.device) # box loss + lobj = torch.zeros(1, device=self.device) # object loss + tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets + + # Losses + for i, pi in enumerate(p): # layer index, layer predictions + b, a, gj, gi = indices[i] # image, anchor, gridy, gridx + tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device) # target obj + + n = b.shape[0] # number of targets + if n: + # pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1) # faster, requires torch 1.8.0 + pxy, pwh, _, pcls = pi[b, a, gj, gi].split((2, 2, 1, self.nc), 1) # target-subset of predictions + + # Regression + pxy = pxy.sigmoid() * 2 - 0.5 + pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i] + pbox = torch.cat((pxy, pwh), 1) # predicted box + iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(prediction, target) + lbox += (1.0 - iou).mean() # iou loss + + # Objectness + iou = iou.detach().clamp(0).type(tobj.dtype) + if self.sort_obj_iou: + j = iou.argsort() + b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j] + if self.gr < 1: + iou = (1.0 - self.gr) + self.gr * iou + tobj[b, a, gj, gi] = iou # iou ratio + + # Classification + if self.nc > 1: # cls loss (only if multiple classes) + t = torch.full_like(pcls, self.cn, device=self.device) # targets + t[range(n), tcls[i]] = self.cp + lcls += self.BCEcls(pcls, t) # BCE + + # Append targets to text file + # with open('targets.txt', 'a') as file: + # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)] + + obji = self.BCEobj(pi[..., 4], tobj) + lobj += obji * self.balance[i] # obj loss + if self.autobalance: + self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item() + + if self.autobalance: + self.balance = [x / self.balance[self.ssi] for x in self.balance] + lbox *= self.hyp['box'] + lobj *= self.hyp['obj'] + lcls *= self.hyp['cls'] + bs = tobj.shape[0] # batch size + + return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach() + + def build_targets(self, p, targets): + # Build targets for compute_loss(), input targets(image,class,x,y,w,h) + na, nt = self.na, targets.shape[0] # number of anchors, targets + tcls, tbox, indices, anch = [], [], [], [] + gain = torch.ones(7, device=self.device) # normalized to gridspace gain + ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) + targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2) # append anchor indices + + g = 0.5 # bias + off = torch.tensor( + [ + [0, 0], + [1, 0], + [0, 1], + [-1, 0], + [0, -1], # j,k,l,m + # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm + ], + device=self.device).float() * g # offsets + + for i in range(self.nl): + anchors, shape = self.anchors[i], p[i].shape + gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain + + # Match targets to anchors + t = targets * gain # shape(3,n,7) + if nt: + # Matches + r = t[..., 4:6] / anchors[:, None] # wh ratio + j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t'] # compare + # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2)) + t = t[j] # filter + + # Offsets + gxy = t[:, 2:4] # grid xy + gxi = gain[[2, 3]] - gxy # inverse + j, k = ((gxy % 1 < g) & (gxy > 1)).T + l, m = ((gxi % 1 < g) & (gxi > 1)).T + j = torch.stack((torch.ones_like(j), j, k, l, m)) + t = t.repeat((5, 1, 1))[j] + offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] + else: + t = targets[0] + offsets = 0 + + # Define + bc, gxy, gwh, a = t.chunk(4, 1) # (image, class), grid xy, grid wh, anchors + a, (b, c) = a.long().view(-1), bc.long().T # anchors, image, class + gij = (gxy - offsets).long() + gi, gj = gij.T # grid indices + + # Append + indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, anchor, grid + tbox.append(torch.cat((gxy - gij, gwh), 1)) # box + anch.append(anchors[a]) # anchors + tcls.append(c) # class + + return tcls, tbox, indices, anch diff --git a/Y5_20221014/utils/metrics.py b/Y5_20221014/utils/metrics.py new file mode 100755 index 0000000..e17747b --- /dev/null +++ b/Y5_20221014/utils/metrics.py @@ -0,0 +1,355 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Model validation metrics +""" + +import math +import warnings +from pathlib import Path + +import matplotlib.pyplot as plt +import numpy as np +import torch + + +def fitness(x): + # Model fitness as a weighted combination of metrics + w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95] + return (x[:, :4] * w).sum(1) + + +def smooth(y, f=0.05): + # Box filter of fraction f + nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd) + p = np.ones(nf // 2) # ones padding + yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded + return np.convolve(yp, np.ones(nf) / nf, mode='valid') # y-smoothed + + +def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16): + """ Compute the average precision, given the recall and precision curves. + Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. + # Arguments + tp: True positives (nparray, nx1 or nx10). + conf: Objectness value from 0-1 (nparray). + pred_cls: Predicted object classes (nparray). + target_cls: True object classes (nparray). + plot: Plot precision-recall curve at mAP@0.5 + save_dir: Plot save directory + # Returns + The average precision as computed in py-faster-rcnn. + """ + + # Sort by objectness + i = np.argsort(-conf) + tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] + + # Find unique classes + unique_classes, nt = np.unique(target_cls, return_counts=True) + nc = unique_classes.shape[0] # number of classes, number of detections + + # Create Precision-Recall curve and compute AP for each class + px, py = np.linspace(0, 1, 1000), [] # for plotting + ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000)) + for ci, c in enumerate(unique_classes): + i = pred_cls == c + n_l = nt[ci] # number of labels + n_p = i.sum() # number of predictions + if n_p == 0 or n_l == 0: + continue + + # Accumulate FPs and TPs + fpc = (1 - tp[i]).cumsum(0) + tpc = tp[i].cumsum(0) + + # Recall + recall = tpc / (n_l + eps) # recall curve + r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases + + # Precision + precision = tpc / (tpc + fpc) # precision curve + p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score + + # AP from recall-precision curve + for j in range(tp.shape[1]): + ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j]) + if plot and j == 0: + py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5 + + # Compute F1 (harmonic mean of precision and recall) + f1 = 2 * p * r / (p + r + eps) + names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data + names = dict(enumerate(names)) # to dict + if plot: + plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names) + plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1') + plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision') + plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall') + + i = smooth(f1.mean(0), 0.1).argmax() # max F1 index + p, r, f1 = p[:, i], r[:, i], f1[:, i] + tp = (r * nt).round() # true positives + fp = (tp / (p + eps) - tp).round() # false positives + return tp, fp, p, r, f1, ap, unique_classes.astype(int) + + +def compute_ap(recall, precision): + """ Compute the average precision, given the recall and precision curves + # Arguments + recall: The recall curve (list) + precision: The precision curve (list) + # Returns + Average precision, precision curve, recall curve + """ + + # Append sentinel values to beginning and end + mrec = np.concatenate(([0.0], recall, [1.0])) + mpre = np.concatenate(([1.0], precision, [0.0])) + + # Compute the precision envelope + mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) + + # Integrate area under curve + method = 'interp' # methods: 'continuous', 'interp' + if method == 'interp': + x = np.linspace(0, 1, 101) # 101-point interp (COCO) + ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate + else: # 'continuous' + i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes + ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve + + return ap, mpre, mrec + + +class ConfusionMatrix: + # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix + def __init__(self, nc, conf=0.25, iou_thres=0.45): + self.matrix = np.zeros((nc + 1, nc + 1)) + self.nc = nc # number of classes + self.conf = conf + self.iou_thres = iou_thres + + def process_batch(self, detections, labels): + """ + Return intersection-over-union (Jaccard index) of boxes. + Both sets of boxes are expected to be in (x1, y1, x2, y2) format. + Arguments: + detections (Array[N, 6]), x1, y1, x2, y2, conf, class + labels (Array[M, 5]), class, x1, y1, x2, y2 + Returns: + None, updates confusion matrix accordingly + """ + detections = detections[detections[:, 4] > self.conf] + gt_classes = labels[:, 0].int() + detection_classes = detections[:, 5].int() + iou = box_iou(labels[:, 1:], detections[:, :4]) + + x = torch.where(iou > self.iou_thres) + if x[0].shape[0]: + matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() + if x[0].shape[0] > 1: + matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 1], return_index=True)[1]] + matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 0], return_index=True)[1]] + else: + matches = np.zeros((0, 3)) + + n = matches.shape[0] > 0 + m0, m1, _ = matches.transpose().astype(int) + for i, gc in enumerate(gt_classes): + j = m0 == i + if n and sum(j) == 1: + self.matrix[detection_classes[m1[j]], gc] += 1 # correct + else: + self.matrix[self.nc, gc] += 1 # background FP + + if n: + for i, dc in enumerate(detection_classes): + if not any(m1 == i): + self.matrix[dc, self.nc] += 1 # background FN + + def matrix(self): + return self.matrix + + def tp_fp(self): + tp = self.matrix.diagonal() # true positives + fp = self.matrix.sum(1) - tp # false positives + # fn = self.matrix.sum(0) - tp # false negatives (missed detections) + return tp[:-1], fp[:-1] # remove background class + + def plot(self, normalize=True, save_dir='', names=()): + try: + import seaborn as sn + + array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1) # normalize columns + array[array < 0.005] = np.nan # don't annotate (would appear as 0.00) + + fig = plt.figure(figsize=(12, 9), tight_layout=True) + nc, nn = self.nc, len(names) # number of classes, names + sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size + labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels + with warnings.catch_warnings(): + warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered + sn.heatmap(array, + annot=nc < 30, + annot_kws={ + "size": 8}, + cmap='Blues', + fmt='.2f', + square=True, + vmin=0.0, + xticklabels=names + ['background FP'] if labels else "auto", + yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1)) + fig.axes[0].set_xlabel('True') + fig.axes[0].set_ylabel('Predicted') + fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250) + plt.close() + except Exception as e: + print(f'WARNING: ConfusionMatrix plot failure: {e}') + + def print(self): + for i in range(self.nc + 1): + print(' '.join(map(str, self.matrix[i]))) + + +def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7): + # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4) + + # Get the coordinates of bounding boxes + if xywh: # transform from xywh to xyxy + (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, 1), box2.chunk(4, 1) + w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2 + b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_ + b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_ + else: # x1, y1, x2, y2 = box1 + b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, 1) + b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, 1) + w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps + w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps + + # Intersection area + inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ + (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) + + # Union Area + union = w1 * h1 + w2 * h2 - inter + eps + + # IoU + iou = inter / union + if CIoU or DIoU or GIoU: + cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width + ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height + if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 + c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared + rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2 + if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 + v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2) + with torch.no_grad(): + alpha = v / (v - iou + (1 + eps)) + return iou - (rho2 / c2 + v * alpha) # CIoU + return iou - rho2 / c2 # DIoU + c_area = cw * ch + eps # convex area + return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf + return iou # IoU + + +def box_area(box): + # box = xyxy(4,n) + return (box[2] - box[0]) * (box[3] - box[1]) + + +def box_iou(box1, box2): + # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py + """ + Return intersection-over-union (Jaccard index) of boxes. + Both sets of boxes are expected to be in (x1, y1, x2, y2) format. + Arguments: + box1 (Tensor[N, 4]) + box2 (Tensor[M, 4]) + Returns: + iou (Tensor[N, M]): the NxM matrix containing the pairwise + IoU values for every element in boxes1 and boxes2 + """ + + # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) + (a1, a2), (b1, b2) = box1[:, None].chunk(2, 2), box2.chunk(2, 1) + inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2) + + # IoU = inter / (area1 + area2 - inter) + return inter / (box_area(box1.T)[:, None] + box_area(box2.T) - inter) + + +def bbox_ioa(box1, box2, eps=1E-7): + """ Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2 + box1: np.array of shape(4) + box2: np.array of shape(nx4) + returns: np.array of shape(n) + """ + + # Get the coordinates of bounding boxes + b1_x1, b1_y1, b1_x2, b1_y2 = box1 + b2_x1, b2_y1, b2_x2, b2_y2 = box2.T + + # Intersection area + inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \ + (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0) + + # box2 area + box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps + + # Intersection over box2 area + return inter_area / box2_area + + +def wh_iou(wh1, wh2): + # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2 + wh1 = wh1[:, None] # [N,1,2] + wh2 = wh2[None] # [1,M,2] + inter = torch.min(wh1, wh2).prod(2) # [N,M] + return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter) + + +# Plots ---------------------------------------------------------------------------------------------------------------- + + +def plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=()): + # Precision-recall curve + fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) + py = np.stack(py, axis=1) + + if 0 < len(names) < 21: # display per-class legend if < 21 classes + for i, y in enumerate(py.T): + ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision) + else: + ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision) + + ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean()) + ax.set_xlabel('Recall') + ax.set_ylabel('Precision') + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") + fig.savefig(save_dir, dpi=250) + plt.close() + + +def plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric'): + # Metric-confidence curve + fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) + + if 0 < len(names) < 21: # display per-class legend if < 21 classes + for i, y in enumerate(py): + ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric) + else: + ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric) + + y = smooth(py.mean(0), 0.05) + ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}') + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") + fig.savefig(save_dir, dpi=250) + plt.close() diff --git a/Y5_20221014/utils/plots.py b/Y5_20221014/utils/plots.py new file mode 100755 index 0000000..1bbb9c0 --- /dev/null +++ b/Y5_20221014/utils/plots.py @@ -0,0 +1,489 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +Plotting utils +""" + +import math +import os +from copy import copy +from pathlib import Path +from urllib.error import URLError + +import cv2 +import matplotlib +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import seaborn as sn +import torch +from PIL import Image, ImageDraw, ImageFont + +from utils.general import (CONFIG_DIR, FONT, LOGGER, Timeout, check_font, check_requirements, clip_coords, + increment_path, is_ascii, threaded, try_except, xywh2xyxy, xyxy2xywh) +from utils.metrics import fitness + +# Settings +RANK = int(os.getenv('RANK', -1)) +matplotlib.rc('font', **{'size': 11}) +matplotlib.use('Agg') # for writing to files only + + +class Colors: + # Ultralytics color palette https://ultralytics.com/ + def __init__(self): + # hex = matplotlib.colors.TABLEAU_COLORS.values() + hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB', + '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7') + self.palette = [self.hex2rgb(f'#{c}') for c in hexs] + self.n = len(self.palette) + + def __call__(self, i, bgr=False): + c = self.palette[int(i) % self.n] + return (c[2], c[1], c[0]) if bgr else c + + @staticmethod + def hex2rgb(h): # rgb order (PIL) + return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4)) + + +colors = Colors() # create instance for 'from utils.plots import colors' + + +def check_pil_font(font=FONT, size=10): + # Return a PIL TrueType Font, downloading to CONFIG_DIR if necessary + font = Path(font) + font = font if font.exists() else (CONFIG_DIR / font.name) + try: + return ImageFont.truetype(str(font) if font.exists() else font.name, size) + except Exception: # download if missing + try: + check_font(font) + return ImageFont.truetype(str(font), size) + except TypeError: + check_requirements('Pillow>=8.4.0') # known issue https://github.com/ultralytics/yolov5/issues/5374 + except URLError: # not online + return ImageFont.load_default() + + +class Annotator: + # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations + def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'): + assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.' + non_ascii = not is_ascii(example) # non-latin labels, i.e. asian, arabic, cyrillic + self.pil = pil or non_ascii + if self.pil: # use PIL + self.im = im if isinstance(im, Image.Image) else Image.fromarray(im) + self.draw = ImageDraw.Draw(self.im) + self.font = check_pil_font(font='Arial.Unicode.ttf' if non_ascii else font, + size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12)) + else: # use cv2 + self.im = im + self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width + + def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)): + # Add one xyxy box to image with label + if self.pil or not is_ascii(label): + self.draw.rectangle(box, width=self.lw, outline=color) # box + if label: + w, h = self.font.getsize(label) # text width, height + outside = box[1] - h >= 0 # label fits outside box + self.draw.rectangle( + (box[0], box[1] - h if outside else box[1], box[0] + w + 1, + box[1] + 1 if outside else box[1] + h + 1), + fill=color, + ) + # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0 + self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font) + else: # cv2 + p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3])) + cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA) + if label: + tf = max(self.lw - 1, 1) # font thickness + w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0] # text width, height + outside = p1[1] - h >= 3 + p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3 + cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled + cv2.putText(self.im, + label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2), + 0, + self.lw / 3, + txt_color, + thickness=tf, + lineType=cv2.LINE_AA) + + def rectangle(self, xy, fill=None, outline=None, width=1): + # Add rectangle to image (PIL-only) + self.draw.rectangle(xy, fill, outline, width) + + def text(self, xy, text, txt_color=(255, 255, 255)): + # Add text to image (PIL-only) + w, h = self.font.getsize(text) # text width, height + self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font) + + def result(self): + # Return annotated image as array + return np.asarray(self.im) + + +def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')): + """ + x: Features to be visualized + module_type: Module type + stage: Module stage within model + n: Maximum number of feature maps to plot + save_dir: Directory to save results + """ + if 'Detect' not in module_type: + batch, channels, height, width = x.shape # batch, channels, height, width + if height > 1 and width > 1: + f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename + + blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels + n = min(n, channels) # number of plots + fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols + ax = ax.ravel() + plt.subplots_adjust(wspace=0.05, hspace=0.05) + for i in range(n): + ax[i].imshow(blocks[i].squeeze()) # cmap='gray' + ax[i].axis('off') + + LOGGER.info(f'Saving {f}... ({n}/{channels})') + plt.savefig(f, dpi=300, bbox_inches='tight') + plt.close() + np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy()) # npy save + + +def hist2d(x, y, n=100): + # 2d histogram used in labels.png and evolve.png + xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n) + hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges)) + xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1) + yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1) + return np.log(hist[xidx, yidx]) + + +def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5): + from scipy.signal import butter, filtfilt + + # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy + def butter_lowpass(cutoff, fs, order): + nyq = 0.5 * fs + normal_cutoff = cutoff / nyq + return butter(order, normal_cutoff, btype='low', analog=False) + + b, a = butter_lowpass(cutoff, fs, order=order) + return filtfilt(b, a, data) # forward-backward filter + + +def output_to_target(output): + # Convert model output to target format [batch_id, class_id, x, y, w, h, conf] + targets = [] + for i, o in enumerate(output): + for *box, conf, cls in o.cpu().numpy(): + targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf]) + return np.array(targets) + + +@threaded +def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=1920, max_subplots=16): + # Plot image grid with labels + if isinstance(images, torch.Tensor): + images = images.cpu().float().numpy() + if isinstance(targets, torch.Tensor): + targets = targets.cpu().numpy() + if np.max(images[0]) <= 1: + images *= 255 # de-normalise (optional) + bs, _, h, w = images.shape # batch size, _, height, width + bs = min(bs, max_subplots) # limit plot images + ns = np.ceil(bs ** 0.5) # number of subplots (square) + + # Build Image + mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init + for i, im in enumerate(images): + if i == max_subplots: # if last batch has fewer images than we expect + break + x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin + im = im.transpose(1, 2, 0) + mosaic[y:y + h, x:x + w, :] = im + + # Resize (optional) + scale = max_size / ns / max(h, w) + if scale < 1: + h = math.ceil(scale * h) + w = math.ceil(scale * w) + mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h))) + + # Annotate + fs = int((h + w) * ns * 0.01) # font size + annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names) + for i in range(i + 1): + x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin + annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders + if paths: + annotator.text((x + 5, y + 5 + h), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames + if len(targets) > 0: + ti = targets[targets[:, 0] == i] # image targets + boxes = xywh2xyxy(ti[:, 2:6]).T + classes = ti[:, 1].astype('int') + labels = ti.shape[1] == 6 # labels if no conf column + conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred) + + if boxes.shape[1]: + if boxes.max() <= 1.01: # if normalized with tolerance 0.01 + boxes[[0, 2]] *= w # scale to pixels + boxes[[1, 3]] *= h + elif scale < 1: # absolute coords need scale if image scales + boxes *= scale + boxes[[0, 2]] += x + boxes[[1, 3]] += y + for j, box in enumerate(boxes.T.tolist()): + cls = classes[j] + color = colors(cls) + cls = names[cls] if names else cls + if labels or conf[j] > 0.25: # 0.25 conf thresh + label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}' + annotator.box_label(box, label, color=color) + annotator.im.save(fname) # save + + +def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''): + # Plot LR simulating training for full epochs + optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals + y = [] + for _ in range(epochs): + scheduler.step() + y.append(optimizer.param_groups[0]['lr']) + plt.plot(y, '.-', label='LR') + plt.xlabel('epoch') + plt.ylabel('LR') + plt.grid() + plt.xlim(0, epochs) + plt.ylim(0) + plt.savefig(Path(save_dir) / 'LR.png', dpi=200) + plt.close() + + +def plot_val_txt(): # from utils.plots import *; plot_val() + # Plot val.txt histograms + x = np.loadtxt('val.txt', dtype=np.float32) + box = xyxy2xywh(x[:, :4]) + cx, cy = box[:, 0], box[:, 1] + + fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True) + ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0) + ax.set_aspect('equal') + plt.savefig('hist2d.png', dpi=300) + + fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True) + ax[0].hist(cx, bins=600) + ax[1].hist(cy, bins=600) + plt.savefig('hist1d.png', dpi=200) + + +def plot_targets_txt(): # from utils.plots import *; plot_targets_txt() + # Plot targets.txt histograms + x = np.loadtxt('targets.txt', dtype=np.float32).T + s = ['x targets', 'y targets', 'width targets', 'height targets'] + fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True) + ax = ax.ravel() + for i in range(4): + ax[i].hist(x[i], bins=100, label=f'{x[i].mean():.3g} +/- {x[i].std():.3g}') + ax[i].legend() + ax[i].set_title(s[i]) + plt.savefig('targets.jpg', dpi=200) + + +def plot_val_study(file='', dir='', x=None): # from utils.plots import *; plot_val_study() + # Plot file=study.txt generated by val.py (or plot all study*.txt in dir) + save_dir = Path(file).parent if file else Path(dir) + plot2 = False # plot additional results + if plot2: + ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel() + + fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True) + # for f in [save_dir / f'study_coco_{x}.txt' for x in ['yolov5n6', 'yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]: + for f in sorted(save_dir.glob('study*.txt')): + y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T + x = np.arange(y.shape[1]) if x is None else np.array(x) + if plot2: + s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)'] + for i in range(7): + ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8) + ax[i].set_title(s[i]) + + j = y[3].argmax() + 1 + ax2.plot(y[5, 1:j], + y[3, 1:j] * 1E2, + '.-', + linewidth=2, + markersize=8, + label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO')) + + ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5], + 'k.-', + linewidth=2, + markersize=8, + alpha=.25, + label='EfficientDet') + + ax2.grid(alpha=0.2) + ax2.set_yticks(np.arange(20, 60, 5)) + ax2.set_xlim(0, 57) + ax2.set_ylim(25, 55) + ax2.set_xlabel('GPU Speed (ms/img)') + ax2.set_ylabel('COCO AP val') + ax2.legend(loc='lower right') + f = save_dir / 'study.png' + print(f'Saving {f}...') + plt.savefig(f, dpi=300) + + +@try_except # known issue https://github.com/ultralytics/yolov5/issues/5395 +@Timeout(30) # known issue https://github.com/ultralytics/yolov5/issues/5611 +def plot_labels(labels, names=(), save_dir=Path('')): + # plot dataset labels + LOGGER.info(f"Plotting labels to {save_dir / 'labels.jpg'}... ") + c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes + nc = int(c.max() + 1) # number of classes + x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height']) + + # seaborn correlogram + sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9)) + plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200) + plt.close() + + # matplotlib labels + matplotlib.use('svg') # faster + ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel() + y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) + try: # color histogram bars by class + [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # known issue #3195 + except Exception: + pass + ax[0].set_ylabel('instances') + if 0 < len(names) < 30: + ax[0].set_xticks(range(len(names))) + ax[0].set_xticklabels(names, rotation=90, fontsize=10) + else: + ax[0].set_xlabel('classes') + sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9) + sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9) + + # rectangles + labels[:, 1:3] = 0.5 # center + labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000 + img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255) + for cls, *box in labels[:1000]: + ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot + ax[1].imshow(img) + ax[1].axis('off') + + for a in [0, 1, 2, 3]: + for s in ['top', 'right', 'left', 'bottom']: + ax[a].spines[s].set_visible(False) + + plt.savefig(save_dir / 'labels.jpg', dpi=200) + matplotlib.use('Agg') + plt.close() + + +def plot_evolve(evolve_csv='path/to/evolve.csv'): # from utils.plots import *; plot_evolve() + # Plot evolve.csv hyp evolution results + evolve_csv = Path(evolve_csv) + data = pd.read_csv(evolve_csv) + keys = [x.strip() for x in data.columns] + x = data.values + f = fitness(x) + j = np.argmax(f) # max fitness index + plt.figure(figsize=(10, 12), tight_layout=True) + matplotlib.rc('font', **{'size': 8}) + print(f'Best results from row {j} of {evolve_csv}:') + for i, k in enumerate(keys[7:]): + v = x[:, 7 + i] + mu = v[j] # best single result + plt.subplot(6, 5, i + 1) + plt.scatter(v, f, c=hist2d(v, f, 20), cmap='viridis', alpha=.8, edgecolors='none') + plt.plot(mu, f.max(), 'k+', markersize=15) + plt.title(f'{k} = {mu:.3g}', fontdict={'size': 9}) # limit to 40 characters + if i % 5 != 0: + plt.yticks([]) + print(f'{k:>15}: {mu:.3g}') + f = evolve_csv.with_suffix('.png') # filename + plt.savefig(f, dpi=200) + plt.close() + print(f'Saved {f}') + + +def plot_results(file='path/to/results.csv', dir=''): + # Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv') + save_dir = Path(file).parent if file else Path(dir) + fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True) + ax = ax.ravel() + files = list(save_dir.glob('results*.csv')) + assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.' + for f in files: + try: + data = pd.read_csv(f) + s = [x.strip() for x in data.columns] + x = data.values[:, 0] + for i, j in enumerate([1, 2, 3, 4, 5, 8, 9, 10, 6, 7]): + y = data.values[:, j].astype('float') + # y[y == 0] = np.nan # don't show zero values + ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8) + ax[i].set_title(s[j], fontsize=12) + # if j in [8, 9, 10]: # share train and val loss y axes + # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5]) + except Exception as e: + LOGGER.info(f'Warning: Plotting error for {f}: {e}') + ax[1].legend() + fig.savefig(save_dir / 'results.png', dpi=200) + plt.close() + + +def profile_idetection(start=0, stop=0, labels=(), save_dir=''): + # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection() + ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel() + s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS'] + files = list(Path(save_dir).glob('frames*.txt')) + for fi, f in enumerate(files): + try: + results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows + n = results.shape[1] # number of rows + x = np.arange(start, min(stop, n) if stop else n) + results = results[:, x] + t = (results[0] - results[0].min()) # set t0=0s + results[0] = x + for i, a in enumerate(ax): + if i < len(results): + label = labels[fi] if len(labels) else f.stem.replace('frames_', '') + a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5) + a.set_title(s[i]) + a.set_xlabel('time (s)') + # if fi == len(files) - 1: + # a.set_ylim(bottom=0) + for side in ['top', 'right']: + a.spines[side].set_visible(False) + else: + a.remove() + except Exception as e: + print(f'Warning: Plotting error for {f}; {e}') + ax[1].legend() + plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200) + + +def save_one_box(xyxy, im, file=Path('im.jpg'), gain=1.02, pad=10, square=False, BGR=False, save=True): + # Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop + xyxy = torch.tensor(xyxy).view(-1, 4) + b = xyxy2xywh(xyxy) # boxes + if square: + b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square + b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad + xyxy = xywh2xyxy(b).long() + clip_coords(xyxy, im.shape) + crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)] + if save: + file.parent.mkdir(parents=True, exist_ok=True) # make directory + f = str(increment_path(file).with_suffix('.jpg')) + # cv2.imwrite(f, crop) # https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue + Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)).save(f, quality=95, subsampling=0) + return crop diff --git a/Y5_20221014/utils/torch_utils.py b/Y5_20221014/utils/torch_utils.py new file mode 100755 index 0000000..d11df83 --- /dev/null +++ b/Y5_20221014/utils/torch_utils.py @@ -0,0 +1,314 @@ +# YOLOv5 🚀 by Ultralytics, GPL-3.0 license +""" +PyTorch utils +""" + +import math +import os +import platform +import subprocess +import time +import warnings +from contextlib import contextmanager +from copy import deepcopy +from pathlib import Path + +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.nn.functional as F + +from utils.general import LOGGER, file_date, git_describe + +try: + import thop # for FLOPs computation +except ImportError: + thop = None + +# Suppress PyTorch warnings +warnings.filterwarnings('ignore', message='User provided device_type of \'cuda\', but CUDA is not available. Disabling') + + +@contextmanager +def torch_distributed_zero_first(local_rank: int): + # Decorator to make all processes in distributed training wait for each local_master to do something + if local_rank not in [-1, 0]: + dist.barrier(device_ids=[local_rank]) + yield + if local_rank == 0: + dist.barrier(device_ids=[0]) + + +def device_count(): + # Returns number of CUDA devices available. Safe version of torch.cuda.device_count(). Supports Linux and Windows + assert platform.system() in ('Linux', 'Windows'), 'device_count() only supported on Linux or Windows' + try: + cmd = 'nvidia-smi -L | wc -l' if platform.system() == 'Linux' else 'nvidia-smi -L | find /c /v ""' # Windows + return int(subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]) + except Exception: + return 0 + + +def select_device(device='', batch_size=0, newline=True): + # device = None or 'cpu' or 0 or '0' or '0,1,2,3' + s = f'YOLOv5 🚀 {git_describe() or file_date()} Python-{platform.python_version()} torch-{torch.__version__} ' + device = str(device).strip().lower().replace('cuda:', '').replace('none', '') # to string, 'cuda:0' to '0' + cpu = device == 'cpu' + mps = device == 'mps' # Apple Metal Performance Shaders (MPS) + if cpu or mps: + os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False + elif device: # non-cpu device requested + os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable - must be before assert is_available() + assert torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', '')), \ + f"Invalid CUDA '--device {device}' requested, use '--device cpu' or pass valid CUDA device(s)" + + cuda = not cpu and torch.cuda.is_available() + if cuda: + devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7 + n = len(devices) # device count + if n > 1 and batch_size > 0: # check batch_size is divisible by device_count + assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}' + space = ' ' * (len(s) + 1) + for i, d in enumerate(devices): + p = torch.cuda.get_device_properties(i) + s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\n" # bytes to MB + elif mps: + s += 'MPS\n' + else: + s += 'CPU\n' + + if not newline: + s = s.rstrip() + LOGGER.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe + return torch.device('cuda:0' if cuda else 'mps' if mps else 'cpu') + + +def time_sync(): + # PyTorch-accurate time + if torch.cuda.is_available(): + torch.cuda.synchronize() + return time.time() + + +def profile(input, ops, n=10, device=None): + # YOLOv5 speed/memory/FLOPs profiler + # + # Usage: + # input = torch.randn(16, 3, 640, 640) + # m1 = lambda x: x * torch.sigmoid(x) + # m2 = nn.SiLU() + # profile(input, [m1, m2], n=100) # profile over 100 iterations + + results = [] + if not isinstance(device, torch.device): + device = select_device(device) + print(f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}" + f"{'input':>24s}{'output':>24s}") + + for x in input if isinstance(input, list) else [input]: + x = x.to(device) + x.requires_grad = True + for m in ops if isinstance(ops, list) else [ops]: + m = m.to(device) if hasattr(m, 'to') else m # device + m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m + tf, tb, t = 0, 0, [0, 0, 0] # dt forward, backward + try: + flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs + except Exception: + flops = 0 + + try: + for _ in range(n): + t[0] = time_sync() + y = m(x) + t[1] = time_sync() + try: + _ = (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward() + t[2] = time_sync() + except Exception: # no backward method + # print(e) # for debug + t[2] = float('nan') + tf += (t[1] - t[0]) * 1000 / n # ms per op forward + tb += (t[2] - t[1]) * 1000 / n # ms per op backward + mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0 # (GB) + s_in, s_out = (tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' for x in (x, y)) # shapes + p = sum(x.numel() for x in m.parameters()) if isinstance(m, nn.Module) else 0 # parameters + print(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}') + results.append([p, flops, mem, tf, tb, s_in, s_out]) + except Exception as e: + print(e) + results.append(None) + torch.cuda.empty_cache() + return results + + +def is_parallel(model): + # Returns True if model is of type DP or DDP + return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) + + +def de_parallel(model): + # De-parallelize a model: returns single-GPU model if model is of type DP or DDP + return model.module if is_parallel(model) else model + + +def initialize_weights(model): + for m in model.modules(): + t = type(m) + if t is nn.Conv2d: + pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + elif t is nn.BatchNorm2d: + m.eps = 1e-3 + m.momentum = 0.03 + elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]: + m.inplace = True + + +def find_modules(model, mclass=nn.Conv2d): + # Finds layer indices matching module class 'mclass' + return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)] + + +def sparsity(model): + # Return global model sparsity + a, b = 0, 0 + for p in model.parameters(): + a += p.numel() + b += (p == 0).sum() + return b / a + + +def prune(model, amount=0.3): + # Prune model to requested global sparsity + import torch.nn.utils.prune as prune + print('Pruning model... ', end='') + for name, m in model.named_modules(): + if isinstance(m, nn.Conv2d): + prune.l1_unstructured(m, name='weight', amount=amount) # prune + prune.remove(m, 'weight') # make permanent + print(' %.3g global sparsity' % sparsity(model)) + + +def fuse_conv_and_bn(conv, bn): + # Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ + fusedconv = nn.Conv2d(conv.in_channels, + conv.out_channels, + kernel_size=conv.kernel_size, + stride=conv.stride, + padding=conv.padding, + groups=conv.groups, + bias=True).requires_grad_(False).to(conv.weight.device) + + # Prepare filters + w_conv = conv.weight.clone().view(conv.out_channels, -1) + w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) + fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape)) + + # Prepare spatial bias + b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias + b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) + fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) + + return fusedconv + + +def model_info(model, verbose=False, img_size=640): + # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320] + n_p = sum(x.numel() for x in model.parameters()) # number parameters + n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients + if verbose: + print(f"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}") + for i, (name, p) in enumerate(model.named_parameters()): + name = name.replace('module_list.', '') + print('%5g %40s %9s %12g %20s %10.3g %10.3g' % + (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) + + try: # FLOPs + from thop import profile + stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32 + img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input + flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPs + img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float + fs = ', %.1f GFLOPs' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPs + except Exception: + fs = '' + + name = Path(model.yaml_file).stem.replace('yolov5', 'YOLOv5') if hasattr(model, 'yaml_file') else 'Model' + LOGGER.info(f"{name} summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}") + + +def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) + # Scales img(bs,3,y,x) by ratio constrained to gs-multiple + if ratio == 1.0: + return img + h, w = img.shape[2:] + s = (int(h * ratio), int(w * ratio)) # new size + img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize + if not same_shape: # pad/crop img + h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w)) + return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean + + +def copy_attr(a, b, include=(), exclude=()): + # Copy attributes from b to a, options to only include [...] and to exclude [...] + for k, v in b.__dict__.items(): + if (len(include) and k not in include) or k.startswith('_') or k in exclude: + continue + else: + setattr(a, k, v) + + +class EarlyStopping: + # YOLOv5 simple early stopper + def __init__(self, patience=30): + self.best_fitness = 0.0 # i.e. mAP + self.best_epoch = 0 + self.patience = patience or float('inf') # epochs to wait after fitness stops improving to stop + self.possible_stop = False # possible stop may occur next epoch + + def __call__(self, epoch, fitness): + if fitness >= self.best_fitness: # >= 0 to allow for early zero-fitness stage of training + self.best_epoch = epoch + self.best_fitness = fitness + delta = epoch - self.best_epoch # epochs without improvement + self.possible_stop = delta >= (self.patience - 1) # possible stop may occur next epoch + stop = delta >= self.patience # stop training if patience exceeded + if stop: + LOGGER.info(f'Stopping training early as no improvement observed in last {self.patience} epochs. ' + f'Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\n' + f'To update EarlyStopping(patience={self.patience}) pass a new patience value, ' + f'i.e. `python train.py --patience 300` or use `--patience 0` to disable EarlyStopping.') + return stop + + +class ModelEMA: + """ Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models + Keeps a moving average of everything in the model state_dict (parameters and buffers) + For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage + """ + + def __init__(self, model, decay=0.9999, tau=2000, updates=0): + # Create EMA + self.ema = deepcopy(de_parallel(model)).eval() # FP32 EMA + # if next(model.parameters()).device.type != 'cpu': + # self.ema.half() # FP16 EMA + self.updates = updates # number of EMA updates + self.decay = lambda x: decay * (1 - math.exp(-x / tau)) # decay exponential ramp (to help early epochs) + for p in self.ema.parameters(): + p.requires_grad_(False) + + def update(self, model): + # Update EMA parameters + with torch.no_grad(): + self.updates += 1 + d = self.decay(self.updates) + + msd = de_parallel(model).state_dict() # model state_dict + for k, v in self.ema.state_dict().items(): + if v.dtype.is_floating_point: + v *= d + v += (1 - d) * msd[k].detach() + + def update_attr(self, model, include=(), exclude=('process_group', 'reducer')): + # Update EMA attributes + copy_attr(self.ema, model, include, exclude) diff --git a/Y5/data/argoverse_hd.yaml b/Y5_old/data/argoverse_hd.yaml similarity index 100% rename from Y5/data/argoverse_hd.yaml rename to Y5_old/data/argoverse_hd.yaml diff --git a/Y5/data/coco.yaml b/Y5_old/data/coco.yaml similarity index 100% rename from Y5/data/coco.yaml rename to Y5_old/data/coco.yaml diff --git a/Y5/data/coco128.yaml b/Y5_old/data/coco128.yaml similarity index 100% rename from Y5/data/coco128.yaml rename to Y5_old/data/coco128.yaml diff --git a/Y5/data/hyp.finetune.yaml b/Y5_old/data/hyp.finetune.yaml similarity index 100% rename from Y5/data/hyp.finetune.yaml rename to Y5_old/data/hyp.finetune.yaml diff --git a/Y5/data/hyp.scratch.yaml b/Y5_old/data/hyp.scratch.yaml similarity index 100% rename from Y5/data/hyp.scratch.yaml rename to Y5_old/data/hyp.scratch.yaml diff --git a/Y5/data/images/bus.jpg b/Y5_old/data/images/bus.jpg similarity index 100% rename from Y5/data/images/bus.jpg rename to Y5_old/data/images/bus.jpg diff --git a/Y5_old/data/images/zidane.jpg b/Y5_old/data/images/zidane.jpg new file mode 100755 index 0000000..92d72ea Binary files /dev/null and b/Y5_old/data/images/zidane.jpg differ diff --git a/Y5/data/scripts/get_argoverse_hd.sh b/Y5_old/data/scripts/get_argoverse_hd.sh similarity index 100% rename from Y5/data/scripts/get_argoverse_hd.sh rename to Y5_old/data/scripts/get_argoverse_hd.sh diff --git a/Y5/data/scripts/get_coco.sh b/Y5_old/data/scripts/get_coco.sh similarity index 100% rename from Y5/data/scripts/get_coco.sh rename to Y5_old/data/scripts/get_coco.sh diff --git a/Y5/data/scripts/get_voc.sh b/Y5_old/data/scripts/get_voc.sh similarity index 100% rename from Y5/data/scripts/get_voc.sh rename to Y5_old/data/scripts/get_voc.sh diff --git a/Y5/data/voc.yaml b/Y5_old/data/voc.yaml similarity index 100% rename from Y5/data/voc.yaml rename to Y5_old/data/voc.yaml diff --git a/Y5_old/models/__init__.py b/Y5_old/models/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/Y5_old/models/__pycache__/__init__.cpython-36.pyc b/Y5_old/models/__pycache__/__init__.cpython-36.pyc new file mode 100755 index 0000000..e659606 Binary files /dev/null and b/Y5_old/models/__pycache__/__init__.cpython-36.pyc differ diff --git a/Y5_old/models/__pycache__/common.cpython-36.pyc b/Y5_old/models/__pycache__/common.cpython-36.pyc new file mode 100755 index 0000000..b20ee6d Binary files /dev/null and b/Y5_old/models/__pycache__/common.cpython-36.pyc differ diff --git a/Y5_old/models/__pycache__/experimental.cpython-36.pyc b/Y5_old/models/__pycache__/experimental.cpython-36.pyc new file mode 100755 index 0000000..fb1fb20 Binary files /dev/null and b/Y5_old/models/__pycache__/experimental.cpython-36.pyc differ diff --git a/Y5_old/models/__pycache__/yolo.cpython-36.pyc b/Y5_old/models/__pycache__/yolo.cpython-36.pyc new file mode 100755 index 0000000..e7b9a74 Binary files /dev/null and b/Y5_old/models/__pycache__/yolo.cpython-36.pyc differ diff --git a/Y5_old/models/common.py b/Y5_old/models/common.py new file mode 100755 index 0000000..5464691 --- /dev/null +++ b/Y5_old/models/common.py @@ -0,0 +1,309 @@ +# This file contains modules common to various models + +import math +from pathlib import Path +import sys +sys.path.append("..") +import numpy as np +import requests +import torch +import torch.nn as nn +from PIL import Image + +from Y5.utils.datasets import letterbox +from Y5.utils.general import non_max_suppression, make_divisible, scale_coords, xyxy2xywh +from Y5.utils.plots import color_list, plot_one_box + + +def autopad(k, p=None): # kernel, padding + # Pad to 'same' + if p is None: + p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad + return p + + +def DWConv(c1, c2, k=1, s=1, act=True): + # Depthwise convolution + return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act) + + +class Conv(nn.Module): + # Standard convolution + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super(Conv, self).__init__() + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False) + self.bn = nn.BatchNorm2d(c2) + self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity()) + + def forward(self, x): + return self.act(self.bn(self.conv(x))) + + def fuseforward(self, x): + return self.act(self.conv(x)) + + +class Bottleneck(nn.Module): + # Standard bottleneck + def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion + super(Bottleneck, self).__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_, c2, 3, 1, g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x): + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) + + +class BottleneckCSP(nn.Module): + # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion + super(BottleneckCSP, self).__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) + self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) + self.cv4 = Conv(2 * c_, c2, 1, 1) + self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) + self.act = nn.LeakyReLU(0.1, inplace=True) + self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) + + def forward(self, x): + y1 = self.cv3(self.m(self.cv1(x))) + y2 = self.cv2(x) + return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1)))) + + +class C3(nn.Module): + # CSP Bottleneck with 3 convolutions + def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion + super(C3, self).__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c1, c_, 1, 1) + self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2) + self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) + # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)]) + + def forward(self, x): + return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1)) + + +class SPP(nn.Module): + # Spatial pyramid pooling layer used in YOLOv3-SPP + def __init__(self, c1, c2, k=(5, 9, 13)): + super(SPP, self).__init__() + c_ = c1 // 2 # hidden channels + self.cv1 = Conv(c1, c_, 1, 1) + self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) + self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) + + def forward(self, x): + x = self.cv1(x) + return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) + + +class Focus(nn.Module): + # Focus wh information into c-space + def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups + super(Focus, self).__init__() + self.conv = Conv(c1 * 4, c2, k, s, p, g, act) + # self.contract = Contract(gain=2) + + def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) + return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)) + # return self.conv(self.contract(x)) + + +class Contract(nn.Module): + # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40) + def __init__(self, gain=2): + super().__init__() + self.gain = gain + + def forward(self, x): + N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain' + s = self.gain + x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2) + x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40) + return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40) + + +class Expand(nn.Module): + # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160) + def __init__(self, gain=2): + super().__init__() + self.gain = gain + + def forward(self, x): + N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain' + s = self.gain + x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80) + x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2) + return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160) + + +class Concat(nn.Module): + # Concatenate a list of tensors along dimension + def __init__(self, dimension=1): + super(Concat, self).__init__() + self.d = dimension + + def forward(self, x): + return torch.cat(x, self.d) + + +class NMS(nn.Module): + # Non-Maximum Suppression (NMS) module + conf = 0.25 # confidence threshold + iou = 0.45 # IoU threshold + classes = None # (optional list) filter by class + + def __init__(self): + super(NMS, self).__init__() + + def forward(self, x): + return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) + + +class autoShape(nn.Module): + # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS + img_size = 640 # inference size (pixels) + conf = 0.25 # NMS confidence threshold + iou = 0.45 # NMS IoU threshold + classes = None # (optional list) filter by class + + def __init__(self, model): + super(autoShape, self).__init__() + self.model = model.eval() + + def autoshape(self): + print('autoShape already enabled, skipping... ') # model already converted to model.autoshape() + return self + + def forward(self, imgs, size=640, augment=False, profile=False): + # Inference from various sources. For height=720, width=1280, RGB images example inputs are: + # filename: imgs = 'data/samples/zidane.jpg' + # URI: = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg' + # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(720,1280,3) + # PIL: = Image.open('image.jpg') # HWC x(720,1280,3) + # numpy: = np.zeros((720,1280,3)) # HWC + # torch: = torch.zeros(16,3,720,1280) # BCHW + # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images + + p = next(self.model.parameters()) # for device and type + if isinstance(imgs, torch.Tensor): # torch + return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference + + # Pre-process + n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images + shape0, shape1, files = [], [], [] # image and inference shapes, filenames + for i, im in enumerate(imgs): + if isinstance(im, str): # filename or uri + im, f = Image.open(requests.get(im, stream=True).raw if im.startswith('http') else im), im # open + im.filename = f # for uri + files.append(Path(im.filename).with_suffix('.jpg').name if isinstance(im, Image.Image) else f'image{i}.jpg') + im = np.array(im) # to numpy + if im.shape[0] < 5: # image in CHW + im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1) + im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input + s = im.shape[:2] # HWC + shape0.append(s) # image shape + g = (size / max(s)) # gain + shape1.append([y * g for y in s]) + imgs[i] = im # update + shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape + x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad + x = np.stack(x, 0) if n > 1 else x[0][None] # stack + x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW + x = torch.from_numpy(x).to(p.device).type_as(p) / 255. # uint8 to fp16/32 + + # Inference + with torch.no_grad(): + y = self.model(x, augment, profile)[0] # forward + y = non_max_suppression(y, conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) # NMS + + # Post-process + for i in range(n): + scale_coords(shape1, y[i][:, :4], shape0[i]) + + return Detections(imgs, y, files, self.names) + + +class Detections: + # detections class for YOLOv5 inference results + def __init__(self, imgs, pred, files, names=None): + super(Detections, self).__init__() + d = pred[0].device # device + gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs] # normalizations + self.imgs = imgs # list of images as numpy arrays + self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls) + self.names = names # class names + self.files = files # image filenames + self.xyxy = pred # xyxy pixels + self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels + self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized + self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized + self.n = len(self.pred) + + def display(self, pprint=False, show=False, save=False, render=False, save_dir=''): + colors = color_list() + for i, (img, pred) in enumerate(zip(self.imgs, self.pred)): + str = f'image {i + 1}/{len(self.pred)}: {img.shape[0]}x{img.shape[1]} ' + if pred is not None: + for c in pred[:, -1].unique(): + n = (pred[:, -1] == c).sum() # detections per class + str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string + if show or save or render: + for *box, conf, cls in pred: # xyxy, confidence, class + label = f'{self.names[int(cls)]} {conf:.2f}' + plot_one_box(box, img, label=label, color=colors[int(cls) % 10]) + img = Image.fromarray(img.astype(np.uint8)) if isinstance(img, np.ndarray) else img # from np + if pprint: + print(str.rstrip(', ')) + if show: + img.show(self.files[i]) # show + if save: + f = Path(save_dir) / self.files[i] + img.save(f) # save + print(f"{'Saving' * (i == 0)} {f},", end='' if i < self.n - 1 else ' done.\n') + if render: + self.imgs[i] = np.asarray(img) + + def print(self): + self.display(pprint=True) # print results + + def show(self): + self.display(show=True) # show results + + def save(self, save_dir='results/'): + Path(save_dir).mkdir(exist_ok=True) + self.display(save=True, save_dir=save_dir) # save results + + def render(self): + self.display(render=True) # render results + return self.imgs + + def __len__(self): + return self.n + + def tolist(self): + # return a list of Detections objects, i.e. 'for result in results.tolist():' + x = [Detections([self.imgs[i]], [self.pred[i]], self.names) for i in range(self.n)] + for d in x: + for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']: + setattr(d, k, getattr(d, k)[0]) # pop out of list + return x + + +class Classify(nn.Module): + # Classification head, i.e. x(b,c1,20,20) to x(b,c2) + def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups + super(Classify, self).__init__() + self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1) + self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1) + self.flat = nn.Flatten() + + def forward(self, x): + z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list + return self.flat(self.conv(z)) # flatten to x(b,c2) diff --git a/Y5_old/models/experimental.py b/Y5_old/models/experimental.py new file mode 100755 index 0000000..a818590 --- /dev/null +++ b/Y5_old/models/experimental.py @@ -0,0 +1,135 @@ +# This file contains experimental modules + +import numpy as np +import torch +import torch.nn as nn + + +from Y5.models.common import Conv, DWConv +from Y5.utils.google_utils import attempt_download + + +class CrossConv(nn.Module): + # Cross Convolution Downsample + def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): + # ch_in, ch_out, kernel, stride, groups, expansion, shortcut + super(CrossConv, self).__init__() + c_ = int(c2 * e) # hidden channels + self.cv1 = Conv(c1, c_, (1, k), (1, s)) + self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) + self.add = shortcut and c1 == c2 + + def forward(self, x): + return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) + + +class Sum(nn.Module): + # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 + def __init__(self, n, weight=False): # n: number of inputs + super(Sum, self).__init__() + self.weight = weight # apply weights boolean + self.iter = range(n - 1) # iter object + if weight: + self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights + + def forward(self, x): + y = x[0] # no weight + if self.weight: + w = torch.sigmoid(self.w) * 2 + for i in self.iter: + y = y + x[i + 1] * w[i] + else: + for i in self.iter: + y = y + x[i + 1] + return y + + +class GhostConv(nn.Module): + # Ghost Convolution https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups + super(GhostConv, self).__init__() + c_ = c2 // 2 # hidden channels + self.cv1 = Conv(c1, c_, k, s, None, g, act) + self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) + + def forward(self, x): + y = self.cv1(x) + return torch.cat([y, self.cv2(y)], 1) + + +class GhostBottleneck(nn.Module): + # Ghost Bottleneck https://github.com/huawei-noah/ghostnet + def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride + super(GhostBottleneck, self).__init__() + c_ = c2 // 2 + self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw + DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw + GhostConv(c_, c2, 1, 1, act=False)) # pw-linear + self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), + Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() + + def forward(self, x): + return self.conv(x) + self.shortcut(x) + + +class MixConv2d(nn.Module): + # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595 + def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): + super(MixConv2d, self).__init__() + groups = len(k) + if equal_ch: # equal c_ per group + i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices + c_ = [(i == g).sum() for g in range(groups)] # intermediate channels + else: # equal weight.numel() per group + b = [c2] + [0] * groups + a = np.eye(groups + 1, groups, k=-1) + a -= np.roll(a, 1, axis=1) + a *= np.array(k) ** 2 + a[0] = 1 + c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b + + self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)]) + self.bn = nn.BatchNorm2d(c2) + self.act = nn.LeakyReLU(0.1, inplace=True) + + def forward(self, x): + return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) + + +class Ensemble(nn.ModuleList): + # Ensemble of models + def __init__(self): + super(Ensemble, self).__init__() + + def forward(self, x, augment=False): + y = [] + for module in self: + y.append(module(x, augment)[0]) + # y = torch.stack(y).max(0)[0] # max ensemble + # y = torch.stack(y).mean(0) # mean ensemble + y = torch.cat(y, 1) # nms ensemble + return y, None # inference, train output + + +def attempt_load(weights, map_location=None): + # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a + model = Ensemble() + for w in weights if isinstance(weights, list) else [weights]: + attempt_download(w) + ckpt = torch.load(w, map_location=map_location) # load + model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model + + # Compatibility updates + for m in model.modules(): + if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]: + m.inplace = True # pytorch 1.7.0 compatibility + elif type(m) is Conv: + m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility + + if len(model) == 1: + return model[-1] # return model + else: + print('Ensemble created with %s\n' % weights) + for k in ['names', 'stride']: + setattr(model, k, getattr(model[-1], k)) + return model # return ensemble diff --git a/Y5/models/export.py b/Y5_old/models/export.py similarity index 100% rename from Y5/models/export.py rename to Y5_old/models/export.py diff --git a/Y5_old/models/hub/anchors.yaml b/Y5_old/models/hub/anchors.yaml new file mode 100755 index 0000000..a07a4dc --- /dev/null +++ b/Y5_old/models/hub/anchors.yaml @@ -0,0 +1,58 @@ +# Default YOLOv5 anchors for COCO data + + +# P5 ------------------------------------------------------------------------------------------------------------------- +# P5-640: +anchors_p5_640: + - [ 10,13, 16,30, 33,23 ] # P3/8 + - [ 30,61, 62,45, 59,119 ] # P4/16 + - [ 116,90, 156,198, 373,326 ] # P5/32 + + +# P6 ------------------------------------------------------------------------------------------------------------------- +# P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387 +anchors_p6_640: + - [ 9,11, 21,19, 17,41 ] # P3/8 + - [ 43,32, 39,70, 86,64 ] # P4/16 + - [ 65,131, 134,130, 120,265 ] # P5/32 + - [ 282,180, 247,354, 512,387 ] # P6/64 + +# P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792 +anchors_p6_1280: + - [ 19,27, 44,40, 38,94 ] # P3/8 + - [ 96,68, 86,152, 180,137 ] # P4/16 + - [ 140,301, 303,264, 238,542 ] # P5/32 + - [ 436,615, 739,380, 925,792 ] # P6/64 + +# P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187 +anchors_p6_1920: + - [ 28,41, 67,59, 57,141 ] # P3/8 + - [ 144,103, 129,227, 270,205 ] # P4/16 + - [ 209,452, 455,396, 358,812 ] # P5/32 + - [ 653,922, 1109,570, 1387,1187 ] # P6/64 + + +# P7 ------------------------------------------------------------------------------------------------------------------- +# P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372 +anchors_p7_640: + - [ 11,11, 13,30, 29,20 ] # P3/8 + - [ 30,46, 61,38, 39,92 ] # P4/16 + - [ 78,80, 146,66, 79,163 ] # P5/32 + - [ 149,150, 321,143, 157,303 ] # P6/64 + - [ 257,402, 359,290, 524,372 ] # P7/128 + +# P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818 +anchors_p7_1280: + - [ 19,22, 54,36, 32,77 ] # P3/8 + - [ 70,83, 138,71, 75,173 ] # P4/16 + - [ 165,159, 148,334, 375,151 ] # P5/32 + - [ 334,317, 251,626, 499,474 ] # P6/64 + - [ 750,326, 534,814, 1079,818 ] # P7/128 + +# P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227 +anchors_p7_1920: + - [ 29,34, 81,55, 47,115 ] # P3/8 + - [ 105,124, 207,107, 113,259 ] # P4/16 + - [ 247,238, 222,500, 563,227 ] # P5/32 + - [ 501,476, 376,939, 749,711 ] # P6/64 + - [ 1126,489, 801,1222, 1618,1227 ] # P7/128 diff --git a/Y5_old/models/hub/yolov3-spp.yaml b/Y5_old/models/hub/yolov3-spp.yaml new file mode 100755 index 0000000..38dcc44 --- /dev/null +++ b/Y5_old/models/hub/yolov3-spp.yaml @@ -0,0 +1,51 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# anchors +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# darknet53 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [32, 3, 1]], # 0 + [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 + [-1, 1, Bottleneck, [64]], + [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 + [-1, 2, Bottleneck, [128]], + [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 + [-1, 8, Bottleneck, [256]], + [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 + [-1, 8, Bottleneck, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 + [-1, 4, Bottleneck, [1024]], # 10 + ] + +# YOLOv3-SPP head +head: + [[-1, 1, Bottleneck, [1024, False]], + [-1, 1, SPP, [512, [5, 9, 13]]], + [-1, 1, Conv, [1024, 3, 1]], + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) + + [-2, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) + + [-2, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P3 + [-1, 1, Bottleneck, [256, False]], + [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) + + [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_old/models/hub/yolov3-tiny.yaml b/Y5_old/models/hub/yolov3-tiny.yaml new file mode 100755 index 0000000..ff7638c --- /dev/null +++ b/Y5_old/models/hub/yolov3-tiny.yaml @@ -0,0 +1,41 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# anchors +anchors: + - [10,14, 23,27, 37,58] # P4/16 + - [81,82, 135,169, 344,319] # P5/32 + +# YOLOv3-tiny backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [16, 3, 1]], # 0 + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2 + [-1, 1, Conv, [32, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4 + [-1, 1, Conv, [64, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8 + [-1, 1, Conv, [128, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16 + [-1, 1, Conv, [256, 3, 1]], + [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32 + [-1, 1, Conv, [512, 3, 1]], + [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11 + [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12 + ] + +# YOLOv3-tiny head +head: + [[-1, 1, Conv, [1024, 3, 1]], + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large) + + [-2, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium) + + [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5) + ] diff --git a/Y5_old/models/hub/yolov3.yaml b/Y5_old/models/hub/yolov3.yaml new file mode 100755 index 0000000..f2e7613 --- /dev/null +++ b/Y5_old/models/hub/yolov3.yaml @@ -0,0 +1,51 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# anchors +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# darknet53 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Conv, [32, 3, 1]], # 0 + [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 + [-1, 1, Bottleneck, [64]], + [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 + [-1, 2, Bottleneck, [128]], + [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 + [-1, 8, Bottleneck, [256]], + [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 + [-1, 8, Bottleneck, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 + [-1, 4, Bottleneck, [1024]], # 10 + ] + +# YOLOv3 head +head: + [[-1, 1, Bottleneck, [1024, False]], + [-1, 1, Conv, [512, [1, 1]]], + [-1, 1, Conv, [1024, 3, 1]], + [-1, 1, Conv, [512, 1, 1]], + [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) + + [-2, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 8], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Bottleneck, [512, False]], + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) + + [-2, 1, Conv, [128, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P3 + [-1, 1, Bottleneck, [256, False]], + [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) + + [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_old/models/hub/yolov5-fpn.yaml b/Y5_old/models/hub/yolov5-fpn.yaml new file mode 100755 index 0000000..e772bff --- /dev/null +++ b/Y5_old/models/hub/yolov5-fpn.yaml @@ -0,0 +1,42 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# anchors +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, Bottleneck, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 9, BottleneckCSP, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, BottleneckCSP, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 1, SPP, [1024, [5, 9, 13]]], + [-1, 6, BottleneckCSP, [1024]], # 9 + ] + +# YOLOv5 FPN head +head: + [[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large) + + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 1, Conv, [512, 1, 1]], + [-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium) + + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 1, Conv, [256, 1, 1]], + [-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small) + + [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_old/models/hub/yolov5-p2.yaml b/Y5_old/models/hub/yolov5-p2.yaml new file mode 100755 index 0000000..0633a90 --- /dev/null +++ b/Y5_old/models/hub/yolov5-p2.yaml @@ -0,0 +1,54 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# anchors +anchors: 3 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 + [ -1, 3, C3, [ 128 ] ], + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 + [ -1, 9, C3, [ 256 ] ], + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 + [ -1, 9, C3, [ 512 ] ], + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32 + [ -1, 1, SPP, [ 1024, [ 5, 9, 13 ] ] ], + [ -1, 3, C3, [ 1024, False ] ], # 9 + ] + +# YOLOv5 head +head: + [ [ -1, 1, Conv, [ 512, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 + [ -1, 3, C3, [ 512, False ] ], # 13 + + [ -1, 1, Conv, [ 256, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 + [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small) + + [ -1, 1, Conv, [ 128, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 2 ], 1, Concat, [ 1 ] ], # cat backbone P2 + [ -1, 1, C3, [ 128, False ] ], # 21 (P2/4-xsmall) + + [ -1, 1, Conv, [ 128, 3, 2 ] ], + [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P3 + [ -1, 3, C3, [ 256, False ] ], # 24 (P3/8-small) + + [ -1, 1, Conv, [ 256, 3, 2 ] ], + [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4 + [ -1, 3, C3, [ 512, False ] ], # 27 (P4/16-medium) + + [ -1, 1, Conv, [ 512, 3, 2 ] ], + [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat head P5 + [ -1, 3, C3, [ 1024, False ] ], # 30 (P5/32-large) + + [ [ 24, 27, 30 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5) + ] diff --git a/Y5_old/models/hub/yolov5-p6.yaml b/Y5_old/models/hub/yolov5-p6.yaml new file mode 100755 index 0000000..3728a11 --- /dev/null +++ b/Y5_old/models/hub/yolov5-p6.yaml @@ -0,0 +1,56 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# anchors +anchors: 3 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 + [ -1, 3, C3, [ 128 ] ], + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 + [ -1, 9, C3, [ 256 ] ], + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 + [ -1, 9, C3, [ 512 ] ], + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 + [ -1, 3, C3, [ 768 ] ], + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], + [ -1, 3, C3, [ 1024, False ] ], # 11 + ] + +# YOLOv5 head +head: + [ [ -1, 1, Conv, [ 768, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 + [ -1, 3, C3, [ 768, False ] ], # 15 + + [ -1, 1, Conv, [ 512, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 + [ -1, 3, C3, [ 512, False ] ], # 19 + + [ -1, 1, Conv, [ 256, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) + + [ -1, 1, Conv, [ 256, 3, 2 ] ], + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) + + [ -1, 1, Conv, [ 512, 3, 2 ] ], + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) + + [ -1, 1, Conv, [ 768, 3, 2 ] ], + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 + [ -1, 3, C3, [ 1024, False ] ], # 32 (P5/64-xlarge) + + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5_old/models/hub/yolov5-p7.yaml b/Y5_old/models/hub/yolov5-p7.yaml new file mode 100755 index 0000000..ca8f849 --- /dev/null +++ b/Y5_old/models/hub/yolov5-p7.yaml @@ -0,0 +1,67 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# anchors +anchors: 3 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 + [ -1, 3, C3, [ 128 ] ], + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 + [ -1, 9, C3, [ 256 ] ], + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 + [ -1, 9, C3, [ 512 ] ], + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 + [ -1, 3, C3, [ 768 ] ], + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 + [ -1, 3, C3, [ 1024 ] ], + [ -1, 1, Conv, [ 1280, 3, 2 ] ], # 11-P7/128 + [ -1, 1, SPP, [ 1280, [ 3, 5 ] ] ], + [ -1, 3, C3, [ 1280, False ] ], # 13 + ] + +# YOLOv5 head +head: + [ [ -1, 1, Conv, [ 1024, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat backbone P6 + [ -1, 3, C3, [ 1024, False ] ], # 17 + + [ -1, 1, Conv, [ 768, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 + [ -1, 3, C3, [ 768, False ] ], # 21 + + [ -1, 1, Conv, [ 512, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 + [ -1, 3, C3, [ 512, False ] ], # 25 + + [ -1, 1, Conv, [ 256, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 + [ -1, 3, C3, [ 256, False ] ], # 29 (P3/8-small) + + [ -1, 1, Conv, [ 256, 3, 2 ] ], + [ [ -1, 26 ], 1, Concat, [ 1 ] ], # cat head P4 + [ -1, 3, C3, [ 512, False ] ], # 32 (P4/16-medium) + + [ -1, 1, Conv, [ 512, 3, 2 ] ], + [ [ -1, 22 ], 1, Concat, [ 1 ] ], # cat head P5 + [ -1, 3, C3, [ 768, False ] ], # 35 (P5/32-large) + + [ -1, 1, Conv, [ 768, 3, 2 ] ], + [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P6 + [ -1, 3, C3, [ 1024, False ] ], # 38 (P6/64-xlarge) + + [ -1, 1, Conv, [ 1024, 3, 2 ] ], + [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P7 + [ -1, 3, C3, [ 1280, False ] ], # 41 (P7/128-xxlarge) + + [ [ 29, 32, 35, 38, 41 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6, P7) + ] diff --git a/Y5_old/models/hub/yolov5-panet.yaml b/Y5_old/models/hub/yolov5-panet.yaml new file mode 100755 index 0000000..340f95a --- /dev/null +++ b/Y5_old/models/hub/yolov5-panet.yaml @@ -0,0 +1,48 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# anchors +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, BottleneckCSP, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 9, BottleneckCSP, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, BottleneckCSP, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 1, SPP, [1024, [5, 9, 13]]], + [-1, 3, BottleneckCSP, [1024, False]], # 9 + ] + +# YOLOv5 PANet head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, BottleneckCSP, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_old/models/hub/yolov5l6.yaml b/Y5_old/models/hub/yolov5l6.yaml new file mode 100755 index 0000000..11298b0 --- /dev/null +++ b/Y5_old/models/hub/yolov5l6.yaml @@ -0,0 +1,60 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# anchors +anchors: + - [ 19,27, 44,40, 38,94 ] # P3/8 + - [ 96,68, 86,152, 180,137 ] # P4/16 + - [ 140,301, 303,264, 238,542 ] # P5/32 + - [ 436,615, 739,380, 925,792 ] # P6/64 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 + [ -1, 3, C3, [ 128 ] ], + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 + [ -1, 9, C3, [ 256 ] ], + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 + [ -1, 9, C3, [ 512 ] ], + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 + [ -1, 3, C3, [ 768 ] ], + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], + [ -1, 3, C3, [ 1024, False ] ], # 11 + ] + +# YOLOv5 head +head: + [ [ -1, 1, Conv, [ 768, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 + [ -1, 3, C3, [ 768, False ] ], # 15 + + [ -1, 1, Conv, [ 512, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 + [ -1, 3, C3, [ 512, False ] ], # 19 + + [ -1, 1, Conv, [ 256, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) + + [ -1, 1, Conv, [ 256, 3, 2 ] ], + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) + + [ -1, 1, Conv, [ 512, 3, 2 ] ], + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) + + [ -1, 1, Conv, [ 768, 3, 2 ] ], + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) + + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5_old/models/hub/yolov5m6.yaml b/Y5_old/models/hub/yolov5m6.yaml new file mode 100755 index 0000000..48afc86 --- /dev/null +++ b/Y5_old/models/hub/yolov5m6.yaml @@ -0,0 +1,60 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 0.67 # model depth multiple +width_multiple: 0.75 # layer channel multiple + +# anchors +anchors: + - [ 19,27, 44,40, 38,94 ] # P3/8 + - [ 96,68, 86,152, 180,137 ] # P4/16 + - [ 140,301, 303,264, 238,542 ] # P5/32 + - [ 436,615, 739,380, 925,792 ] # P6/64 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 + [ -1, 3, C3, [ 128 ] ], + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 + [ -1, 9, C3, [ 256 ] ], + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 + [ -1, 9, C3, [ 512 ] ], + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 + [ -1, 3, C3, [ 768 ] ], + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], + [ -1, 3, C3, [ 1024, False ] ], # 11 + ] + +# YOLOv5 head +head: + [ [ -1, 1, Conv, [ 768, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 + [ -1, 3, C3, [ 768, False ] ], # 15 + + [ -1, 1, Conv, [ 512, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 + [ -1, 3, C3, [ 512, False ] ], # 19 + + [ -1, 1, Conv, [ 256, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) + + [ -1, 1, Conv, [ 256, 3, 2 ] ], + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) + + [ -1, 1, Conv, [ 512, 3, 2 ] ], + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) + + [ -1, 1, Conv, [ 768, 3, 2 ] ], + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) + + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5_old/models/hub/yolov5s6.yaml b/Y5_old/models/hub/yolov5s6.yaml new file mode 100755 index 0000000..1df577a --- /dev/null +++ b/Y5_old/models/hub/yolov5s6.yaml @@ -0,0 +1,60 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple + +# anchors +anchors: + - [ 19,27, 44,40, 38,94 ] # P3/8 + - [ 96,68, 86,152, 180,137 ] # P4/16 + - [ 140,301, 303,264, 238,542 ] # P5/32 + - [ 436,615, 739,380, 925,792 ] # P6/64 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 + [ -1, 3, C3, [ 128 ] ], + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 + [ -1, 9, C3, [ 256 ] ], + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 + [ -1, 9, C3, [ 512 ] ], + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 + [ -1, 3, C3, [ 768 ] ], + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], + [ -1, 3, C3, [ 1024, False ] ], # 11 + ] + +# YOLOv5 head +head: + [ [ -1, 1, Conv, [ 768, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 + [ -1, 3, C3, [ 768, False ] ], # 15 + + [ -1, 1, Conv, [ 512, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 + [ -1, 3, C3, [ 512, False ] ], # 19 + + [ -1, 1, Conv, [ 256, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) + + [ -1, 1, Conv, [ 256, 3, 2 ] ], + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) + + [ -1, 1, Conv, [ 512, 3, 2 ] ], + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) + + [ -1, 1, Conv, [ 768, 3, 2 ] ], + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) + + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5_old/models/hub/yolov5x6.yaml b/Y5_old/models/hub/yolov5x6.yaml new file mode 100755 index 0000000..5ebc021 --- /dev/null +++ b/Y5_old/models/hub/yolov5x6.yaml @@ -0,0 +1,60 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.33 # model depth multiple +width_multiple: 1.25 # layer channel multiple + +# anchors +anchors: + - [ 19,27, 44,40, 38,94 ] # P3/8 + - [ 96,68, 86,152, 180,137 ] # P4/16 + - [ 140,301, 303,264, 238,542 ] # P5/32 + - [ 436,615, 739,380, 925,792 ] # P6/64 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 + [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 + [ -1, 3, C3, [ 128 ] ], + [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 + [ -1, 9, C3, [ 256 ] ], + [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 + [ -1, 9, C3, [ 512 ] ], + [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 + [ -1, 3, C3, [ 768 ] ], + [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 + [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], + [ -1, 3, C3, [ 1024, False ] ], # 11 + ] + +# YOLOv5 head +head: + [ [ -1, 1, Conv, [ 768, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 + [ -1, 3, C3, [ 768, False ] ], # 15 + + [ -1, 1, Conv, [ 512, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 + [ -1, 3, C3, [ 512, False ] ], # 19 + + [ -1, 1, Conv, [ 256, 1, 1 ] ], + [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], + [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 + [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) + + [ -1, 1, Conv, [ 256, 3, 2 ] ], + [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 + [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) + + [ -1, 1, Conv, [ 512, 3, 2 ] ], + [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 + [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) + + [ -1, 1, Conv, [ 768, 3, 2 ] ], + [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 + [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) + + [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) + ] diff --git a/Y5_old/models/yolo.py b/Y5_old/models/yolo.py new file mode 100755 index 0000000..8117cb4 --- /dev/null +++ b/Y5_old/models/yolo.py @@ -0,0 +1,275 @@ +import argparse +import logging +import sys +from copy import deepcopy + +sys.path.append('./') # to run '$ python *.py' files in subdirectories +logger = logging.getLogger(__name__) + +from Y5.models.common import * +from Y5.models.experimental import * +from Y5.utils.autoanchor import check_anchor_order +from Y5.utils.general import make_divisible, check_file, set_logging +from Y5.utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \ + select_device, copy_attr + +try: + import thop # for FLOPS computation +except ImportError: + thop = None + + +class Detect(nn.Module): + stride = None # strides computed during build + export = False # onnx export + + def __init__(self, nc=80, anchors=(), ch=()): # detection layer + super(Detect, self).__init__() + self.nc = nc # number of classes + self.no = nc + 5 # number of outputs per anchor + self.nl = len(anchors) # number of detection layers + self.na = len(anchors[0]) // 2 # number of anchors + self.grid = [torch.zeros(1)] * self.nl # init grid + a = torch.tensor(anchors).float().view(self.nl, -1, 2) + self.register_buffer('anchors', a) # shape(nl,na,2) + self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) + self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv + + def forward(self, x): + # x = x.copy() # for profiling + z = [] # inference output + self.training |= self.export + for i in range(self.nl): + x[i] = self.m[i](x[i]) # conv + bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) + x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() + + if not self.training: # inference + if self.grid[i].shape[2:4] != x[i].shape[2:4]: + self.grid[i] = self._make_grid(nx, ny).to(x[i].device) + + y = x[i].sigmoid() + y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy + y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh + z.append(y.view(bs, -1, self.no)) + + return x if self.training else (torch.cat(z, 1), x) + + @staticmethod + def _make_grid(nx=20, ny=20): + yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) + return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() + + +class Model(nn.Module): + def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes + super(Model, self).__init__() + if isinstance(cfg, dict): + self.yaml = cfg # model dict + else: # is *.yaml + import yaml # for torch hub + self.yaml_file = Path(cfg).name + with open(cfg) as f: + self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict + + # Define model + ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels + if nc and nc != self.yaml['nc']: + logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") + self.yaml['nc'] = nc # override yaml value + if anchors: + logger.info(f'Overriding model.yaml anchors with anchors={anchors}') + self.yaml['anchors'] = round(anchors) # override yaml value + self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist + self.names = [str(i) for i in range(self.yaml['nc'])] # default names + # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))]) + + # Build strides, anchors + m = self.model[-1] # Detect() + if isinstance(m, Detect): + s = 256 # 2x min stride + m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward + m.anchors /= m.stride.view(-1, 1, 1) + check_anchor_order(m) + self.stride = m.stride + self._initialize_biases() # only run once + # print('Strides: %s' % m.stride.tolist()) + + # Init weights, biases + initialize_weights(self) + self.info() + logger.info('') + + def forward(self, x, augment=False, profile=False): + if augment: + img_size = x.shape[-2:] # height, width + s = [1, 0.83, 0.67] # scales + f = [None, 3, None] # flips (2-ud, 3-lr) + y = [] # outputs + for si, fi in zip(s, f): + xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) + yi = self.forward_once(xi)[0] # forward + # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save + yi[..., :4] /= si # de-scale + if fi == 2: + yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud + elif fi == 3: + yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr + y.append(yi) + return torch.cat(y, 1), None # augmented inference, train + else: + return self.forward_once(x, profile) # single-scale inference, train + + def forward_once(self, x, profile=False): + y, dt = [], [] # outputs + for m in self.model: + if m.f != -1: # if not from previous layer + x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers + + if profile: + o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPS + t = time_synchronized() + for _ in range(10): + _ = m(x) + dt.append((time_synchronized() - t) * 100) + print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type)) + + x = m(x) # run + y.append(x if m.i in self.save else None) # save output + + if profile: + print('%.1fms total' % sum(dt)) + return x + + def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency + # https://arxiv.org/abs/1708.02002 section 3.3 + # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. + m = self.model[-1] # Detect() module + for mi, s in zip(m.m, m.stride): # from + b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) + b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) + b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls + mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) + + def _print_biases(self): + m = self.model[-1] # Detect() module + for mi in m.m: # from + b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) + print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())) + + # def _print_weights(self): + # for m in self.model.modules(): + # if type(m) is Bottleneck: + # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights + + def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers + #print('Fusing layers... ') + for m in self.model.modules(): + if type(m) is Conv and hasattr(m, 'bn'): + m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv + delattr(m, 'bn') # remove batchnorm + m.forward = m.fuseforward # update forward + self.info() + return self + + def nms(self, mode=True): # add or remove NMS module + present = type(self.model[-1]) is NMS # last layer is NMS + if mode and not present: + print('Adding NMS... ') + m = NMS() # module + m.f = -1 # from + m.i = self.model[-1].i + 1 # index + self.model.add_module(name='%s' % m.i, module=m) # add + self.eval() + elif not mode and present: + print('Removing NMS... ') + self.model = self.model[:-1] # remove + return self + + def autoshape(self): # add autoShape module + print('Adding autoShape... ') + m = autoShape(self) # wrap model + copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes + return m + + def info(self, verbose=False, img_size=640): # print model information + model_info(self, verbose, img_size) + + +def parse_model(d, ch): # model_dict, input_channels(3) + logger.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments')) + anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] + na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors + no = na * (nc + 5) # number of outputs = anchors * (classes + 5) + + layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out + for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args + m = eval(m) if isinstance(m, str) else m # eval strings + for j, a in enumerate(args): + try: + args[j] = eval(a) if isinstance(a, str) else a # eval strings + except: + pass + + n = max(round(n * gd), 1) if n > 1 else n # depth gain + if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, + C3]: + c1, c2 = ch[f], args[0] + if c2 != no: # if not output + c2 = make_divisible(c2 * gw, 8) + + args = [c1, c2, *args[1:]] + if m in [BottleneckCSP, C3]: + args.insert(2, n) # number of repeats + n = 1 + elif m is nn.BatchNorm2d: + args = [ch[f]] + elif m is Concat: + c2 = sum([ch[x] for x in f]) + elif m is Detect: + args.append([ch[x] for x in f]) + if isinstance(args[1], int): # number of anchors + args[1] = [list(range(args[1] * 2))] * len(f) + elif m is Contract: + c2 = ch[f] * args[0] ** 2 + elif m is Expand: + c2 = ch[f] // args[0] ** 2 + else: + c2 = ch[f] + + m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module + t = str(m)[8:-2].replace('__main__.', '') # module type + np = sum([x.numel() for x in m_.parameters()]) # number params + m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params + logger.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print + save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist + layers.append(m_) + if i == 0: + ch = [] + ch.append(c2) + return nn.Sequential(*layers), sorted(save) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') + parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') + opt = parser.parse_args() + opt.cfg = check_file(opt.cfg) # check file + set_logging() + device = select_device(opt.device) + + # Create model + model = Model(opt.cfg).to(device) + model.train() + + # Profile + # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device) + # y = model(img, profile=True) + + # Tensorboard + # from torch.utils.tensorboard import SummaryWriter + # tb_writer = SummaryWriter() + # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/") + # tb_writer.add_graph(model.model, img) # add model to tensorboard + # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard diff --git a/Y5_old/models/yolov5l.yaml b/Y5_old/models/yolov5l.yaml new file mode 100755 index 0000000..71ebf86 --- /dev/null +++ b/Y5_old/models/yolov5l.yaml @@ -0,0 +1,48 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.0 # model depth multiple +width_multiple: 1.0 # layer channel multiple + +# anchors +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 9, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 1, SPP, [1024, [5, 9, 13]]], + [-1, 3, C3, [1024, False]], # 9 + ] + +# YOLOv5 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_old/models/yolov5m.yaml b/Y5_old/models/yolov5m.yaml new file mode 100755 index 0000000..3c749c9 --- /dev/null +++ b/Y5_old/models/yolov5m.yaml @@ -0,0 +1,48 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 0.67 # model depth multiple +width_multiple: 0.75 # layer channel multiple + +# anchors +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 9, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 1, SPP, [1024, [5, 9, 13]]], + [-1, 3, C3, [1024, False]], # 9 + ] + +# YOLOv5 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_old/models/yolov5s.yaml b/Y5_old/models/yolov5s.yaml new file mode 100755 index 0000000..aca669d --- /dev/null +++ b/Y5_old/models/yolov5s.yaml @@ -0,0 +1,48 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 0.33 # model depth multiple +width_multiple: 0.50 # layer channel multiple + +# anchors +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 9, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 1, SPP, [1024, [5, 9, 13]]], + [-1, 3, C3, [1024, False]], # 9 + ] + +# YOLOv5 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_old/models/yolov5x.yaml b/Y5_old/models/yolov5x.yaml new file mode 100755 index 0000000..d3babdf --- /dev/null +++ b/Y5_old/models/yolov5x.yaml @@ -0,0 +1,48 @@ +# parameters +nc: 80 # number of classes +depth_multiple: 1.33 # model depth multiple +width_multiple: 1.25 # layer channel multiple + +# anchors +anchors: + - [10,13, 16,30, 33,23] # P3/8 + - [30,61, 62,45, 59,119] # P4/16 + - [116,90, 156,198, 373,326] # P5/32 + +# YOLOv5 backbone +backbone: + # [from, number, module, args] + [[-1, 1, Focus, [64, 3]], # 0-P1/2 + [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 + [-1, 3, C3, [128]], + [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 + [-1, 9, C3, [256]], + [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 + [-1, 9, C3, [512]], + [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 + [-1, 1, SPP, [1024, [5, 9, 13]]], + [-1, 3, C3, [1024, False]], # 9 + ] + +# YOLOv5 head +head: + [[-1, 1, Conv, [512, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 6], 1, Concat, [1]], # cat backbone P4 + [-1, 3, C3, [512, False]], # 13 + + [-1, 1, Conv, [256, 1, 1]], + [-1, 1, nn.Upsample, [None, 2, 'nearest']], + [[-1, 4], 1, Concat, [1]], # cat backbone P3 + [-1, 3, C3, [256, False]], # 17 (P3/8-small) + + [-1, 1, Conv, [256, 3, 2]], + [[-1, 14], 1, Concat, [1]], # cat head P4 + [-1, 3, C3, [512, False]], # 20 (P4/16-medium) + + [-1, 1, Conv, [512, 3, 2]], + [[-1, 10], 1, Concat, [1]], # cat head P5 + [-1, 3, C3, [1024, False]], # 23 (P5/32-large) + + [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) + ] diff --git a/Y5_old/utils/__init__.py b/Y5_old/utils/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/Y5_old/utils/__pycache__/__init__.cpython-36.pyc b/Y5_old/utils/__pycache__/__init__.cpython-36.pyc new file mode 100755 index 0000000..c39f41d Binary files /dev/null and b/Y5_old/utils/__pycache__/__init__.cpython-36.pyc differ diff --git a/Y5_old/utils/__pycache__/__init__.cpython-37.pyc b/Y5_old/utils/__pycache__/__init__.cpython-37.pyc new file mode 100755 index 0000000..20d9c22 Binary files /dev/null and b/Y5_old/utils/__pycache__/__init__.cpython-37.pyc differ diff --git a/Y5_old/utils/__pycache__/__init__.cpython-38.pyc b/Y5_old/utils/__pycache__/__init__.cpython-38.pyc new file mode 100755 index 0000000..ff07141 Binary files /dev/null and b/Y5_old/utils/__pycache__/__init__.cpython-38.pyc differ diff --git a/Y5_old/utils/__pycache__/autoanchor.cpython-36.pyc b/Y5_old/utils/__pycache__/autoanchor.cpython-36.pyc new file mode 100755 index 0000000..dc82a50 Binary files /dev/null and b/Y5_old/utils/__pycache__/autoanchor.cpython-36.pyc differ diff --git a/Y5_old/utils/__pycache__/datasets.cpython-36.pyc b/Y5_old/utils/__pycache__/datasets.cpython-36.pyc new file mode 100755 index 0000000..6417c35 Binary files /dev/null and b/Y5_old/utils/__pycache__/datasets.cpython-36.pyc differ diff --git a/Y5_old/utils/__pycache__/general.cpython-36.pyc b/Y5_old/utils/__pycache__/general.cpython-36.pyc new file mode 100755 index 0000000..fa7db0d Binary files /dev/null and b/Y5_old/utils/__pycache__/general.cpython-36.pyc differ diff --git a/Y5/utils/__pycache__/google_utils.cpython-36.pyc b/Y5_old/utils/__pycache__/google_utils.cpython-36.pyc old mode 100644 new mode 100755 similarity index 93% rename from Y5/utils/__pycache__/google_utils.cpython-36.pyc rename to Y5_old/utils/__pycache__/google_utils.cpython-36.pyc index 1659ddd..f2986ba Binary files a/Y5/utils/__pycache__/google_utils.cpython-36.pyc and b/Y5_old/utils/__pycache__/google_utils.cpython-36.pyc differ diff --git a/Y5/utils/__pycache__/loss.cpython-36.pyc b/Y5_old/utils/__pycache__/loss.cpython-36.pyc old mode 100644 new mode 100755 similarity index 100% rename from Y5/utils/__pycache__/loss.cpython-36.pyc rename to Y5_old/utils/__pycache__/loss.cpython-36.pyc diff --git a/Y5_old/utils/__pycache__/metrics.cpython-36.pyc b/Y5_old/utils/__pycache__/metrics.cpython-36.pyc new file mode 100755 index 0000000..db9aec0 Binary files /dev/null and b/Y5_old/utils/__pycache__/metrics.cpython-36.pyc differ diff --git a/Y5_old/utils/__pycache__/plots.cpython-36.pyc b/Y5_old/utils/__pycache__/plots.cpython-36.pyc new file mode 100755 index 0000000..118482e Binary files /dev/null and b/Y5_old/utils/__pycache__/plots.cpython-36.pyc differ diff --git a/Y5_old/utils/__pycache__/plots.cpython-37.pyc b/Y5_old/utils/__pycache__/plots.cpython-37.pyc new file mode 100755 index 0000000..991697d Binary files /dev/null and b/Y5_old/utils/__pycache__/plots.cpython-37.pyc differ diff --git a/Y5_old/utils/__pycache__/plots.cpython-38.pyc b/Y5_old/utils/__pycache__/plots.cpython-38.pyc new file mode 100755 index 0000000..feaa9df Binary files /dev/null and b/Y5_old/utils/__pycache__/plots.cpython-38.pyc differ diff --git a/Y5_old/utils/__pycache__/torch_utils.cpython-36.pyc b/Y5_old/utils/__pycache__/torch_utils.cpython-36.pyc new file mode 100755 index 0000000..7f87608 Binary files /dev/null and b/Y5_old/utils/__pycache__/torch_utils.cpython-36.pyc differ diff --git a/Y5_old/utils/activations.py b/Y5_old/utils/activations.py new file mode 100755 index 0000000..aa3ddf0 --- /dev/null +++ b/Y5_old/utils/activations.py @@ -0,0 +1,72 @@ +# Activation functions + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +# SiLU https://arxiv.org/pdf/1606.08415.pdf ---------------------------------------------------------------------------- +class SiLU(nn.Module): # export-friendly version of nn.SiLU() + @staticmethod + def forward(x): + return x * torch.sigmoid(x) + + +class Hardswish(nn.Module): # export-friendly version of nn.Hardswish() + @staticmethod + def forward(x): + # return x * F.hardsigmoid(x) # for torchscript and CoreML + return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX + + +class MemoryEfficientSwish(nn.Module): + class F(torch.autograd.Function): + @staticmethod + def forward(ctx, x): + ctx.save_for_backward(x) + return x * torch.sigmoid(x) + + @staticmethod + def backward(ctx, grad_output): + x = ctx.saved_tensors[0] + sx = torch.sigmoid(x) + return grad_output * (sx * (1 + x * (1 - sx))) + + def forward(self, x): + return self.F.apply(x) + + +# Mish https://github.com/digantamisra98/Mish -------------------------------------------------------------------------- +class Mish(nn.Module): + @staticmethod + def forward(x): + return x * F.softplus(x).tanh() + + +class MemoryEfficientMish(nn.Module): + class F(torch.autograd.Function): + @staticmethod + def forward(ctx, x): + ctx.save_for_backward(x) + return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) + + @staticmethod + def backward(ctx, grad_output): + x = ctx.saved_tensors[0] + sx = torch.sigmoid(x) + fx = F.softplus(x).tanh() + return grad_output * (fx + x * sx * (1 - fx * fx)) + + def forward(self, x): + return self.F.apply(x) + + +# FReLU https://arxiv.org/abs/2007.11824 ------------------------------------------------------------------------------- +class FReLU(nn.Module): + def __init__(self, c1, k=3): # ch_in, kernel + super().__init__() + self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) + self.bn = nn.BatchNorm2d(c1) + + def forward(self, x): + return torch.max(x, self.bn(self.conv(x))) diff --git a/Y5_old/utils/autoanchor.py b/Y5_old/utils/autoanchor.py new file mode 100755 index 0000000..86a1baf --- /dev/null +++ b/Y5_old/utils/autoanchor.py @@ -0,0 +1,155 @@ +# Auto-anchor utils + +import numpy as np +import torch +import yaml +from scipy.cluster.vq import kmeans +from tqdm import tqdm + +from Y5.utils.general import colorstr + + +def check_anchor_order(m): + # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary + a = m.anchor_grid.prod(-1).view(-1) # anchor area + da = a[-1] - a[0] # delta a + ds = m.stride[-1] - m.stride[0] # delta s + if da.sign() != ds.sign(): # same order + print('Reversing anchor order') + m.anchors[:] = m.anchors.flip(0) + m.anchor_grid[:] = m.anchor_grid.flip(0) + + +def check_anchors(dataset, model, thr=4.0, imgsz=640): + # Check anchor fit to data, recompute if necessary + prefix = colorstr('autoanchor: ') + print(f'\n{prefix}Analyzing anchors... ', end='') + m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect() + shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True) + scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale + wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh + + def metric(k): # compute metric + r = wh[:, None] / k[None] + x = torch.min(r, 1. / r).min(2)[0] # ratio metric + best = x.max(1)[0] # best_x + aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold + bpr = (best > 1. / thr).float().mean() # best possible recall + return bpr, aat + + bpr, aat = metric(m.anchor_grid.clone().cpu().view(-1, 2)) + print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='') + if bpr < 0.98: # threshold to recompute + print('. Attempting to improve anchors, please wait...') + na = m.anchor_grid.numel() // 2 # number of anchors + new_anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) + new_bpr = metric(new_anchors.reshape(-1, 2))[0] + if new_bpr > bpr: # replace anchors + new_anchors = torch.tensor(new_anchors, device=m.anchors.device).type_as(m.anchors) + m.anchor_grid[:] = new_anchors.clone().view_as(m.anchor_grid) # for inference + m.anchors[:] = new_anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss + check_anchor_order(m) + print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.') + else: + print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.') + print('') # newline + + +def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): + """ Creates kmeans-evolved anchors from training dataset + + Arguments: + path: path to dataset *.yaml, or a loaded dataset + n: number of anchors + img_size: image size used for training + thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0 + gen: generations to evolve anchors using genetic algorithm + verbose: print all results + + Return: + k: kmeans evolved anchors + + Usage: + from utils.autoanchor import *; _ = kmean_anchors() + """ + thr = 1. / thr + prefix = colorstr('autoanchor: ') + + def metric(k, wh): # compute metrics + r = wh[:, None] / k[None] + x = torch.min(r, 1. / r).min(2)[0] # ratio metric + # x = wh_iou(wh, torch.tensor(k)) # iou metric + return x, x.max(1)[0] # x, best_x + + def anchor_fitness(k): # mutation fitness + _, best = metric(torch.tensor(k, dtype=torch.float32), wh) + return (best * (best > thr).float()).mean() # fitness + + def print_results(k): + k = k[np.argsort(k.prod(1))] # sort small to large + x, best = metric(k, wh0) + bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr + print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr') + print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' + f'past_thr={x[x > thr].mean():.3f}-mean: ', end='') + for i, x in enumerate(k): + print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg + return k + + if isinstance(path, str): # *.yaml file + with open(path) as f: + data_dict = yaml.load(f, Loader=yaml.SafeLoader) # model dict + from utils.datasets import LoadImagesAndLabels + dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) + else: + dataset = path # dataset + + # Get label wh + shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) + wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh + + # Filter + i = (wh0 < 3.0).any(1).sum() + if i: + print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.') + wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels + # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 + + # Kmeans calculation + print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...') + s = wh.std(0) # sigmas for whitening + k, dist = kmeans(wh / s, n, iter=30) # points, mean distance + k *= s + wh = torch.tensor(wh, dtype=torch.float32) # filtered + wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered + k = print_results(k) + + # Plot + # k, d = [None] * 20, [None] * 20 + # for i in tqdm(range(1, 21)): + # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance + # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) + # ax = ax.ravel() + # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') + # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh + # ax[0].hist(wh[wh[:, 0]<100, 0],400) + # ax[1].hist(wh[wh[:, 1]<100, 1],400) + # fig.savefig('wh.png', dpi=200) + + # Evolve + npr = np.random + f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma + pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar + for _ in pbar: + v = np.ones(sh) + while (v == 1).all(): # mutate until a change occurs (prevent duplicates) + v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) + kg = (k.copy() * v).clip(min=2.0) + fg = anchor_fitness(kg) + if fg > f: + f, k = fg, kg.copy() + pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' + if verbose: + print_results(k) + + return print_results(k) diff --git a/Y5_old/utils/aws/__init__.py b/Y5_old/utils/aws/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/Y5_old/utils/aws/mime.sh b/Y5_old/utils/aws/mime.sh new file mode 100755 index 0000000..c319a83 --- /dev/null +++ b/Y5_old/utils/aws/mime.sh @@ -0,0 +1,26 @@ +# AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/ +# This script will run on every instance restart, not only on first start +# --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA --- + +Content-Type: multipart/mixed; boundary="//" +MIME-Version: 1.0 + +--// +Content-Type: text/cloud-config; charset="us-ascii" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Content-Disposition: attachment; filename="cloud-config.txt" + +#cloud-config +cloud_final_modules: +- [scripts-user, always] + +--// +Content-Type: text/x-shellscript; charset="us-ascii" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Content-Disposition: attachment; filename="userdata.txt" + +#!/bin/bash +# --- paste contents of userdata.sh here --- +--// diff --git a/Y5_old/utils/aws/resume.py b/Y5_old/utils/aws/resume.py new file mode 100755 index 0000000..563f22b --- /dev/null +++ b/Y5_old/utils/aws/resume.py @@ -0,0 +1,37 @@ +# Resume all interrupted trainings in yolov5/ dir including DPP trainings +# Usage: $ python utils/aws/resume.py + +import os +import sys +from pathlib import Path + +import torch +import yaml + +sys.path.append('./') # to run '$ python *.py' files in subdirectories + +port = 0 # --master_port +path = Path('').resolve() +for last in path.rglob('*/**/last.pt'): + ckpt = torch.load(last) + if ckpt['optimizer'] is None: + continue + + # Load opt.yaml + with open(last.parent.parent / 'opt.yaml') as f: + opt = yaml.load(f, Loader=yaml.SafeLoader) + + # Get device count + d = opt['device'].split(',') # devices + nd = len(d) # number of devices + ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel + + if ddp: # multi-GPU + port += 1 + cmd = f'python -m torch.distributed.launch --nproc_per_node {nd} --master_port {port} train.py --resume {last}' + else: # single-GPU + cmd = f'python train.py --resume {last}' + + cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread + print(cmd) + os.system(cmd) diff --git a/Y5_old/utils/aws/userdata.sh b/Y5_old/utils/aws/userdata.sh new file mode 100755 index 0000000..890606b --- /dev/null +++ b/Y5_old/utils/aws/userdata.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html +# This script will run only once on first instance start (for a re-start script see mime.sh) +# /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir +# Use >300 GB SSD + +cd home/ubuntu +if [ ! -d yolov5 ]; then + echo "Running first-time script." # install dependencies, download COCO, pull Docker + git clone https://github.com/ultralytics/yolov5 && sudo chmod -R 777 yolov5 + cd yolov5 + bash data/scripts/get_coco.sh && echo "Data done." & + sudo docker pull ultralytics/yolov5:latest && echo "Docker done." & + python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." & + wait && echo "All tasks done." # finish background tasks +else + echo "Running re-start script." # resume interrupted runs + i=0 + list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour' + while IFS= read -r id; do + ((i++)) + echo "restarting container $i: $id" + sudo docker start $id + # sudo docker exec -it $id python train.py --resume # single-GPU + sudo docker exec -d $id python utils/aws/resume.py # multi-scenario + done <<<"$list" +fi diff --git a/Y5/utils/datasets.py b/Y5_old/utils/datasets.py similarity index 100% rename from Y5/utils/datasets.py rename to Y5_old/utils/datasets.py diff --git a/Y5_old/utils/general.py b/Y5_old/utils/general.py new file mode 100755 index 0000000..324114e --- /dev/null +++ b/Y5_old/utils/general.py @@ -0,0 +1,576 @@ +# General utils + +import glob +import logging +import math +import os +import platform +import random +import re +import subprocess +import time +from pathlib import Path + +import cv2 +import numpy as np +import torch +import torchvision +import yaml + +from Y5.utils.google_utils import gsutil_getsize +from Y5.utils.metrics import fitness +from Y5.utils.torch_utils import init_torch_seeds + +# Settings +torch.set_printoptions(linewidth=320, precision=5, profile='long') +np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5 +cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader) +#os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8)) # NumExpr max threads + + +def set_logging(rank=-1): + logging.basicConfig( + format="%(message)s", + level=logging.INFO if rank in [-1, 0] else logging.WARN) + + +def init_seeds(seed=0): + # Initialize random number generator (RNG) seeds + random.seed(seed) + np.random.seed(seed) + init_torch_seeds(seed) + + +def get_latest_run(search_dir='.'): + # Return path to most recent 'last.pt' in /runs (i.e. to --resume from) + last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True) + return max(last_list, key=os.path.getctime) if last_list else '' + + +def isdocker(): + # Is environment a Docker container + return Path('/workspace').exists() # or Path('/.dockerenv').exists() + + +def check_online(): + # Check internet connectivity + import socket + try: + socket.create_connection(("1.1.1.1", 443), 5) # check host accesability + return True + except OSError: + return False + + +def check_git_status(): + # Recommend 'git pull' if code is out of date + print(colorstr('github: '), end='') + try: + assert Path('.git').exists(), 'skipping check (not a git repository)' + assert not isdocker(), 'skipping check (Docker image)' + assert check_online(), 'skipping check (offline)' + + cmd = 'git fetch && git config --get remote.origin.url' + url = subprocess.check_output(cmd, shell=True).decode().strip().rstrip('.git') # github repo url + branch = subprocess.check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out + n = int(subprocess.check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind + if n > 0: + s = f"⚠️ WARNING: code is out of date by {n} commit{'s' * (n > 1)}. " \ + f"Use 'git pull' to update or 'git clone {url}' to download latest." + else: + s = f'up to date with {url} ✅' + print(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) + except Exception as e: + print(e) + + +def check_requirements(file='requirements.txt', exclude=()): + # Check installed dependencies meet requirements + import pkg_resources + requirements = [f'{x.name}{x.specifier}' for x in pkg_resources.parse_requirements(Path(file).open()) + if x.name not in exclude] + pkg_resources.require(requirements) # DistributionNotFound or VersionConflict exception if requirements not met + + +def check_img_size(img_size, s=32): + # Verify img_size is a multiple of stride s + new_size = make_divisible(img_size, int(s)) # ceil gs-multiple + if new_size != img_size: + print('WARNING: --img-size %g must be multiple of max stride %g, updating to %g' % (img_size, s, new_size)) + return new_size + + +def check_imshow(): + # Check if environment supports image displays + try: + assert not isdocker(), 'cv2.imshow() is disabled in Docker environments' + cv2.imshow('test', np.zeros((1, 1, 3))) + cv2.waitKey(1) + cv2.destroyAllWindows() + cv2.waitKey(1) + return True + except Exception as e: + print(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}') + return False + + +def check_file(file): + # Search for file if not found + if os.path.isfile(file) or file == '': + return file + else: + files = glob.glob('./**/' + file, recursive=True) # find file + assert len(files), 'File Not Found: %s' % file # assert file was found + assert len(files) == 1, "Multiple files match '%s', specify exact path: %s" % (file, files) # assert unique + return files[0] # return file + + +def check_dataset(dict): + # Download dataset if not found locally + val, s = dict.get('val'), dict.get('download') + if val and len(val): + val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path + if not all(x.exists() for x in val): + print('\nWARNING: Dataset not found, nonexistent paths: %s' % [str(x) for x in val if not x.exists()]) + if s and len(s): # download script + print('Downloading %s ...' % s) + if s.startswith('http') and s.endswith('.zip'): # URL + f = Path(s).name # filename + torch.hub.download_url_to_file(s, f) + r = os.system('unzip -q %s -d ../ && rm %s' % (f, f)) # unzip + else: # bash script + r = os.system(s) + print('Dataset autodownload %s\n' % ('success' if r == 0 else 'failure')) # analyze return value + else: + raise Exception('Dataset not found.') + + +def make_divisible(x, divisor): + # Returns x evenly divisible by divisor + return math.ceil(x / divisor) * divisor + + +def clean_str(s): + # Cleans a string by replacing special characters with underscore _ + return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s) + + +def one_cycle(y1=0.0, y2=1.0, steps=100): + # lambda function for sinusoidal ramp from y1 to y2 + return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1 + + +def colorstr(*input): + # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world') + *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string + colors = {'black': '\033[30m', # basic colors + 'red': '\033[31m', + 'green': '\033[32m', + 'yellow': '\033[33m', + 'blue': '\033[34m', + 'magenta': '\033[35m', + 'cyan': '\033[36m', + 'white': '\033[37m', + 'bright_black': '\033[90m', # bright colors + 'bright_red': '\033[91m', + 'bright_green': '\033[92m', + 'bright_yellow': '\033[93m', + 'bright_blue': '\033[94m', + 'bright_magenta': '\033[95m', + 'bright_cyan': '\033[96m', + 'bright_white': '\033[97m', + 'end': '\033[0m', # misc + 'bold': '\033[1m', + 'underline': '\033[4m'} + return ''.join(colors[x] for x in args) + f'{string}' + colors['end'] + + +def labels_to_class_weights(labels, nc=80): + # Get class weights (inverse frequency) from training labels + if labels[0] is None: # no labels loaded + return torch.Tensor() + + labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO + classes = labels[:, 0].astype(np.int) # labels = [class xywh] + weights = np.bincount(classes, minlength=nc) # occurrences per class + + # Prepend gridpoint count (for uCE training) + # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image + # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start + + weights[weights == 0] = 1 # replace empty bins with 1 + weights = 1 / weights # number of targets per class + weights /= weights.sum() # normalize + return torch.from_numpy(weights) + + +def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)): + # Produces image weights based on class_weights and image contents + class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels]) + image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1) + # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample + return image_weights + + +def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper) + # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/ + # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n') + # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n') + # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco + # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet + x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, + 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90] + return x + + +def xyxy2xywh(x): + # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center + y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center + y[:, 2] = x[:, 2] - x[:, 0] # width + y[:, 3] = x[:, 3] - x[:, 1] # height + return y + + +def xywh2xyxy(x): + # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x + y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y + y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x + y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y + return y + + +def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0): + # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x + y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y + y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x + y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y + return y + + +def xyn2xy(x, w=640, h=640, padw=0, padh=0): + # Convert normalized segments into pixel segments, shape (n,2) + y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x) + y[:, 0] = w * x[:, 0] + padw # top left x + y[:, 1] = h * x[:, 1] + padh # top left y + return y + + +def segment2box(segment, width=640, height=640): + # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy) + x, y = segment.T # segment xy + inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height) + x, y, = x[inside], y[inside] + return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # cls, xyxy + + +def segments2boxes(segments): + # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh) + boxes = [] + for s in segments: + x, y = s.T # segment xy + boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy + return xyxy2xywh(np.array(boxes)) # cls, xywh + + +def resample_segments(segments, n=1000): + # Up-sample an (n,2) segment + for i, s in enumerate(segments): + x = np.linspace(0, len(s) - 1, n) + xp = np.arange(len(s)) + segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy + return segments + + +def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None): + # Rescale coords (xyxy) from img1_shape to img0_shape + if ratio_pad is None: # calculate from img0_shape + gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new + pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding + else: + gain = ratio_pad[0][0] + pad = ratio_pad[1] + + coords[:, [0, 2]] -= pad[0] # x padding + coords[:, [1, 3]] -= pad[1] # y padding + coords[:, :4] /= gain + clip_coords(coords, img0_shape) + return coords + + +def clip_coords(boxes, img_shape): + # Clip bounding xyxy bounding boxes to image shape (height, width) + boxes[:, 0].clamp_(0, img_shape[1]) # x1 + boxes[:, 1].clamp_(0, img_shape[0]) # y1 + boxes[:, 2].clamp_(0, img_shape[1]) # x2 + boxes[:, 3].clamp_(0, img_shape[0]) # y2 + + +def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7): + # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4 + box2 = box2.T + + # Get the coordinates of bounding boxes + if x1y1x2y2: # x1, y1, x2, y2 = box1 + b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] + b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] + else: # transform from xywh to xyxy + b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2 + b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2 + b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2 + b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2 + + # Intersection area + inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ + (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) + + # Union Area + w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps + w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps + union = w1 * h1 + w2 * h2 - inter + eps + + iou = inter / union + if GIoU or DIoU or CIoU: + cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width + ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height + if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 + c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared + rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared + if DIoU: + return iou - rho2 / c2 # DIoU + elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 + v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2) + with torch.no_grad(): + alpha = v / (v - iou + (1 + eps)) + return iou - (rho2 / c2 + v * alpha) # CIoU + else: # GIoU https://arxiv.org/pdf/1902.09630.pdf + c_area = cw * ch + eps # convex area + return iou - (c_area - union) / c_area # GIoU + else: + return iou # IoU + + +def box_iou(box1, box2): + # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py + """ + Return intersection-over-union (Jaccard index) of boxes. + Both sets of boxes are expected to be in (x1, y1, x2, y2) format. + Arguments: + box1 (Tensor[N, 4]) + box2 (Tensor[M, 4]) + Returns: + iou (Tensor[N, M]): the NxM matrix containing the pairwise + IoU values for every element in boxes1 and boxes2 + """ + + def box_area(box): + # box = 4xn + return (box[2] - box[0]) * (box[3] - box[1]) + + area1 = box_area(box1.T) + area2 = box_area(box2.T) + + # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) + inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) + return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter) + + +def wh_iou(wh1, wh2): + # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2 + wh1 = wh1[:, None] # [N,1,2] + wh2 = wh2[None] # [1,M,2] + inter = torch.min(wh1, wh2).prod(2) # [N,M] + return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter) + + +def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False, + labels=()): + """Runs Non-Maximum Suppression (NMS) on inference results + + Returns: + list of detections, on (n,6) tensor per image [xyxy, conf, cls] + """ + + nc = prediction.shape[2] - 5 # number of classes + xc = prediction[..., 4] > conf_thres # candidates + + # Settings + min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height + max_det = 300 # maximum number of detections per image + max_nms = 30000 # maximum number of boxes into torchvision.ops.nms() + time_limit = 10.0 # seconds to quit after + redundant = True # require redundant detections + multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img) + merge = False # use merge-NMS + + t = time.time() + output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0] + for xi, x in enumerate(prediction): # image index, image inference + # Apply constraints + # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height + x = x[xc[xi]] # confidence + + # Cat apriori labels if autolabelling + if labels and len(labels[xi]): + l = labels[xi] + v = torch.zeros((len(l), nc + 5), device=x.device) + v[:, :4] = l[:, 1:5] # box + v[:, 4] = 1.0 # conf + v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls + x = torch.cat((x, v), 0) + + # If none remain process next image + if not x.shape[0]: + continue + + # Compute conf + x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf + + # Box (center x, center y, width, height) to (x1, y1, x2, y2) + box = xywh2xyxy(x[:, :4]) + + # Detections matrix nx6 (xyxy, conf, cls) + if multi_label: + i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T + x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1) + else: # best class only + conf, j = x[:, 5:].max(1, keepdim=True) + x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres] + + # Filter by class + if classes is not None: + x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] + + # Apply finite constraint + # if not torch.isfinite(x).all(): + # x = x[torch.isfinite(x).all(1)] + + # Check shape + n = x.shape[0] # number of boxes + if not n: # no boxes + continue + elif n > max_nms: # excess boxes + x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence + + # Batched NMS + c = x[:, 5:6] * (0 if agnostic else max_wh) # classes + boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores + i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS + if i.shape[0] > max_det: # limit detections + i = i[:max_det] + if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean) + # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4) + iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix + weights = iou * scores[None] # box weights + x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes + if redundant: + i = i[iou.sum(1) > 1] # require redundancy + + output[xi] = x[i] + if (time.time() - t) > time_limit: + print(f'WARNING: NMS time limit {time_limit}s exceeded') + break # time limit exceeded + + return output + + +def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer() + # Strip optimizer from 'f' to finalize training, optionally save as 's' + x = torch.load(f, map_location=torch.device('cpu')) + if x.get('ema'): + x['model'] = x['ema'] # replace model with ema + for k in 'optimizer', 'training_results', 'wandb_id', 'ema', 'updates': # keys + x[k] = None + x['epoch'] = -1 + x['model'].half() # to FP16 + for p in x['model'].parameters(): + p.requires_grad = False + torch.save(x, s or f) + mb = os.path.getsize(s or f) / 1E6 # filesize + print(f"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB") + + +def print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''): + # Print mutation results to evolve.txt (for use with train.py --evolve) + a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys + b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values + c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3) + print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c)) + + if bucket: + url = 'gs://%s/evolve.txt' % bucket + if gsutil_getsize(url) > (os.path.getsize('evolve.txt') if os.path.exists('evolve.txt') else 0): + os.system('gsutil cp %s .' % url) # download evolve.txt if larger than local + + with open('evolve.txt', 'a') as f: # append result + f.write(c + b + '\n') + x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows + x = x[np.argsort(-fitness(x))] # sort + np.savetxt('evolve.txt', x, '%10.3g') # save sort by fitness + + # Save yaml + for i, k in enumerate(hyp.keys()): + hyp[k] = float(x[0, i + 7]) + with open(yaml_file, 'w') as f: + results = tuple(x[0, :7]) + c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3) + f.write('# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: ' % len(x) + c + '\n\n') + yaml.dump(hyp, f, sort_keys=False) + + if bucket: + os.system('gsutil cp evolve.txt %s gs://%s' % (yaml_file, bucket)) # upload + + +def apply_classifier(x, model, img, im0): + # applies a second stage classifier to yolo outputs + im0 = [im0] if isinstance(im0, np.ndarray) else im0 + for i, d in enumerate(x): # per image + if d is not None and len(d): + d = d.clone() + + # Reshape and pad cutouts + b = xyxy2xywh(d[:, :4]) # boxes + b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square + b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad + d[:, :4] = xywh2xyxy(b).long() + + # Rescale boxes from img_size to im0 size + scale_coords(img.shape[2:], d[:, :4], im0[i].shape) + + # Classes + pred_cls1 = d[:, 5].long() + ims = [] + for j, a in enumerate(d): # per item + cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])] + im = cv2.resize(cutout, (224, 224)) # BGR + # cv2.imwrite('test%i.jpg' % j, cutout) + + im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 + im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32 + im /= 255.0 # 0 - 255 to 0.0 - 1.0 + ims.append(im) + + pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction + x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections + + return x + + +def increment_path(path, exist_ok=True, sep=''): + # Increment path, i.e. runs/exp --> runs/exp{sep}0, runs/exp{sep}1 etc. + path = Path(path) # os-agnostic + if (path.exists() and exist_ok) or (not path.exists()): + return str(path) + else: + dirs = glob.glob(f"{path}{sep}*") # similar paths + matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs] + i = [int(m.groups()[0]) for m in matches if m] # indices + n = max(i) + 1 if i else 2 # increment number + return f"{path}{sep}{n}" # update path diff --git a/Y5_old/utils/google_app_engine/Dockerfile b/Y5_old/utils/google_app_engine/Dockerfile new file mode 100755 index 0000000..0155618 --- /dev/null +++ b/Y5_old/utils/google_app_engine/Dockerfile @@ -0,0 +1,25 @@ +FROM gcr.io/google-appengine/python + +# Create a virtualenv for dependencies. This isolates these packages from +# system-level packages. +# Use -p python3 or -p python3.7 to select python version. Default is version 2. +RUN virtualenv /env -p python3 + +# Setting these environment variables are the same as running +# source /env/bin/activate. +ENV VIRTUAL_ENV /env +ENV PATH /env/bin:$PATH + +RUN apt-get update && apt-get install -y python-opencv + +# Copy the application's requirements.txt and run pip to install all +# dependencies into the virtualenv. +ADD requirements.txt /app/requirements.txt +RUN pip install -r /app/requirements.txt + +# Add the application source code. +ADD . /app + +# Run a WSGI server to serve the application. gunicorn must be declared as +# a dependency in requirements.txt. +CMD gunicorn -b :$PORT main:app diff --git a/Y5_old/utils/google_app_engine/additional_requirements.txt b/Y5_old/utils/google_app_engine/additional_requirements.txt new file mode 100755 index 0000000..5fcc305 --- /dev/null +++ b/Y5_old/utils/google_app_engine/additional_requirements.txt @@ -0,0 +1,4 @@ +# add these requirements in your app on top of the existing ones +pip==18.1 +Flask==1.0.2 +gunicorn==19.9.0 diff --git a/Y5_old/utils/google_app_engine/app.yaml b/Y5_old/utils/google_app_engine/app.yaml new file mode 100755 index 0000000..ac29d10 --- /dev/null +++ b/Y5_old/utils/google_app_engine/app.yaml @@ -0,0 +1,14 @@ +runtime: custom +env: flex + +service: yolov5app + +liveness_check: + initial_delay_sec: 600 + +manual_scaling: + instances: 1 +resources: + cpu: 1 + memory_gb: 4 + disk_size_gb: 20 \ No newline at end of file diff --git a/Y5/utils/google_utils.py b/Y5_old/utils/google_utils.py similarity index 100% rename from Y5/utils/google_utils.py rename to Y5_old/utils/google_utils.py diff --git a/Y5_old/utils/loss.py b/Y5_old/utils/loss.py new file mode 100755 index 0000000..82c3271 --- /dev/null +++ b/Y5_old/utils/loss.py @@ -0,0 +1,216 @@ +# Loss functions + +import torch +import torch.nn as nn + +from Y5.utils.general import bbox_iou +from Y5.utils.torch_utils import is_parallel + + +def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441 + # return positive, negative label smoothing BCE targets + return 1.0 - 0.5 * eps, 0.5 * eps + + +class BCEBlurWithLogitsLoss(nn.Module): + # BCEwithLogitLoss() with reduced missing label effects. + def __init__(self, alpha=0.05): + super(BCEBlurWithLogitsLoss, self).__init__() + self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss() + self.alpha = alpha + + def forward(self, pred, true): + loss = self.loss_fcn(pred, true) + pred = torch.sigmoid(pred) # prob from logits + dx = pred - true # reduce only missing label effects + # dx = (pred - true).abs() # reduce missing label and false label effects + alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4)) + loss *= alpha_factor + return loss.mean() + + +class FocalLoss(nn.Module): + # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) + def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): + super(FocalLoss, self).__init__() + self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() + self.gamma = gamma + self.alpha = alpha + self.reduction = loss_fcn.reduction + self.loss_fcn.reduction = 'none' # required to apply FL to each element + + def forward(self, pred, true): + loss = self.loss_fcn(pred, true) + # p_t = torch.exp(-loss) + # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability + + # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py + pred_prob = torch.sigmoid(pred) # prob from logits + p_t = true * pred_prob + (1 - true) * (1 - pred_prob) + alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) + modulating_factor = (1.0 - p_t) ** self.gamma + loss *= alpha_factor * modulating_factor + + if self.reduction == 'mean': + return loss.mean() + elif self.reduction == 'sum': + return loss.sum() + else: # 'none' + return loss + + +class QFocalLoss(nn.Module): + # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) + def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): + super(QFocalLoss, self).__init__() + self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() + self.gamma = gamma + self.alpha = alpha + self.reduction = loss_fcn.reduction + self.loss_fcn.reduction = 'none' # required to apply FL to each element + + def forward(self, pred, true): + loss = self.loss_fcn(pred, true) + + pred_prob = torch.sigmoid(pred) # prob from logits + alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) + modulating_factor = torch.abs(true - pred_prob) ** self.gamma + loss *= alpha_factor * modulating_factor + + if self.reduction == 'mean': + return loss.mean() + elif self.reduction == 'sum': + return loss.sum() + else: # 'none' + return loss + + +class ComputeLoss: + # Compute losses + def __init__(self, model, autobalance=False): + super(ComputeLoss, self).__init__() + device = next(model.parameters()).device # get model device + h = model.hyp # hyperparameters + + # Define criteria + BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device)) + BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device)) + + # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3 + self.cp, self.cn = smooth_BCE(eps=0.0) + + # Focal loss + g = h['fl_gamma'] # focal loss gamma + if g > 0: + BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g) + + det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module + self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7 + self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index + self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance + for k in 'na', 'nc', 'nl', 'anchors': + setattr(self, k, getattr(det, k)) + + def __call__(self, p, targets): # predictions, targets, model + device = targets.device + lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device) + tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets + + # Losses + for i, pi in enumerate(p): # layer index, layer predictions + b, a, gj, gi = indices[i] # image, anchor, gridy, gridx + tobj = torch.zeros_like(pi[..., 0], device=device) # target obj + + n = b.shape[0] # number of targets + if n: + ps = pi[b, a, gj, gi] # prediction subset corresponding to targets + + # Regression + pxy = ps[:, :2].sigmoid() * 2. - 0.5 + pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i] + pbox = torch.cat((pxy, pwh), 1) # predicted box + iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target) + lbox += (1.0 - iou).mean() # iou loss + + # Objectness + tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio + + # Classification + if self.nc > 1: # cls loss (only if multiple classes) + t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets + t[range(n), tcls[i]] = self.cp + lcls += self.BCEcls(ps[:, 5:], t) # BCE + + # Append targets to text file + # with open('targets.txt', 'a') as file: + # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)] + + obji = self.BCEobj(pi[..., 4], tobj) + lobj += obji * self.balance[i] # obj loss + if self.autobalance: + self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item() + + if self.autobalance: + self.balance = [x / self.balance[self.ssi] for x in self.balance] + lbox *= self.hyp['box'] + lobj *= self.hyp['obj'] + lcls *= self.hyp['cls'] + bs = tobj.shape[0] # batch size + + loss = lbox + lobj + lcls + return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach() + + def build_targets(self, p, targets): + # Build targets for compute_loss(), input targets(image,class,x,y,w,h) + na, nt = self.na, targets.shape[0] # number of anchors, targets + tcls, tbox, indices, anch = [], [], [], [] + gain = torch.ones(7, device=targets.device) # normalized to gridspace gain + ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) + targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices + + g = 0.5 # bias + off = torch.tensor([[0, 0], + [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m + # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm + ], device=targets.device).float() * g # offsets + + for i in range(self.nl): + anchors = self.anchors[i] + gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain + + # Match targets to anchors + t = targets * gain + if nt: + # Matches + r = t[:, :, 4:6] / anchors[:, None] # wh ratio + j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare + # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2)) + t = t[j] # filter + + # Offsets + gxy = t[:, 2:4] # grid xy + gxi = gain[[2, 3]] - gxy # inverse + j, k = ((gxy % 1. < g) & (gxy > 1.)).T + l, m = ((gxi % 1. < g) & (gxi > 1.)).T + j = torch.stack((torch.ones_like(j), j, k, l, m)) + t = t.repeat((5, 1, 1))[j] + offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] + else: + t = targets[0] + offsets = 0 + + # Define + b, c = t[:, :2].long().T # image, class + gxy = t[:, 2:4] # grid xy + gwh = t[:, 4:6] # grid wh + gij = (gxy - offsets).long() + gi, gj = gij.T # grid xy indices + + # Append + a = t[:, 6].long() # anchor indices + indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices + tbox.append(torch.cat((gxy - gij, gwh), 1)) # box + anch.append(anchors[a]) # anchors + tcls.append(c) # class + + return tcls, tbox, indices, anch diff --git a/Y5_old/utils/metrics.py b/Y5_old/utils/metrics.py new file mode 100755 index 0000000..666b8c7 --- /dev/null +++ b/Y5_old/utils/metrics.py @@ -0,0 +1,223 @@ +# Model validation metrics + +from pathlib import Path + +import matplotlib.pyplot as plt +import numpy as np +import torch + +from . import general + + +def fitness(x): + # Model fitness as a weighted combination of metrics + w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95] + return (x[:, :4] * w).sum(1) + + +def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()): + """ Compute the average precision, given the recall and precision curves. + Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. + # Arguments + tp: True positives (nparray, nx1 or nx10). + conf: Objectness value from 0-1 (nparray). + pred_cls: Predicted object classes (nparray). + target_cls: True object classes (nparray). + plot: Plot precision-recall curve at mAP@0.5 + save_dir: Plot save directory + # Returns + The average precision as computed in py-faster-rcnn. + """ + + # Sort by objectness + i = np.argsort(-conf) + tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] + + # Find unique classes + unique_classes = np.unique(target_cls) + nc = unique_classes.shape[0] # number of classes, number of detections + + # Create Precision-Recall curve and compute AP for each class + px, py = np.linspace(0, 1, 1000), [] # for plotting + ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000)) + for ci, c in enumerate(unique_classes): + i = pred_cls == c + n_l = (target_cls == c).sum() # number of labels + n_p = i.sum() # number of predictions + + if n_p == 0 or n_l == 0: + continue + else: + # Accumulate FPs and TPs + fpc = (1 - tp[i]).cumsum(0) + tpc = tp[i].cumsum(0) + + # Recall + recall = tpc / (n_l + 1e-16) # recall curve + r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases + + # Precision + precision = tpc / (tpc + fpc) # precision curve + p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score + + # AP from recall-precision curve + for j in range(tp.shape[1]): + ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j]) + if plot and j == 0: + py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5 + + # Compute F1 (harmonic mean of precision and recall) + f1 = 2 * p * r / (p + r + 1e-16) + if plot: + plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names) + plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1') + plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision') + plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall') + + i = f1.mean(0).argmax() # max F1 index + return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32') + + +def compute_ap(recall, precision): + """ Compute the average precision, given the recall and precision curves + # Arguments + recall: The recall curve (list) + precision: The precision curve (list) + # Returns + Average precision, precision curve, recall curve + """ + + # Append sentinel values to beginning and end + mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01])) + mpre = np.concatenate(([1.], precision, [0.])) + + # Compute the precision envelope + mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) + + # Integrate area under curve + method = 'interp' # methods: 'continuous', 'interp' + if method == 'interp': + x = np.linspace(0, 1, 101) # 101-point interp (COCO) + ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate + else: # 'continuous' + i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes + ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve + + return ap, mpre, mrec + + +class ConfusionMatrix: + # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix + def __init__(self, nc, conf=0.25, iou_thres=0.45): + self.matrix = np.zeros((nc + 1, nc + 1)) + self.nc = nc # number of classes + self.conf = conf + self.iou_thres = iou_thres + + def process_batch(self, detections, labels): + """ + Return intersection-over-union (Jaccard index) of boxes. + Both sets of boxes are expected to be in (x1, y1, x2, y2) format. + Arguments: + detections (Array[N, 6]), x1, y1, x2, y2, conf, class + labels (Array[M, 5]), class, x1, y1, x2, y2 + Returns: + None, updates confusion matrix accordingly + """ + detections = detections[detections[:, 4] > self.conf] + gt_classes = labels[:, 0].int() + detection_classes = detections[:, 5].int() + iou = general.box_iou(labels[:, 1:], detections[:, :4]) + + x = torch.where(iou > self.iou_thres) + if x[0].shape[0]: + matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() + if x[0].shape[0] > 1: + matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 1], return_index=True)[1]] + matches = matches[matches[:, 2].argsort()[::-1]] + matches = matches[np.unique(matches[:, 0], return_index=True)[1]] + else: + matches = np.zeros((0, 3)) + + n = matches.shape[0] > 0 + m0, m1, _ = matches.transpose().astype(np.int16) + for i, gc in enumerate(gt_classes): + j = m0 == i + if n and sum(j) == 1: + self.matrix[gc, detection_classes[m1[j]]] += 1 # correct + else: + self.matrix[self.nc, gc] += 1 # background FP + + if n: + for i, dc in enumerate(detection_classes): + if not any(m1 == i): + self.matrix[dc, self.nc] += 1 # background FN + + def matrix(self): + return self.matrix + + def plot(self, save_dir='', names=()): + try: + import seaborn as sn + + array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize + array[array < 0.005] = np.nan # don't annotate (would appear as 0.00) + + fig = plt.figure(figsize=(12, 9), tight_layout=True) + sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size + labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels + sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True, + xticklabels=names + ['background FP'] if labels else "auto", + yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1)) + fig.axes[0].set_xlabel('True') + fig.axes[0].set_ylabel('Predicted') + fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250) + except Exception as e: + pass + + def print(self): + for i in range(self.nc + 1): + print(' '.join(map(str, self.matrix[i]))) + + +# Plots ---------------------------------------------------------------------------------------------------------------- + +def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()): + # Precision-recall curve + fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) + py = np.stack(py, axis=1) + + if 0 < len(names) < 21: # display per-class legend if < 21 classes + for i, y in enumerate(py.T): + ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision) + else: + ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision) + + ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean()) + ax.set_xlabel('Recall') + ax.set_ylabel('Precision') + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") + fig.savefig(Path(save_dir), dpi=250) + + +def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'): + # Metric-confidence curve + fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) + + if 0 < len(names) < 21: # display per-class legend if < 21 classes + for i, y in enumerate(py): + ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric) + else: + ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric) + + y = py.mean(0) + ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}') + ax.set_xlabel(xlabel) + ax.set_ylabel(ylabel) + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") + fig.savefig(Path(save_dir), dpi=250) diff --git a/Y5_old/utils/plots.py b/Y5_old/utils/plots.py new file mode 100755 index 0000000..393fa2e --- /dev/null +++ b/Y5_old/utils/plots.py @@ -0,0 +1,477 @@ +# Plotting utils + +import glob +import math +import os +import random +from copy import copy +from pathlib import Path + +import cv2 +import matplotlib +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import seaborn as sns +import torch +import yaml +from common import global_para as gp +from PIL import Image, ImageDraw, ImageFont +from scipy.signal import butter, filtfilt + +from Y5.utils.general import xywh2xyxy, xyxy2xywh +from Y5.utils.metrics import fitness +from cv2AddChineseText import cv2AddChineseText +# Settings +matplotlib.rc('font', **{'size': 11}) +matplotlib.use('Agg') # for writing to files only + + +def color_list(): + # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb + def hex2rgb(h): + return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4)) + + return [hex2rgb(h) for h in matplotlib.colors.TABLEAU_COLORS.values()] # or BASE_ (8), CSS4_ (148), XKCD_ (949) + + +def hist2d(x, y, n=100): + # 2d histogram used in labels.png and evolve.png + xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n) + hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges)) + xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1) + yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1) + return np.log(hist[xidx, yidx]) + + +def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5): + # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy + def butter_lowpass(cutoff, fs, order): + nyq = 0.5 * fs + normal_cutoff = cutoff / nyq + return butter(order, normal_cutoff, btype='low', analog=False) + + b, a = butter_lowpass(cutoff, fs, order=order) + return filtfilt(b, a, data) # forward-backward filter + + +def plot_one_box1(x, draw, height,width,color=None, label=None, line_thickness=3): + # Plots one bounding box on image img + tl = line_thickness or round(0.002 * (height + width) / 2) + 1 # line/font thickness + color = color or tuple(random.randint(0, 255) for _ in range(3)) + c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) + #ÏÔʾindex + + + # draw.text((c1[0]-20, c1[1]), str(Index), (0, 0, 255),font=fontStyle) + draw.rectangle((c1, c2), fill=None, outline=color, width=tl) + if label: + tf = max(tl - 1, 1) # font thickness + t_size = cv2.getTextSize(label, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=gp.fontScale , thickness=tl)[0] + print(label,t_size[0],t_size[1]) + c1 = c1[0],c1[1]-t_size[1] + c2 = c1[0] + t_size[0], c1[1]+t_size[1] + draw.rectangle((c1, c2), fill=color, outline=color, width=tl) + #cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled + #cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) + #if not label == None: + + draw = cv2AddChineseText(draw, label,(c1[0], c1[1]), textColor = (225, 255, 255), textSize=tf*17) + #img = cv2AddChineseText(img, "ÊýÁ¿: {}".format(str("011")), (2000,100), textColor=(0, 255, 0), textSize=80) + return draw +def plot_one_box1tcopy(x, img, color=None, label=None, line_thickness=3): + # Plots one bounding box on image img + tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness + color = color or [random.randint(0, 255) for _ in range(3)] + c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) + cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA) + if label: + tf = max(tl - 1, 1) # font thickness + t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] + c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3 + cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled + cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) + return img +def plot_one_box(x, draw, height,width,color=None, label=None, Index = None, line_thickness=3): + # Plots one bounding box on image img + tl = line_thickness or round(0.002 * (height + width) / 2) + 1 # line/font thickness + color = color or tuple(random.randint(0, 255) for _ in range(3)) + c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) + #ÏÔʾindex + + + # draw.text((c1[0]-20, c1[1]), str(Index), (0, 0, 255),font=fontStyle) + draw.rectangle((c1, c2), fill=None, outline=color, width=tl) + if label: + tf = max(tl - 1, 1) # font thickness + t_size = cv2.getTextSize(label, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=gp.fontScale , thickness=tl)[0] + print(label,t_size[0],t_size[1]) + c1 = c1[0],c1[1]-t_size[1] + c2 = c1[0] + t_size[0], c1[1]+t_size[1] + draw.rectangle((c1, c2), fill=color, outline=color, width=tl) + #cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled + #cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) + #if not label == None: + + draw = cv2AddChineseText(draw, label,(c1[0], c1[1]), textColor = (225, 255, 255), textSize=tf*17) + #img = cv2AddChineseText(img, "ÊýÁ¿: {}".format(str("011")), (2000,100), textColor=(0, 255, 0), textSize=80) + return draw + +def plot_one_box_PIL(box, img, color=None, label=None, line_thickness=None): + img = Image.fromarray(img) + draw = ImageDraw.Draw(img) + line_thickness = line_thickness or max(int(min(img.size) / 200), 2) + draw.rectangle(box, width=line_thickness, outline=tuple(color)) # plot + if label: + fontsize = max(round(max(img.size) / 40), 12) + font = ImageFont.truetype("Arial.ttf", fontsize) + txt_width, txt_height = font.getsize(label) + draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=tuple(color)) + draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font) + return np.asarray(img) + + +def plot_wh_methods(): # from utils.plots import *; plot_wh_methods() + # Compares the two methods for width-height anchor multiplication + # https://github.com/ultralytics/yolov3/issues/168 + x = np.arange(-4.0, 4.0, .1) + ya = np.exp(x) + yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2 + + fig = plt.figure(figsize=(6, 3), tight_layout=True) + plt.plot(x, ya, '.-', label='YOLOv3') + plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2') + plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6') + plt.xlim(left=-4, right=4) + plt.ylim(bottom=0, top=6) + plt.xlabel('input') + plt.ylabel('output') + plt.grid() + plt.legend() + fig.savefig('comparison.png', dpi=200) + + +def output_to_target(output): + # Convert model output to target format [batch_id, class_id, x, y, w, h, conf] + targets = [] + for i, o in enumerate(output): + for *box, conf, cls in o.cpu().numpy(): + targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf]) + return np.array(targets) + + +def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16): + # Plot image grid with labels + + if isinstance(images, torch.Tensor): + images = images.cpu().float().numpy() + if isinstance(targets, torch.Tensor): + targets = targets.cpu().numpy() + + # un-normalise + if np.max(images[0]) <= 1: + images *= 255 + + tl = 3 # line thickness + tf = max(tl - 1, 1) # font thickness + bs, _, h, w = images.shape # batch size, _, height, width + bs = min(bs, max_subplots) # limit plot images + ns = np.ceil(bs ** 0.5) # number of subplots (square) + + # Check if we should resize + scale_factor = max_size / max(h, w) + if scale_factor < 1: + h = math.ceil(scale_factor * h) + w = math.ceil(scale_factor * w) + + colors = color_list() # list of colors + mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init + for i, img in enumerate(images): + if i == max_subplots: # if last batch has fewer images than we expect + break + + block_x = int(w * (i // ns)) + block_y = int(h * (i % ns)) + + img = img.transpose(1, 2, 0) + if scale_factor < 1: + img = cv2.resize(img, (w, h)) + + mosaic[block_y:block_y + h, block_x:block_x + w, :] = img + if len(targets) > 0: + image_targets = targets[targets[:, 0] == i] + boxes = xywh2xyxy(image_targets[:, 2:6]).T + classes = image_targets[:, 1].astype('int') + labels = image_targets.shape[1] == 6 # labels if no conf column + conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred) + + if boxes.shape[1]: + if boxes.max() <= 1.01: # if normalized with tolerance 0.01 + boxes[[0, 2]] *= w # scale to pixels + boxes[[1, 3]] *= h + elif scale_factor < 1: # absolute coords need scale if image scales + boxes *= scale_factor + boxes[[0, 2]] += block_x + boxes[[1, 3]] += block_y + for j, box in enumerate(boxes.T): + cls = int(classes[j]) + color = colors[cls % len(colors)] + cls = names[cls] if names else cls + if labels or conf[j] > 0.25: # 0.25 conf thresh + label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j]) + plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl) + + # Draw image filename labels + if paths: + label = Path(paths[i]).name[:40] # trim to 40 char + t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] + cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf, + lineType=cv2.LINE_AA) + + # Image border + cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3) + + if fname: + r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size + mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA) + # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save + Image.fromarray(mosaic).save(fname) # PIL save + return mosaic + + +def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''): + # Plot LR simulating training for full epochs + optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals + y = [] + for _ in range(epochs): + scheduler.step() + y.append(optimizer.param_groups[0]['lr']) + plt.plot(y, '.-', label='LR') + plt.xlabel('epoch') + plt.ylabel('LR') + plt.grid() + plt.xlim(0, epochs) + plt.ylim(0) + plt.savefig(Path(save_dir) / 'LR.png', dpi=200) + plt.close() + + +def plot_test_txt(): # from utils.plots import *; plot_test() + # Plot test.txt histograms + x = np.loadtxt('test.txt', dtype=np.float32) + box = xyxy2xywh(x[:, :4]) + cx, cy = box[:, 0], box[:, 1] + + fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True) + ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0) + ax.set_aspect('equal') + plt.savefig('hist2d.png', dpi=300) + + fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True) + ax[0].hist(cx, bins=600) + ax[1].hist(cy, bins=600) + plt.savefig('hist1d.png', dpi=200) + + +def plot_targets_txt(): # from utils.plots import *; plot_targets_txt() + # Plot targets.txt histograms + x = np.loadtxt('targets.txt', dtype=np.float32).T + s = ['x targets', 'y targets', 'width targets', 'height targets'] + fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True) + ax = ax.ravel() + for i in range(4): + ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std())) + ax[i].legend() + ax[i].set_title(s[i]) + plt.savefig('targets.jpg', dpi=200) + + +def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt() + # Plot study.txt generated by test.py + fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True) + # ax = ax.ravel() + + fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True) + # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s', 'yolov5m', 'yolov5l', 'yolov5x']]: + for f in sorted(Path(path).glob('study*.txt')): + y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T + x = np.arange(y.shape[1]) if x is None else np.array(x) + s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)'] + # for i in range(7): + # ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8) + # ax[i].set_title(s[i]) + + j = y[3].argmax() + 1 + ax2.plot(y[6, :j], y[3, :j] * 1E2, '.-', linewidth=2, markersize=8, + label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO')) + + ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5], + 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet') + + ax2.grid(alpha=0.2) + ax2.set_yticks(np.arange(20, 60, 5)) + ax2.set_xlim(0, 30) + ax2.set_ylim(30, 55) + ax2.set_xlabel('GPU Speed (ms/img)') + ax2.set_ylabel('COCO AP val') + ax2.legend(loc='lower right') + plt.savefig(str(Path(path).name) + '.png', dpi=300) + + +def plot_labels(labels, save_dir=Path(''), loggers=None): + # plot dataset labels + print('Plotting labels... ') + c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes + nc = int(c.max() + 1) # number of classes + colors = color_list() + x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height']) + + # seaborn correlogram + sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9)) + plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200) + plt.close() + + # matplotlib labels + matplotlib.use('svg') # faster + ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel() + ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8) + ax[0].set_xlabel('classes') + sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9) + sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9) + + # rectangles + labels[:, 1:3] = 0.5 # center + labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000 + img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255) + for cls, *box in labels[:1000]: + ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10]) # plot + ax[1].imshow(img) + ax[1].axis('off') + + for a in [0, 1, 2, 3]: + for s in ['top', 'right', 'left', 'bottom']: + ax[a].spines[s].set_visible(False) + + plt.savefig(save_dir / 'labels.jpg', dpi=200) + matplotlib.use('Agg') + plt.close() + + # loggers + for k, v in loggers.items() or {}: + if k == 'wandb' and v: + v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False) + + +def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution() + # Plot hyperparameter evolution results in evolve.txt + with open(yaml_file) as f: + hyp = yaml.load(f, Loader=yaml.SafeLoader) + x = np.loadtxt('evolve.txt', ndmin=2) + f = fitness(x) + # weights = (f - f.min()) ** 2 # for weighted results + plt.figure(figsize=(10, 12), tight_layout=True) + matplotlib.rc('font', **{'size': 8}) + for i, (k, v) in enumerate(hyp.items()): + y = x[:, i + 7] + # mu = (y * weights).sum() / weights.sum() # best weighted result + mu = y[f.argmax()] # best single result + plt.subplot(6, 5, i + 1) + plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none') + plt.plot(mu, f.max(), 'k+', markersize=15) + plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters + if i % 5 != 0: + plt.yticks([]) + print('%15s: %.3g' % (k, mu)) + plt.savefig('evolve.png', dpi=200) + print('\nPlot saved as evolve.png') + + +def profile_idetection(start=0, stop=0, labels=(), save_dir=''): + # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection() + ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel() + s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS'] + files = list(Path(save_dir).glob('frames*.txt')) + for fi, f in enumerate(files): + try: + results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows + n = results.shape[1] # number of rows + x = np.arange(start, min(stop, n) if stop else n) + results = results[:, x] + t = (results[0] - results[0].min()) # set t0=0s + results[0] = x + for i, a in enumerate(ax): + if i < len(results): + label = labels[fi] if len(labels) else f.stem.replace('frames_', '') + a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5) + a.set_title(s[i]) + a.set_xlabel('time (s)') + # if fi == len(files) - 1: + # a.set_ylim(bottom=0) + for side in ['top', 'right']: + a.spines[side].set_visible(False) + else: + a.remove() + except Exception as e: + print('Warning: Plotting error for %s; %s' % (f, e)) + + ax[1].legend() + plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200) + + +def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay() + # Plot training 'results*.txt', overlaying train and val losses + s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends + t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles + for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')): + results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T + n = results.shape[1] # number of rows + x = range(start, min(stop, n) if stop else n) + fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True) + ax = ax.ravel() + for i in range(5): + for j in [i, i + 5]: + y = results[j, x] + ax[i].plot(x, y, marker='.', label=s[j]) + # y_smooth = butter_lowpass_filtfilt(y) + # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j]) + + ax[i].set_title(t[i]) + ax[i].legend() + ax[i].set_ylabel(f) if i == 0 else None # add filename + fig.savefig(f.replace('.txt', '.png'), dpi=200) + + +def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''): + # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp') + fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True) + ax = ax.ravel() + s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall', + 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95'] + if bucket: + # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id] + files = ['results%g.txt' % x for x in id] + c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id) + os.system(c) + else: + files = list(Path(save_dir).glob('results*.txt')) + assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir) + for fi, f in enumerate(files): + try: + results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T + n = results.shape[1] # number of rows + x = range(start, min(stop, n) if stop else n) + for i in range(10): + y = results[i, x] + if i in [0, 1, 2, 5, 6, 7]: + y[y == 0] = np.nan # don't show zero loss values + # y /= y[0] # normalize + label = labels[fi] if len(labels) else f.stem + ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8) + ax[i].set_title(s[i]) + # if i in [5, 6, 7]: # share train and val loss y axes + # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5]) + except Exception as e: + print('Warning: Plotting error for %s; %s' % (f, e)) + + ax[1].legend() + fig.savefig(Path(save_dir) / 'results.png', dpi=200) diff --git a/Y5_old/utils/torch_utils.py b/Y5_old/utils/torch_utils.py new file mode 100755 index 0000000..1b1cc20 --- /dev/null +++ b/Y5_old/utils/torch_utils.py @@ -0,0 +1,294 @@ +# PyTorch utils + +import logging +import math +import os +import subprocess +import time +from contextlib import contextmanager +from copy import deepcopy +from pathlib import Path + +import torch +import torch.backends.cudnn as cudnn +import torch.nn as nn +import torch.nn.functional as F +import torchvision + +try: + import thop # for FLOPS computation +except ImportError: + thop = None +logger = logging.getLogger(__name__) + + +@contextmanager +def torch_distributed_zero_first(local_rank: int): + """ + Decorator to make all processes in distributed training wait for each local_master to do something. + """ + if local_rank not in [-1, 0]: + torch.distributed.barrier() + yield + if local_rank == 0: + torch.distributed.barrier() + + +def init_torch_seeds(seed=0): + # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html + torch.manual_seed(seed) + if seed == 0: # slower, more reproducible + cudnn.benchmark, cudnn.deterministic = False, True + else: # faster, less reproducible + cudnn.benchmark, cudnn.deterministic = True, False + + +def git_describe(): + # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe + if Path('.git').exists(): + return subprocess.check_output('git describe --tags --long --always', shell=True).decode('utf-8')[:-1] + else: + return '' + + +def select_device(device='', batch_size=None): + # device = 'cpu' or '0' or '0,1,2,3' + s = f'YOLOv5 {git_describe()} torch {torch.__version__} ' # string + cpu = device.lower() == 'cpu' + if cpu: + os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False + elif device: # non-cpu device requested + os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable + assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability + + cuda = not cpu and torch.cuda.is_available() + if cuda: + n = torch.cuda.device_count() + if n > 1 and batch_size: # check that batch_size is compatible with device_count + assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}' + space = ' ' * len(s) + for i, d in enumerate(device.split(',') if device else range(n)): + p = torch.cuda.get_device_properties(i) + s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB + else: + s += 'CPU\n' + + logger.info(s) # skip a line + return torch.device('cuda:0' if cuda else 'cpu') + + +def time_synchronized(): + # pytorch-accurate time + if torch.cuda.is_available(): + torch.cuda.synchronize() + return time.time() + + +def profile(x, ops, n=100, device=None): + # profile a pytorch module or list of modules. Example usage: + # x = torch.randn(16, 3, 640, 640) # input + # m1 = lambda x: x * torch.sigmoid(x) + # m2 = nn.SiLU() + # profile(x, [m1, m2], n=100) # profile speed over 100 iterations + + device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') + x = x.to(device) + x.requires_grad = True + print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '') + print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}") + for m in ops if isinstance(ops, list) else [ops]: + m = m.to(device) if hasattr(m, 'to') else m # device + m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type + dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward + try: + flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS + except: + flops = 0 + + for _ in range(n): + t[0] = time_synchronized() + y = m(x) + t[1] = time_synchronized() + try: + _ = y.sum().backward() + t[2] = time_synchronized() + except: # no backward method + t[2] = float('nan') + dtf += (t[1] - t[0]) * 1000 / n # ms per op forward + dtb += (t[2] - t[1]) * 1000 / n # ms per op backward + + s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' + s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list' + p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters + print(f'{p:12.4g}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}') + + +def is_parallel(model): + return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) + + +def intersect_dicts(da, db, exclude=()): + # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values + return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape} + + +def initialize_weights(model): + for m in model.modules(): + t = type(m) + if t is nn.Conv2d: + pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') + elif t is nn.BatchNorm2d: + m.eps = 1e-3 + m.momentum = 0.03 + elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]: + m.inplace = True + + +def find_modules(model, mclass=nn.Conv2d): + # Finds layer indices matching module class 'mclass' + return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)] + + +def sparsity(model): + # Return global model sparsity + a, b = 0., 0. + for p in model.parameters(): + a += p.numel() + b += (p == 0).sum() + return b / a + + +def prune(model, amount=0.3): + # Prune model to requested global sparsity + import torch.nn.utils.prune as prune + print('Pruning model... ', end='') + for name, m in model.named_modules(): + if isinstance(m, nn.Conv2d): + prune.l1_unstructured(m, name='weight', amount=amount) # prune + prune.remove(m, 'weight') # make permanent + print(' %.3g global sparsity' % sparsity(model)) + + +def fuse_conv_and_bn(conv, bn): + # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ + fusedconv = nn.Conv2d(conv.in_channels, + conv.out_channels, + kernel_size=conv.kernel_size, + stride=conv.stride, + padding=conv.padding, + groups=conv.groups, + bias=True).requires_grad_(False).to(conv.weight.device) + + # prepare filters + w_conv = conv.weight.clone().view(conv.out_channels, -1) + w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) + fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size())) + + # prepare spatial bias + b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias + b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) + fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) + + return fusedconv + + +def model_info(model, verbose=False, img_size=640): + # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320] + n_p = sum(x.numel() for x in model.parameters()) # number parameters + n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients + if verbose: + print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma')) + for i, (name, p) in enumerate(model.named_parameters()): + name = name.replace('module_list.', '') + print('%5g %40s %9s %12g %20s %10.3g %10.3g' % + (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) + + try: # FLOPS + from thop import profile + stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32 + img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input + flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS + img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float + fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS + except (ImportError, Exception): + fs = '' + + logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}") + + +def load_classifier(name='resnet101', n=2): + # Loads a pretrained model reshaped to n-class output + model = torchvision.models.__dict__[name](pretrained=True) + + # ResNet model properties + # input_size = [3, 224, 224] + # input_space = 'RGB' + # input_range = [0, 1] + # mean = [0.485, 0.456, 0.406] + # std = [0.229, 0.224, 0.225] + + # Reshape output to n classes + filters = model.fc.weight.shape[1] + model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True) + model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True) + model.fc.out_features = n + return model + + +def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) + # scales img(bs,3,y,x) by ratio constrained to gs-multiple + if ratio == 1.0: + return img + else: + h, w = img.shape[2:] + s = (int(h * ratio), int(w * ratio)) # new size + img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize + if not same_shape: # pad/crop img + h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)] + return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean + + +def copy_attr(a, b, include=(), exclude=()): + # Copy attributes from b to a, options to only include [...] and to exclude [...] + for k, v in b.__dict__.items(): + if (len(include) and k not in include) or k.startswith('_') or k in exclude: + continue + else: + setattr(a, k, v) + + +class ModelEMA: + """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models + Keep a moving average of everything in the model state_dict (parameters and buffers). + This is intended to allow functionality like + https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage + A smoothed version of the weights is necessary for some training schemes to perform well. + This class is sensitive where it is initialized in the sequence of model init, + GPU assignment and distributed training wrappers. + """ + + def __init__(self, model, decay=0.9999, updates=0): + # Create EMA + self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA + # if next(model.parameters()).device.type != 'cpu': + # self.ema.half() # FP16 EMA + self.updates = updates # number of EMA updates + self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs) + for p in self.ema.parameters(): + p.requires_grad_(False) + + def update(self, model): + # Update EMA parameters + with torch.no_grad(): + self.updates += 1 + d = self.decay(self.updates) + + msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict + for k, v in self.ema.state_dict().items(): + if v.dtype.is_floating_point: + v *= d + v += (1. - d) * msd[k].detach() + + def update_attr(self, model, include=(), exclude=('process_group', 'reducer')): + # Update EMA attributes + copy_attr(self.ema, model, include, exclude) diff --git a/Y5_old/utils/wandb_logging/__init__.py b/Y5_old/utils/wandb_logging/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/Y5/utils/wandb_logging/log_dataset.py b/Y5_old/utils/wandb_logging/log_dataset.py similarity index 100% rename from Y5/utils/wandb_logging/log_dataset.py rename to Y5_old/utils/wandb_logging/log_dataset.py diff --git a/Y5/utils/wandb_logging/wandb_utils.py b/Y5_old/utils/wandb_logging/wandb_utils.py similarity index 100% rename from Y5/utils/wandb_logging/wandb_utils.py rename to Y5_old/utils/wandb_logging/wandb_utils.py diff --git a/__pycache__/Hatcher_cam.cpython-36.pyc b/__pycache__/Hatcher_cam.cpython-36.pyc old mode 100644 new mode 100755 diff --git a/__pycache__/Hatcher_red.cpython-36.pyc b/__pycache__/Hatcher_red.cpython-36.pyc old mode 100644 new mode 100755 diff --git a/__pycache__/PlayVideo.cpython-35.pyc b/__pycache__/PlayVideo.cpython-35.pyc old mode 100644 new mode 100755 diff --git a/__pycache__/System_I.cpython-35.pyc b/__pycache__/System_I.cpython-35.pyc new file mode 100755 index 0000000..ee0005c Binary files /dev/null and b/__pycache__/System_I.cpython-35.pyc differ diff --git a/__pycache__/System_I.cpython-36.pyc b/__pycache__/System_I.cpython-36.pyc old mode 100644 new mode 100755 index f205ec8..fd74120 Binary files a/__pycache__/System_I.cpython-36.pyc and b/__pycache__/System_I.cpython-36.pyc differ diff --git a/__pycache__/System_I.cpython-37.pyc b/__pycache__/System_I.cpython-37.pyc index f85e155..b7f4c16 100755 Binary files a/__pycache__/System_I.cpython-37.pyc and b/__pycache__/System_I.cpython-37.pyc differ diff --git a/__pycache__/System_I.cpython-38.pyc b/__pycache__/System_I.cpython-38.pyc new file mode 100755 index 0000000..0c87533 Binary files /dev/null and b/__pycache__/System_I.cpython-38.pyc differ diff --git a/__pycache__/System_zwq.cpython-36.pyc b/__pycache__/System_zwq.cpython-36.pyc new file mode 100755 index 0000000..7652e1f Binary files /dev/null and b/__pycache__/System_zwq.cpython-36.pyc differ diff --git a/__pycache__/System_zwq.cpython-38.pyc b/__pycache__/System_zwq.cpython-38.pyc new file mode 100755 index 0000000..f2f614a Binary files /dev/null and b/__pycache__/System_zwq.cpython-38.pyc differ diff --git a/__pycache__/check_VOC.cpython-36.pyc b/__pycache__/check_VOC.cpython-36.pyc old mode 100644 new mode 100755 diff --git a/__pycache__/coco_visualization.cpython-36.pyc b/__pycache__/coco_visualization.cpython-36.pyc new file mode 100755 index 0000000..77d8b67 Binary files /dev/null and b/__pycache__/coco_visualization.cpython-36.pyc differ diff --git a/__pycache__/coco_visualization.cpython-38.pyc b/__pycache__/coco_visualization.cpython-38.pyc new file mode 100755 index 0000000..26dddaf Binary files /dev/null and b/__pycache__/coco_visualization.cpython-38.pyc differ diff --git a/__pycache__/common.cpython-36.pyc b/__pycache__/common.cpython-36.pyc old mode 100644 new mode 100755 index 69ff0a9..912bdef Binary files a/__pycache__/common.cpython-36.pyc and b/__pycache__/common.cpython-36.pyc differ diff --git a/__pycache__/common.cpython-37.pyc b/__pycache__/common.cpython-37.pyc new file mode 100755 index 0000000..6fc44c5 Binary files /dev/null and b/__pycache__/common.cpython-37.pyc differ diff --git a/__pycache__/common.cpython-38.pyc b/__pycache__/common.cpython-38.pyc new file mode 100644 index 0000000..f0f3655 Binary files /dev/null and b/__pycache__/common.cpython-38.pyc differ diff --git a/__pycache__/common.cpython-39.pyc b/__pycache__/common.cpython-39.pyc new file mode 100644 index 0000000..e56ca80 Binary files /dev/null and b/__pycache__/common.cpython-39.pyc differ diff --git a/__pycache__/creat_xml.cpython-36.pyc b/__pycache__/creat_xml.cpython-36.pyc new file mode 100755 index 0000000..a81b057 Binary files /dev/null and b/__pycache__/creat_xml.cpython-36.pyc differ diff --git a/__pycache__/creat_xml.cpython-38.pyc b/__pycache__/creat_xml.cpython-38.pyc new file mode 100755 index 0000000..d240568 Binary files /dev/null and b/__pycache__/creat_xml.cpython-38.pyc differ diff --git a/__pycache__/creat_xml_fordetection.cpython-36.pyc b/__pycache__/creat_xml_fordetection.cpython-36.pyc old mode 100644 new mode 100755 index 1d8580b..52f00f5 Binary files a/__pycache__/creat_xml_fordetection.cpython-36.pyc and b/__pycache__/creat_xml_fordetection.cpython-36.pyc differ diff --git a/__pycache__/creat_xml_fordetection.cpython-37.pyc b/__pycache__/creat_xml_fordetection.cpython-37.pyc new file mode 100755 index 0000000..c5d7afd Binary files /dev/null and b/__pycache__/creat_xml_fordetection.cpython-37.pyc differ diff --git a/__pycache__/creat_xml_fordetection.cpython-38.pyc b/__pycache__/creat_xml_fordetection.cpython-38.pyc new file mode 100644 index 0000000..246b3b5 Binary files /dev/null and b/__pycache__/creat_xml_fordetection.cpython-38.pyc differ diff --git a/__pycache__/creat_xml_fordetection.cpython-39.pyc b/__pycache__/creat_xml_fordetection.cpython-39.pyc new file mode 100644 index 0000000..cad66ed Binary files /dev/null and b/__pycache__/creat_xml_fordetection.cpython-39.pyc differ diff --git a/__pycache__/cv2AddChineseText.cpython-36.pyc b/__pycache__/cv2AddChineseText.cpython-36.pyc old mode 100644 new mode 100755 index 3f3934d..1529751 Binary files a/__pycache__/cv2AddChineseText.cpython-36.pyc and b/__pycache__/cv2AddChineseText.cpython-36.pyc differ diff --git a/__pycache__/cv2AddChineseText.cpython-37.pyc b/__pycache__/cv2AddChineseText.cpython-37.pyc new file mode 100755 index 0000000..7a6ee93 Binary files /dev/null and b/__pycache__/cv2AddChineseText.cpython-37.pyc differ diff --git a/__pycache__/cv2AddChineseText.cpython-38.pyc b/__pycache__/cv2AddChineseText.cpython-38.pyc new file mode 100755 index 0000000..e278bd9 Binary files /dev/null and b/__pycache__/cv2AddChineseText.cpython-38.pyc differ diff --git a/__pycache__/dataset.cpython-36.pyc b/__pycache__/dataset.cpython-36.pyc old mode 100644 new mode 100755 diff --git a/__pycache__/detection.cpython-36.pyc b/__pycache__/detection.cpython-36.pyc old mode 100644 new mode 100755 diff --git a/__pycache__/imatovideo.cpython-36.pyc b/__pycache__/imatovideo.cpython-36.pyc old mode 100644 new mode 100755 index a55889a..b88dbc9 Binary files a/__pycache__/imatovideo.cpython-36.pyc and b/__pycache__/imatovideo.cpython-36.pyc differ diff --git a/__pycache__/imatovideo.cpython-37.pyc b/__pycache__/imatovideo.cpython-37.pyc new file mode 100755 index 0000000..fa25312 Binary files /dev/null and b/__pycache__/imatovideo.cpython-37.pyc differ diff --git a/__pycache__/imatovideo.cpython-38.pyc b/__pycache__/imatovideo.cpython-38.pyc new file mode 100755 index 0000000..469090e Binary files /dev/null and b/__pycache__/imatovideo.cpython-38.pyc differ diff --git a/__pycache__/jpg.cpython-36.pyc b/__pycache__/jpg.cpython-36.pyc old mode 100644 new mode 100755 index 76b8ebc..5973f71 Binary files a/__pycache__/jpg.cpython-36.pyc and b/__pycache__/jpg.cpython-36.pyc differ diff --git a/__pycache__/network.cpython-36.pyc b/__pycache__/network.cpython-36.pyc old mode 100644 new mode 100755 diff --git a/__pycache__/network_multi.cpython-36.pyc b/__pycache__/network_multi.cpython-36.pyc old mode 100644 new mode 100755 index 45f8e71..025333a Binary files a/__pycache__/network_multi.cpython-36.pyc and b/__pycache__/network_multi.cpython-36.pyc differ diff --git a/__pycache__/network_multi.cpython-38.pyc b/__pycache__/network_multi.cpython-38.pyc new file mode 100755 index 0000000..83ab224 Binary files /dev/null and b/__pycache__/network_multi.cpython-38.pyc differ diff --git a/__pycache__/rtsp_process.cpython-36.pyc b/__pycache__/rtsp_process.cpython-36.pyc old mode 100644 new mode 100755 diff --git a/__pycache__/vediotoima.cpython-36.pyc b/__pycache__/vediotoima.cpython-36.pyc old mode 100644 new mode 100755 diff --git a/__pycache__/vgg.cpython-36.pyc b/__pycache__/vgg.cpython-36.pyc old mode 100644 new mode 100755 index 8045eda..db38c02 Binary files a/__pycache__/vgg.cpython-36.pyc and b/__pycache__/vgg.cpython-36.pyc differ diff --git a/__pycache__/vgg.cpython-38.pyc b/__pycache__/vgg.cpython-38.pyc new file mode 100755 index 0000000..de6c820 Binary files /dev/null and b/__pycache__/vgg.cpython-38.pyc differ diff --git a/__pycache__/vgg_baye.cpython-36.pyc b/__pycache__/vgg_baye.cpython-36.pyc new file mode 100755 index 0000000..f8101b4 Binary files /dev/null and b/__pycache__/vgg_baye.cpython-36.pyc differ diff --git a/__pycache__/vgg_baye.cpython-37.pyc b/__pycache__/vgg_baye.cpython-37.pyc new file mode 100755 index 0000000..2db3af8 Binary files /dev/null and b/__pycache__/vgg_baye.cpython-37.pyc differ diff --git a/__pycache__/vgg_baye.cpython-38.pyc b/__pycache__/vgg_baye.cpython-38.pyc new file mode 100755 index 0000000..2420fa6 Binary files /dev/null and b/__pycache__/vgg_baye.cpython-38.pyc differ diff --git a/__pycache__/videoCrop.cpython-35.pyc b/__pycache__/videoCrop.cpython-35.pyc new file mode 100755 index 0000000..00d3335 Binary files /dev/null and b/__pycache__/videoCrop.cpython-35.pyc differ diff --git a/app/20251105002/panorama.jpg b/app/20251105002/panorama.jpg new file mode 100644 index 0000000..9c5b5e6 Binary files /dev/null and b/app/20251105002/panorama.jpg differ diff --git a/app/20251105002/result_panorama.jpg b/app/20251105002/result_panorama.jpg new file mode 100644 index 0000000..a4789c3 Binary files /dev/null and b/app/20251105002/result_panorama.jpg differ diff --git a/app/__pycache__/processor.cpython-38.pyc b/app/__pycache__/processor.cpython-38.pyc new file mode 100644 index 0000000..ddc7d1b Binary files /dev/null and b/app/__pycache__/processor.cpython-38.pyc differ diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..df4ba55 --- /dev/null +++ b/app/main.py @@ -0,0 +1,53 @@ +from fastapi import FastAPI, HTTPException, Query +from fastapi.responses import FileResponse, JSONResponse +import os +import traceback +from processor import process_video_to_panorama + +app = FastAPI(title="Video Density Estimation API") + +@app.get("/process") +async def process_video( + input_video: str = Query(..., description="Path to input video file"), + output_dir: str = Query(..., description="Output directory path") +): + """ + Process video to generate density estimation result + + Args: + input_video: Path to input video file (e.g., /path/to/video.mp4) + output_dir: Output directory path (e.g., /path/to/output) + + Returns: + JSON with result path or error message + """ + try: + # Validate input video + if not os.path.exists(input_video): + raise HTTPException(status_code=400, detail=f"Input video not found: {input_video}") + + # Process video + result_path,total_count = process_video_to_panorama(input_video, output_dir) + + return JSONResponse({ + "status": "success", + "result_path": result_path, + "total_count": int(total_count), + "message": "Processing completed successfully" + }) + + except Exception as e: + error_msg = f"Processing failed: {str(e)}" + print(f"Error traceback:\n{traceback.format_exc()}") + raise HTTPException(status_code=500, detail=error_msg) + +@app.get("/result") +async def get_result(result_path: str = Query(..., description="Path to result image")): + """Download result image""" + if not os.path.exists(result_path): + raise HTTPException(status_code=404, detail="Result image not found") + return FileResponse(result_path) + +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=8000) diff --git a/app/output.log b/app/output.log new file mode 100644 index 0000000..1e3c284 --- /dev/null +++ b/app/output.log @@ -0,0 +1,268 @@ +nohup: ignoring input +INFO: Started server process [39713] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +ONNX model loaded with providers: ['CUDAExecutionProvider'] +INFO: 172.16.8.253:36032 - "GET /process?input_video=%2Fdata5%2Ffile%2Fdensity%2F2025%2F11%2F06%2F07033a2c-abf8-486c-bf02-76d7158bd160.mp4&output_dir=%2Fdata5%2Ffile%2Foutput%2F20251106173248 HTTP/1.1" 200 OK +INFO: 172.16.8.253:46274 - "GET /process?input_video=%2Fdata5%2Ffile%2Fdensity%2F2025%2F11%2F06%2Feee06cd5-96b0-4927-a0fc-d5d8f72591f2.mp4&output_dir=%2Fdata5%2Ffile%2Foutput%2F20251106182437 HTTP/1.1" 200 OK +INFO: 172.16.8.253:40578 - "GET /process?input_video=%2Fdata5%2Ffile%2Fdensity%2F2025%2F11%2F06%2F1c643e2f-eeef-4f4d-926e-f81b012d4c89.mp4&output_dir=%2Fdata5%2Ffile%2Foutput%2F20251106203817 HTTP/1.1" 200 OK +INFO: 172.16.8.253:40998 - "GET /process?input_video=%2Fdata5%2Ffile%2Fdensity%2F2025%2F11%2F06%2Fd78190f1-1929-4207-af1c-729386759c81.mp4&output_dir=%2Fdata5%2Ffile%2Foutput%2F20251106204100 HTTP/1.1" 200 OK +INFO: 172.16.8.253:41366 - "GET /process?input_video=%2Fdata5%2Ffile%2Fdensity%2F2025%2F11%2F06%2F295e3654-d134-4e80-8d29-01ef1f8f8118.mp4&output_dir=%2Fdata5%2Ffile%2Foutput%2F20251106204254 HTTP/1.1" 200 OK +INFO: 172.16.8.253:42858 - "GET /process?input_video=%2Fdata5%2Ffile%2Fdensity%2F2025%2F11%2F06%2Ff91d6e11-af82-4896-96b7-5606e15db4b0.mp4&output_dir=%2Fdata5%2Ffile%2Foutput%2F20251106205112 HTTP/1.1" 200 OK +INFO: 172.16.8.253:43242 - "GET /process?input_video=%2Fdata5%2Ffile%2Fdensity%2F2025%2F11%2F06%2F55a201dd-d865-4118-b5ad-f798e170743e.mp4&output_dir=%2Fdata5%2Ffile%2Foutput%2F20251106205338 HTTP/1.1" 200 OK +INFO: 172.16.8.253:35640 - "GET /process?input_video=%2Fdata5%2Ffile%2Fdensity%2F2025%2F11%2F07%2Fca5dfe3f-91dd-4a5b-87fb-e61b16a32938.mp4&output_dir=%2Fdata5%2Ffile%2Foutput%2F20251107080758 HTTP/1.1" 200 OK +INFO: 172.16.8.253:36852 - "GET /process?input_video=%2Fdata5%2Ffile%2Fdensity%2F2025%2F11%2F07%2F68104776-9dab-4c71-b9a6-5b62f0a56da2.mp4&output_dir=%2Fdata5%2Ffile%2Foutput%2F20251107102003 HTTP/1.1" 200 OK +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:45168 - "GET / HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:45195 - "GET /nice%20ports%2C/Trinity.txt.bak HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:45199 - "OPTIONS / HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:45551 - "GET /nmaplowercheck1762703348 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:45552 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:45559 - "POST /sdk HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:45565 - "GET /HNAP1 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:45568 - "GET /evox/about HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:54407 - "GET http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:54410 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:54412 - "GET /robots.txt HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:54414 - "OPTIONS / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:54416 - "HEAD http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:54418 - "GET /favicon.ico HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:54420 - "CONNECT www.google.com%3A80 HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:46569 - "GET / HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:46600 - "GET /nice%20ports%2C/Trinity.txt.bak HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:46604 - "OPTIONS / HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:46807 - "POST /sdk HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:46814 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:46813 - "GET /nmaplowercheck1763306540 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:46821 - "GET /evox/about HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:46824 - "GET /HNAP1 HTTP/1.1" 404 Not Found +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:45536 - "GET / HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:45583 - "GET /nice%20ports%2C/Trinity.txt.bak HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:45587 - "OPTIONS / HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:45813 - "GET /nmaplowercheck1763913242 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:45810 - "POST /sdk HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:45812 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:45820 - "GET /HNAP1 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:45822 - "GET /evox/about HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:38472 - "GET http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:38475 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:38477 - "OPTIONS / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:38478 - "GET /robots.txt HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:38484 - "HEAD http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:38486 - "GET /favicon.ico HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:38488 - "CONNECT www.google.com%3A80 HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:43698 - "GET / HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:43744 - "GET /nice%20ports%2C/Trinity.txt.bak HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:43747 - "OPTIONS / HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:44049 - "GET /nmaplowercheck1764518315 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:44051 - "POST /sdk HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:44050 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:44061 - "GET /HNAP1 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:44064 - "GET /evox/about HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:53503 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:53505 - "GET http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:53508 - "OPTIONS / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:53509 - "GET /robots.txt HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:53511 - "HEAD http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:53513 - "GET /favicon.ico HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:53515 - "CONNECT www.google.com%3A80 HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:38906 - "GET / HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:38932 - "GET /nice%20ports%2C/Trinity.txt.bak HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:38936 - "OPTIONS / HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:46904 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:46895 - "POST /sdk HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:46900 - "GET /nmaplowercheck1765122601 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:46909 - "GET /HNAP1 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:46912 - "GET /evox/about HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:36677 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:36679 - "GET http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:36683 - "GET /robots.txt HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:36685 - "OPTIONS / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:36687 - "HEAD http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:36690 - "CONNECT www.google.com%3A80 HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:36691 - "GET /favicon.ico HTTP/1.1" 404 Not Found +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:47654 - "GET / HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:47720 - "GET /nice%20ports%2C/Trinity.txt.bak HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:47725 - "OPTIONS / HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:48004 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:48006 - "POST /sdk HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:48003 - "GET /nmaplowercheck1765731479 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:48012 - "GET /evox/about HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:48014 - "GET /HNAP1 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:34018 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:34022 - "GET /robots.txt HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:34023 - "OPTIONS / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:34028 - "GET http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:34032 - "HEAD http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:34033 - "GET /favicon.ico HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:34035 - "CONNECT www.google.com%3A80 HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:50736 - "GET / HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:50763 - "GET /nice%20ports%2C/Trinity.txt.bak HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:50766 - "OPTIONS / HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:41450 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:41452 - "POST /sdk HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:41449 - "GET /nmaplowercheck1766334717 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:41458 - "GET /HNAP1 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:41461 - "GET /evox/about HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:58010 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:58011 - "GET /robots.txt HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:58018 - "GET http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:58021 - "OPTIONS / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:58022 - "GET /favicon.ico HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:58024 - "HEAD http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:58028 - "CONNECT www.google.com%3A80 HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:58001 - "GET / HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:58033 - "GET /nice%20ports%2C/Trinity.txt.bak HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:58039 - "OPTIONS / HTTP/1.0" 404 Not Found +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +WARNING: Invalid HTTP request received. +INFO: 172.16.0.234:58278 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:58279 - "GET /nmaplowercheck1766940881 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:58283 - "POST /sdk HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:58286 - "GET /HNAP1 HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:58289 - "GET /evox/about HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:54645 - "OPTIONS / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:54646 - "GET / HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:54652 - "GET http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:54649 - "GET /robots.txt HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:54656 - "HEAD http%3A//www.google.com HTTP/1.0" 404 Not Found +INFO: 172.16.0.234:54654 - "GET /favicon.ico HTTP/1.1" 404 Not Found +INFO: 172.16.0.234:54658 - "CONNECT www.google.com%3A80 HTTP/1.0" 404 Not Found +INFO: Shutting down +INFO: Waiting for application shutdown. +INFO: Application shutdown complete. +INFO: Finished server process [39713] diff --git a/app/processor.py b/app/processor.py new file mode 100644 index 0000000..4ec0836 --- /dev/null +++ b/app/processor.py @@ -0,0 +1,175 @@ +import os +import cv2 +import numpy as np +import onnxruntime as ort +from concurrent.futures import ThreadPoolExecutor +import threading +from typing import List, Tuple + +# 全局 ONNX 会话(单例) +_ort_session = None +_session_lock = threading.Lock() + +def get_ort_session(): + """获取 ONNX Runtime 会话(线程安全单例)""" + global _ort_session + if _ort_session is None: + with _session_lock: + if _ort_session is None: + test_weights = "/data1/Hatcher/model/PopulationCounting/Bayesian_project_ours/sim-CAS-base-test.onnx" + if not os.path.exists(test_weights): + raise FileNotFoundError(f"ONNX model not found: {test_weights}") + + providers = ["CUDAExecutionProvider"] if "CUDAExecutionProvider" in ort.get_available_providers() else ["CPUExecutionProvider"] + _ort_session = ort.InferenceSession(test_weights, providers=providers) + print(f"ONNX model loaded with providers: {providers}") + return _ort_session + +def extract_specific_frames(video_path: str, frame_numbers: List[int]) -> np.ndarray: + """从视频中提取指定帧号的图像并拼接""" + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + raise ValueError(f"Cannot open video file: {video_path}") + + frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + + canvas_width = frame_width * len(frame_numbers) + canvas = np.zeros((frame_height, canvas_width, 3), dtype=np.uint8) + current_frame = 0 + canvas_position = 0 + + for target_frame in sorted(frame_numbers): + if target_frame >= total_frames: + continue + + while current_frame < target_frame: + if not cap.grab(): + break + current_frame += 1 + + ret, frame = cap.retrieve() + if ret: + canvas[:, canvas_position:canvas_position+frame_width] = frame + canvas_position += frame_width + else: + print(f"Warning: Failed to read frame {target_frame}") + + cap.release() + + if canvas_position < canvas_width: + canvas = canvas[:, :canvas_position] + return canvas + +def split_image(image: np.ndarray) -> Tuple[List[np.ndarray], List[Tuple[int, int]], float, Tuple[int, int]]: + """Split large image into 800x800 patches""" + h, w = image.shape[:2] + n_segments = max(1, w // 800) + target_w = n_segments * 800 + scale = target_w / w + new_w = target_w + new_h = int(h * scale) + resized_img = cv2.resize(image, (new_w, new_h)) + + patches = [] + positions = [] + for i in range(0, new_w, 800): + patch = resized_img[:, i:i+800] + if patch.shape[1] == 800: + patches.append(patch) + positions.append((i, i+800)) + return patches, positions, scale, (new_h, new_w) + +def process_patch(patch: np.ndarray, ort_session) -> np.ndarray: + """Process a single 800x800 patch""" + img = cv2.resize(patch, (800, 800)) / 255.0 + img = img[np.newaxis, :, :].transpose(0, 3, 1, 2) + input_blob = np.array(img, dtype=np.float32) + + onnx_input_name = ort_session.get_inputs()[0].name + onnx_outputs_names = ort_session.get_outputs()[0].name + onnx_result = ort_session.run([onnx_outputs_names], {onnx_input_name: input_blob}) + + density_map = onnx_result[0][0][0] + density_map[density_map < 1e-6] = 0 + return density_map + +def process_single_image(image_path: str, save_root: str, ort_session, file_lock) -> bool: + """Process a single large image""" + try: + image_name = os.path.basename(image_path) + result_name = f"result_{image_name}" + img_or = cv2.imread(image_path) + if img_or is None: + return False + + patches, positions, scale, (new_h, new_w) = split_image(img_or) + density_maps = [] + total_count = 0 + + for patch in patches: + density_map = process_patch(patch, ort_session) + density_maps.append(density_map) + total_count += np.sum(density_map) + + combined_density = np.zeros((new_h, new_w)) + for density_map, (start_x, end_x) in zip(density_maps, positions): + resized_density = cv2.resize(density_map, (800, new_h)) + combined_density[:, start_x:end_x] = resized_density + + combined_density = cv2.resize(combined_density, (img_or.shape[1], img_or.shape[0])) + heatmap = combined_density / np.max(combined_density) + heatmap = np.power(heatmap, 0.7) + heatmap = np.uint8(heatmap * 255) + heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET) + + imgheatmap_W = int(img_or.shape[1] / 3) + imgheatmap_H = int(img_or.shape[0] / 3) + density_result = cv2.resize(heatmap, (imgheatmap_W, imgheatmap_H)) + img_or[0:imgheatmap_H, 0:imgheatmap_W] = density_result + + cv2.putText(img_or, f"Count: {int(total_count)}", (50, 200), + cv2.FONT_HERSHEY_SIMPLEX, 4, (0, 0, 255), 8) + + save_path = os.path.join(save_root, result_name) + with file_lock: + cv2.imwrite(save_path, img_or) + return True, float(total_count) + except Exception as e: + print(f"Error processing {image_path}: {str(e)}") + return False + +def process_video_to_panorama(video_path: str, output_dir: str) -> Tuple[str, float]: + """Main pipeline: video -> panorama -> density estimation, returns (result_path, total_count)""" + os.makedirs(output_dir, exist_ok=True) + + # Step 1: Extract frames and create panorama + frame_numbers = [13, 82, 196, 290, 381, 483, 697, 798, 893, 1047] + panorama = extract_specific_frames(video_path, frame_numbers) + panorama_path = os.path.join(output_dir, "panorama.jpg") + cv2.imwrite(panorama_path, panorama) + + # Step 2: Process images with ONNX model + ort_session = get_ort_session() + image_paths = [panorama_path] + save_root = output_dir + os.makedirs(save_root, exist_ok=True) + + results = [] + file_lock = threading.Lock() + + def process_with_result(image_path): + result = process_single_image(image_path, save_root, ort_session, file_lock) + results.append(result) # (success, total_count) + + with ThreadPoolExecutor(max_workers=4) as executor: + executor.map(process_with_result, image_paths) + + if not results or not results[0][0]: + raise RuntimeError("Failed to process panorama image") + + result_path = os.path.join(save_root, f"result_{os.path.basename(panorama_path)}") + total_count = results[0][1] # ← 获取 total_count + + return result_path, total_count # ← 返回 total_count diff --git a/check_VOC.py b/check_VOC.py index f7cdb04..13ebec8 100755 --- a/check_VOC.py +++ b/check_VOC.py @@ -10,15 +10,17 @@ import cv2 import xml.dom.minidom from tqdm import tqdm -image_path="/data1/Hatcher/model/20210708/ftp_Result/860548046389083/RAWImage/WVGA__20210604_040328_100_0356/" -annotation_path="/data1/Hatcher/model/20210708/ftp_Result/860548046389083/VideoResult/WVGA_20210604_040328_100_0356/" -save_path ="/data1/Hatcher/model/20210708/ftp_Result/860548046389083/VideoResult/check/" +image_path="/data4/Hatcher/smallobject/voc_class/airplane/images/" +annotation_path="/data4/Hatcher/smallobject/voc_class/airplane/annos/" +save_path ="/data4/Hatcher/smallobject/voc_class/airplane/check/" def _check_voc(image_path,annotation_path,save_path): + if not os.path.exists(save_path): + os.makedirs(save_path) files_name = os.listdir(image_path) for filename_ in tqdm(files_name): filename, extension= os.path.splitext(filename_) #filename=filename.split('__')[0] - img_path =image_path+filename+'.jpg' + img_path =image_path+filename+'.png' xml_path =annotation_path+filename+'.xml' img = cv2.imread(img_path) if img is None: @@ -50,5 +52,6 @@ def _check_voc(image_path,annotation_path,save_path): if not (flag): print(filename,"error") print("all done ====================================") - +if __name__ == "__main__": + _check_voc(image_path,annotation_path,save_path) #(int((xmin_data+xmax_data/2)),int((ymin_data+ymax_data)/2)) \ No newline at end of file diff --git a/coco2voc.py b/coco2voc.py new file mode 100755 index 0000000..bcaaa41 --- /dev/null +++ b/coco2voc.py @@ -0,0 +1,136 @@ +''' +把coco数据集合的所有标注转换到voc格式,不改变图片命名方式, +注意,原来有一些图片是黑白照片,检测出不是 RGB 图像,这样的图像不会被放到新的文件夹中 +''' +from pycocotools.coco import COCO +import os, cv2, shutil +from lxml import etree, objectify +from tqdm import tqdm +from PIL import Image + +# 1、生成图片保存的路径 +CKimg_dir = '/data4/Hatcher/smallobject/voc/val_images/' +# 2、生成标注文件保存的路径 +CKanno_dir = '/data4/Hatcher/smallobject/voc/val_annos/' + + +# 若模型保存文件夹不存在,创建模型保存文件夹,若存在,删除重建 +def mkr(path): + if os.path.exists(path): + shutil.rmtree(path) + os.mkdir(path) + else: + os.mkdir(path) + + +def save_annotations(filename, objs, filepath): + annopath = CKanno_dir + "/" + filename[:-3] + "xml" # 生成的xml文件保存路径 + dst_path = CKimg_dir + "/" + filename + img_path = filepath + img = cv2.imread(img_path) + im = Image.open(img_path) + # if im.mode != "RGB": + # print(filename + " not a RGB image") + # im.close() + # return + im.close() + shutil.copy(img_path, dst_path) # 把原始图像复制到目标文件夹 + E = objectify.ElementMaker(annotate=False) + anno_tree = E.annotation( + E.folder('1'), + E.filename(filename), + E.source( + E.database('CKdemo'), + E.annotation('VOC'), + E.image('CK') + ), + E.size( + E.width(img.shape[1]), + E.height(img.shape[0]), + E.depth(img.shape[2]) + ), + E.segmented(0) + ) + for obj in objs: + E2 = objectify.ElementMaker(annotate=False) + anno_tree2 = E2.object( + E.name(obj[0]), + E.pose(), + E.truncated("0"), + E.difficult(0), + E.bndbox( + E.xmin(obj[2]), + E.ymin(obj[3]), + E.xmax(obj[4]), + E.ymax(obj[5]) + ) + ) + anno_tree.append(anno_tree2) + etree.ElementTree(anno_tree).write(annopath, pretty_print=True) + + +def showbycv(coco, img, classes, origin_image_dir, verbose=False): + filename = img['file_name'] + filepath = os.path.join(origin_image_dir, filename) + I = cv2.imread(filepath) + annIds = coco.getAnnIds(imgIds=img['id'], iscrowd=None) + anns = coco.loadAnns(annIds) + objs = [] + for ann in anns: + name = classes[ann['category_id']] + if 'bbox' in ann: + bbox = ann['bbox'] + xmin = (int)(bbox[0]) + ymin = (int)(bbox[1]) + xmax = (int)(bbox[2] + bbox[0]) + ymax = (int)(bbox[3] + bbox[1]) + obj = [name, 1.0, xmin, ymin, xmax, ymax] + objs.append(obj) + if verbose: + cv2.rectangle(I, (xmin, ymin), (xmax, ymax), (255, 0, 0)) + cv2.putText(I, name, (xmin, ymin), 3, 1, (0, 0, 255)) + save_annotations(filename, objs, filepath) + if verbose: + cv2.imshow("img", I) + cv2.waitKey(0) + +def catid2name(coco): # 将名字和id号建立一个字典 + classes = dict() + for cat in coco.dataset['categories']: + classes[cat['id']] = cat['name'] + # print(str(cat['id'])+":"+cat['name']) + return classes + + +def get_CK5(origin_anno_dir, origin_image_dir, verbose=False): + dataTypes = ['val'] # 3、根据你要转化的是训练集还是验证集(annotations名称) + for dataType in dataTypes: + annFile = 'aitod_{}.json'.format(dataType) + annpath = os.path.join(origin_anno_dir, annFile) + coco = COCO(annpath) + classes = catid2name(coco) + imgIds = coco.getImgIds() + # imgIds=imgIds[0:1000]#测试用,抽取10张图片,看下存储效果 + for imgId in tqdm(imgIds): + img = coco.loadImgs(imgId)[0] + #showbycv(coco, dataType, img, classes, origin_image_dir, verbose=False) + showbycv(coco, img, classes, origin_image_dir, verbose=False) + + +def main(): + # base_dir = 'C:\\Users\\admin\\Desktop\\few shot competition\\train\\voc' # step1 这里是一个新的文件夹,存放转换后的图片和标注 + # image_dir = os.path.join(base_dir, 'images') # 在上述文件夹中生成images,annotations两个子文件夹 + # anno_dir = os.path.join(base_dir, 'annotations') + # mkr(image_dir) + # mkr(anno_dir) + # 4、 + origin_image_dir = '/data4/Hatcher/smallobject/val/images/' # step 2原始的coco的图像存放位置 + # 5、 + origin_anno_dir = '/data4/Hatcher/smallobject/annotations/' # step 3 原始的coco的标注存放位置 + print(origin_anno_dir) + verbose = True # 是否需要看下标记是否正确的开关标记,若是true,就会把标记展示到图片上 + get_CK5(origin_anno_dir, origin_image_dir, verbose) + + +if __name__ == "__main__": + main() diff --git a/coco_visualization.py b/coco_visualization.py new file mode 100755 index 0000000..436e0e7 --- /dev/null +++ b/coco_visualization.py @@ -0,0 +1,96 @@ +import os +import sys + +#if "/opt/ros/kinetic/lib/python2.7/dist-packages" in sys.path: + # sys.path.remove("/opt/ros/kinetic/lib/python2.7/dist-packages") +import cv2 +import numpy as np +from skimage import io +import matplotlib +import matplotlib.pyplot as plt +from matplotlib import patches, lines +from matplotlib.patches import Polygon, Rectangle +from matplotlib.collections import PatchCollection + + +from pycocotools.coco import COCO +#matplotlib.use('TkAgg') + + +def showAnns(cat_names,anns): + if len(anns) == 0: + return 0 + ax = plt.gca() + ax.set_autoscale_on(False) + captions = [] + polygons = [] + rectangles = [] + color = [] + for ann in anns: + c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0] + # if 'segmentation' in ann: + # if type(ann['segmentation']) == list: + # # polygon + # for seg in ann['segmentation']: + # print(132131,ann['category_id']) + # print(cat_names[0]) + captions.append(cat_names[ann['category_id']-1]) + #poly = np.array(seg).reshape((int(len(seg) / 2), 2)) + l_corner, w, h = (ann['bbox'][0], ann['bbox'][1]), ann['bbox'][2], ann['bbox'][3] + rectangles.append(Rectangle(l_corner, w, h)) + #polygons.append(Polygon(poly)) + color.append(c) + + p = PatchCollection(rectangles, facecolor='none', edgecolors=color, alpha=1, linestyle='--', linewidths=2) + ax.add_collection(p) + + for i in range(len(captions)): + x = rectangles[i].xy[0] + y = rectangles[i].xy[1] + ax.text(x, y, captions[i], size=10, verticalalignment='top', color='w', backgroundcolor="none") + + # p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.6) + # ax.add_collection(p) + # #p = PatchCollection(polygons, facecolor='none', edgecolors=color, linewidths=2) + # p = PatchCollection(polygons, facecolor='none', edgecolors='b', linewidths=0.5) + # ax.add_collection(p) + print('Ok!') + + + +import random + +#annfile = "/data/DataManagement/Project/CAS_ProjectBird/CDB_ProjectBird/coco/annotations/val.json" #####coco json +#imgroot = "/data/DataManagement/Project/CAS_ProjectBird/CDB_ProjectBird/images/test" ####image_path +def draw(coco,imgids,cat_names,imgroot,m, n, i): + img = coco.loadImgs([str(imgids[np.random.randint(0, len(imgids))])])[0] + I = io.imread(os.path.join(imgroot, img['file_name'])) + plt.subplot(m, n, i) + plt.axis('off') + plt.title(img['file_name'], fontsize=8, color='blue') + plt.imshow(I, aspect='equal') + annids = coco.getAnnIds(imgIds=[img['id']]) + anns = coco.loadAnns(annids) + showAnns(cat_names,anns) +def checkCOCO(annfile,imgroot): + coco = COCO(annfile) + cats = coco.loadCats(coco.getCatIds()) + cat_names = [cat['name'] for cat in cats] + print(cat_names) + catids = coco.getCatIds(catNms=random.randint(0,len(cat_names)-1)) + imgids = coco.getImgIds(catIds=catids) + if 1: + m=4 + n=4 + plt.figure(figsize=(m*6,n*4)) + plt.subplots_adjust(top=1,bottom=0,left=0,right=1,hspace=0,wspace=0) + plt.margins(0,0) + #fig = plt.figure(figsize=(18*m,12*n)) + for i in range(1,m*n+1): + draw(coco,imgids,cat_names,imgroot,m,n,i) + plt.savefig('static_map.png') + plt.show() +if __name__ == "__main__": + annfile = "/data3/Project/CAS_ProjectBird/CDB_ProjectBird_BJCH_YNDC_HHK/COCO/annotations_str/train.json" #####coco json + imgroot = "/data3/Project/CAS_ProjectBird/CDB_ProjectBird_BJCH_YNDC_HHK/COCO/train" ####image_path + checkCOCO(annfile,imgroot) \ No newline at end of file diff --git a/common.py b/common.py index 399b7ef..354e760 100755 --- a/common.py +++ b/common.py @@ -22,14 +22,14 @@ class global_para(): # args = parser1.parse_args() #print(args) # root = "/home/gyd/output1" - # # os.environ['CUDA_VISIBLE_DEVICES'] = '0' + #os.environ['CUDA_VISIBLE_DEVICES'] = '7' # os.environ['CUDA_VISIBLE_DEVICES'] = args.GPU - # devices = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') + devices = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # camera_address = args.add # VideoPath = args.video_num # red_flag = args.red # detect_thresh = args.thresh - + #fine_thresh2 = torch.tensor(fine_thresh2).cuda() birdIndex = 99999 #birdIndex = torch.tensor(birdIndex).cuda() @@ -44,12 +44,12 @@ class global_para(): DebugPrint_flag = False # ´òÓ¡±ê־λ - Species = torch.zeros(8).cuda() + #Species = torch.zeros(8).cuda() num_count_old =0 boxes_fine = None labels_fine = None - showThresh = 25 + showThresh = 50 destory_image = False # Camera_device = args.video_num # ÉãÏñÍ·±àºÅ£¬0001 image_time = None # µ±Ç°´¦ÀíµÄ30ÊÓÆµµÄ±àºÅ @@ -66,44 +66,75 @@ class global_para(): sortiou_threshold = 0.3 Finerestartboxes = [] IndexMax = 0 - radioShowX = 2560.0 - radioShowY = 1440.0 + radioShowX = 2560/2560.0#3840/2560.0 + radioShowY = 1440/1440.0 #2160/1440.0 radioShowtext = radioShowX - SortLabel_Index = None #±êÇ©ºÍË÷Òý¶ÔÓ¦¹ØÏµ[[4,1],[3,2]] - SortLabel_Indexpre = [] #±êÇ©ºÍË÷ÒýµÄ¶ÔÓ¦¹ØÏµ£¬ÓÃÔÚ×·×Ù¹ý³ÌÖÐгöÏÖµÄÄ¿±ê£¬[[label,Index,Count]] + SortLabel_Index = None + SortLabel_Indexpre = [] # Detection2 = Detection(devices,root) FineCountThresh = 5 img_show = None Fine_thresh = 0.4 - + detthresh = 0.4 + backbone = "convnext_base_in22k"#"vit_base_patch16_224_in21k" + + # HHK # DetWeight = "/data1/Hatcher/model/Detection/yolov5/runs/train/exp21/weights/best.pt" # FineWeight = "/data/Hatcher/data/weigth/areaproject/resnet50-JXPYH-Bird-3-4-20220429/_42911_PYH-3/best.pth" - #DetWeight = "/data1/Hatcher/model/Detection/yolov5/runs/train/KunMingCuiHu-Fish2/weights/best.pt" - #FineWeight = "/data/Hatcher/data/weigth/areaproject/resnet50-KMDC-Fish-5-1-20220505/_5510_DianChiFish-4/best.pth" - DetWeight = "/data1/Hatcher/model/Detection/yolov5/runs/train/BeijingCuiHu-Bird26/weights/best.pt" - FineWeight = "/data/Hatcher/data/weigth/areaproject/VIT-BJCH_Bird_94_DDP/_5914_CUI-94-1/best.pth" - #BHG_chineseName = ["kong", '白鹤', '白头鹤','白枕鹤'] - #BHG_chineseName = ["kong","鲫鱼","麦穗鱼","鳑鲏","鲈鱼"] + # BHG_chineseName = ['Bird', 'Person', 'Other_Object', 'ANSERIFORMES', 'Phasianus_colchicus', 'Anser_fabalis', 'Anser_cygnoides', 'Anser_anser', 'Anser_erythropus', 'Cygnus_olor', 'Cygnus_columbianus', 'Cygnus_cygnus', 'Anas_zonorhyncha', 'Tadorna_ferruginea', 'Aix_galericulata', 'Mareca_strepera', 'Mareca_falcata', 'Anas_platyrhynchos', 'Netta_rufina', 'Aythya_ferina', 'Aythya_fuligula', 'Mergus_merganser', 'Tachybaptus_ruficollis', 'Podiceps_cristatus', 'Gallinula_chloropus', 'Fulica_atra', 'Leucogeranus_leucogeranus', 'Grus_virgo', 'Grus_japonensis', 'Grus_grus', 'Grus_monacha', 'Himantopus_himantopus', 'Calidris_falcinellus', 'Recurvirostra_avosetta', 'Charadrius_alexandrinus', 'Scolopax_rusticola', 'Limosa_limosa', 'Tringa_ochropus', 'Actitis_hypoleucos', 'Calidris_subminuta', 'Chroicocephalus_brunnicephalus', 'Chroicocephalus_ridibundus', 'Ciconia_boyciana', 'Phalacrocorax_carbo', 'Platalea_leucorodia', 'Ixobrychus_sinensis', 'Nycticorax_nycticorax', 'Ardeola_bacchus', 'Ardea_cinerea', 'Ardea_purpurea', 'Ardea_alba', 'Ardea_intermedia', 'Egretta_garzetta', 'Aegypius_monachus', 'Accipiter_gularis', 'Haliaeetus_albicilla', 'Alcedo_atthis', 'Dicrurus_macrocercus', 'Cyanopica_cyanus', 'Corvus_frugilegus', 'Passer_montanus', 'Antigone_vipio', 'Otis_tarda', 'Pica_serica', 'Mergellus_albellus', 'Aythya_baeri', 'Tadorna_tadorna', 'Pelecanus_crispus', 'Buteo_japonicus', 'Elanus_caeruleus', 'Phylloscopus_claudiae', 'Falco_tinnunculus', 'Ficedula_zanthopygia', 'Falco_cherrug', 'Falco_peregrinus', 'Phylloscopus_armandii', 'Emberiza_rustica', 'Mergus_squamatus', 'Spodiopsar_cineraceus', 'Tringa_erythropus', 'Anthus_rufulus', 'Charadrius_dubius', 'Asio_otus', 'Motacilla_alba', 'Platalea_minor', 'Sterna_hirundo', 'Clanga_clanga', 'Bubo_bubo', 'Circus_cyaneus', 'Emberiza_tristrami', 'Botaurus_stellaris', 'Mergus_serrator', 'Ciconia_nigra', 'Motacilla_cinerea', 'Tarsiger_cyanurus', 'Coloeus_dauuricus', 'Turdus_pallidus', 'Milvus_migrans', 'Aquila_heliaca', 'Clangula_hyemalis', 'Spilopelia_chinensis', 'Rallus_indicus', 'Sitta_villosa', 'Falco_amurensis', 'Vanellus_vanellus', 'Phoenicurus_auroreus', 'Pluvialis_squatarola', 'Bucephala_clangula', 'Anas_acuta', 'Hydrophasianus_chirurgus', 'Terpsiphone_incei', 'Phylloscopus_proregulus', 'Aythya_nyroca', 'Gallinago_gallinago', 'Calidris_alpina', 'Gelochelidon_nilotica', 'Phylloscopus_inornatus', 'Tringa_glareola', 'Podiceps_nigricollis', 'Ixobrychus_cinnamomeus', 'Numenius_phaeopus', 'Agropsar_sturninus', 'Pernis_ptilorhynchus', 'Columba_rupestris', 'Lanius_bucephalus', 'Emberiza_chrysophrys', 'Motacilla_citreola', 'Larus_crassirostris', 'Accipiter_nisus', 'Rhopophilus_pekinensis', 'Amaurornis_phoenicurus', 'Coccothraustes_coccothraustes', 'Pycnonotus_sinensis', 'Emberiza_cia', 'Butorides_striata', 'Ficedula_albicilla', 'Anas_crecca', 'Falco_subbuteo', 'Sibirionetta_formosa', 'Emberiza_cioides', 'Vanellus_cinereus', 'Phylloscopus_fuscatus', 'Spatula_querquedula', 'Halcyon_pileata', 'Chlidonias_hybrida', 'Spodiopsar_sericeus', 'Podiceps_auritus', 'Anthus_spinoletta', 'Aquila_chrysaetos', 'Turdus_hortulorum', 'Buteo_lagopus', 'Zosterops_erythropleurus', 'Anthus_hodgsoni', 'Spatula_clypeata', 'Glareola_maldivarum', 'Motacilla_tschutschensis', 'Bombycilla_garrulus', 'Zosterops_simplex', 'Aythya_marila', 'Larus_vegae', 'Bubulcus_coromandus', 'Sitta_europaea', 'Anser_indicus', 'Mareca_penelope', 'Tringa_nebularia', 'Fregata_ariel', 'Circus_spilonotus', 'Corvus_corone'] + # FineClassNum = 64 + + # BJHSQ + DetWeight = "/data5/Train_Models/data/Detection_weigth/3090/202305/20230520-116424-pixel10000-HHK_Person_yolov5s6_2176_30902/weights/best.pt" + FineWeight = "/data5/Train_Models/mmcls_weigth/3090/202306/CMB_HHKBird_20230615_169/convnext-base_4xb32_cmb200/latest.pth" + #BHG_chineseName = ['Bird', 'ANSERIFORMES', 'Anser_anser', 'Anser_cygnoides', 'Anser_fabalis', 'Cygnus_cygnus', 'Tadorna_tadorna', 'Tadorna_ferruginea', 'Aix_galericulata', 'Sibirionetta_formosa', 'Spatula_querquedula', 'Spatula_clypeata', 'Mareca_strepera', 'Mareca_falcata', 'Mareca_penelope', 'Anas_zonorhyncha', 'Anas_platyrhynchos', 'Anas_acuta', 'Anas_crecca', 'Aythya_ferina', 'Aythya_baeri', 'Aythya_nyroca', 'Aythya_fuligula', 'Bucephala_clangula', 'Mergellus_albellus', 'Mergus_merganser', 'Phasianus_colchicus', 'Tachybaptus_ruficollis', 'Podiceps_cristatus', 'Ciconia_nigra', 'Platalea_leucorodia', 'Botaurus_stellaris', 'Ixobrychus_sinensis', 'Ixobrychus_cinnamomeus', 'Nycticorax_nycticorax', 'Butorides_striata', 'Ardeola_bacchus', 'Ardea_cinerea', 'Ardea_purpurea', 'Ardea_alba', 'Ardea_intermedia', 'Egretta_garzetta', 'Phalacrocorax_carbo', 'Elanus_caeruleus', 'Pernis_ptilorhynchus', 'Clanga_clanga', 'Aquila_chrysaetos', 'Accipiter_gularis', 'Accipiter_nisus', 'Circus_aeruginosus', 'Circus_spilonotus', 'Circus_cyaneus', 'Milvus_migrans', 'Haliaeetus_albicilla', 'Buteo_lagopus', 'Buteo_japonicus', 'Otis_tarda', 'Rallus_indicus', 'Gallinula_chloropus', 'Fulica_atra', 'Amaurornis_phoenicurus', 'Antigone_vipio', 'Grus_grus', 'Himantopus_himantopus', 'Vanellus_vanellus', 'Vanellus_cinereus', 'Charadrius_dubius', 'Limosa_limosa', 'Calidris_subminuta', 'Scolopax_rusticola', 'Gallinago_gallinago', 'Actitis_hypoleucos', 'Tringa_ochropus', 'Tringa_glareola', 'Tringa_erythropus', 'Tringa_nebularia', 'Chroicocephalus_ridibundus', 'Sterna_hirundo', 'Chlidonias_hybrida', 'Asio_otus', 'Alcedo_atthis', 'Falco_tinnunculus', 'Falco_amurensis', 'Falco_subbuteo', 'Falco_cherrug', 'Falco_peregrinus', 'Lanius_bucephalus', 'Dicrurus_macrocercus', 'Cyanopica_cyanus', 'Pica_serica', 'Corvus_frugilegus', 'Corvus_corone', 'Corvus_macrorhynchos', 'Pycnonotus_sinensis', 'Phylloscopus_inornatus', 'Phylloscopus_proregulus', 'Phylloscopus_armandii', 'Phylloscopus_fuscatus', 'Phylloscopus_claudiae', 'Zosterops_erythropleurus', 'Zosterops_simplex', 'Spodiopsar_cineraceus', 'Agropsar_sturninus', 'Turdus_hortulorum', 'Turdus_ruficollis', 'Tarsiger_cyanurus', 'Ficedula_albicilla', 'Phoenicurus_auroreus', 'Passer_montanus', 'Motacilla_tschutschensis', 'Motacilla_citreola', 'Motacilla_cinerea', 'Motacilla_alba', 'Anthus_rufulus', 'Anthus_hodgsoni', 'Anthus_spinoletta', 'Emberiza_tristrami', 'Emberiza_chrysophrys', 'Emberiza_rustica', 'Coloeus_dauuricus', 'Spilopelia_chinensis', 'Larus_vegae', 'Bubulcus_coromandus', 'Ciconia_boyciana','ANSERIFORMES', 'Anser_anser', 'Anser_cygnoides', 'Anser_fabalis', 'Cygnus_cygnus', 'Tadorna_tadorna', 'Tadorna_ferruginea', 'Aix_galericulata', 'Sibirionetta_formosa', 'Spatula_querquedula', 'Spatula_clypeata', 'Mareca_strepera', 'Mareca_falcata', 'Mareca_penelope', 'Anas_zonorhyncha', 'Anas_platyrhynchos', 'Anas_acuta', 'Anas_crecca', 'Aythya_ferina', 'Aythya_baeri', 'Aythya_nyroca', 'Aythya_fuligula', 'Bucephala_clangula', 'Mergellus_albellus', 'Mergus_merganser', 'Phasianus_colchicus', 'Tachybaptus_ruficollis', 'Podiceps_cristatus', 'Ciconia_nigra', 'Platalea_leucorodia', 'Botaurus_stellaris', 'Ixobrychus_sinensis', 'Ixobrychus_cinnamomeus', 'Nycticorax_nycticorax', 'Butorides_striata', 'Ardeola_bacchus', 'Ardea_cinerea', 'Ardea_purpurea', 'Ardea_alba', 'Ardea_intermedia', 'Egretta_garzetta', 'Phalacrocorax_carbo', 'Elanus_caeruleus', 'Pernis_ptilorhynchus', 'Clanga_clanga', 'Aquila_chrysaetos', 'Accipiter_gularis', 'Accipiter_nisus', 'Circus_aeruginosus', 'Circus_spilonotus', 'Circus_cyaneus', 'Milvus_migrans', 'Haliaeetus_albicilla', 'Buteo_lagopus', 'Buteo_japonicus', 'Otis_tarda', 'Rallus_indicus', 'Gallinula_chloropus', 'Fulica_atra', 'Amaurornis_phoenicurus', 'Antigone_vipio', 'Grus_grus', 'Himantopus_himantopus', 'Vanellus_vanellus', 'Vanellus_cinereus', 'Charadrius_dubius', 'Limosa_limosa', 'Calidris_subminuta', 'Scolopax_rusticola', 'Gallinago_gallinago', 'Actitis_hypoleucos', 'Tringa_ochropus', 'Tringa_glareola', 'Tringa_erythropus', 'Tringa_nebularia', 'Chroicocephalus_ridibundus', 'Sterna_hirundo', 'Chlidonias_hybrida', 'Asio_otus', 'Alcedo_atthis', 'Falco_tinnunculus', 'Falco_amurensis', 'Falco_subbuteo', 'Falco_cherrug', 'Falco_peregrinus', 'Lanius_bucephalus', 'Dicrurus_macrocercus', 'Cyanopica_cyanus', 'Pica_serica', 'Corvus_frugilegus', 'Corvus_corone', 'Corvus_macrorhynchos', 'Pycnonotus_sinensis', 'Phylloscopus_inornatus', 'Phylloscopus_proregulus', 'Phylloscopus_armandii', 'Phylloscopus_fuscatus', 'Phylloscopus_claudiae', 'Zosterops_erythropleurus', 'Zosterops_simplex', 'Spodiopsar_cineraceus', 'Agropsar_sturninus', 'Turdus_hortulorum', 'Turdus_ruficollis', 'Tarsiger_cyanurus', 'Ficedula_albicilla', 'Phoenicurus_auroreus', 'Passer_montanus', 'Motacilla_tschutschensis', 'Motacilla_citreola', 'Motacilla_cinerea', 'Motacilla_alba', 'Anthus_rufulus', 'Anthus_hodgsoni', 'Anthus_spinoletta', 'Emberiza_tristrami', 'Emberiza_chrysophrys', 'Emberiza_rustica', 'Coloeus_dauuricus', 'Spilopelia_chinensis', 'Larus_vegae', 'Bubulcus_coromandus', 'Ciconia_boyciana','ANSERIFORMES', 'Anser_anser', 'Anser_cygnoides', 'Anser_fabalis', 'Cygnus_cygnus', 'Tadorna_tadorna', 'Tadorna_ferruginea', 'Aix_galericulata', 'Sibirionetta_formosa', 'Spatula_querquedula', 'Spatula_clypeata', 'Mareca_strepera', 'Mareca_falcata', 'Mareca_penelope', 'Anas_zonorhyncha', 'Anas_platyrhynchos', 'Anas_acuta', 'Anas_crecca', 'Aythya_ferina', 'Aythya_baeri', 'Aythya_nyroca', 'Aythya_fuligula', 'Bucephala_clangula', 'Mergellus_albellus', 'Mergus_merganser', 'Phasianus_colchicus', 'Tachybaptus_ruficollis', 'Podiceps_cristatus', 'Ciconia_nigra', 'Platalea_leucorodia', 'Botaurus_stellaris', 'Ixobrychus_sinensis', 'Ixobrychus_cinnamomeus', 'Nycticorax_nycticorax', 'Butorides_striata', 'Ardeola_bacchus', 'Ardea_cinerea', 'Ardea_purpurea', 'Ardea_alba', 'Ardea_intermedia', 'Egretta_garzetta', 'Phalacrocorax_carbo', 'Elanus_caeruleus', 'Pernis_ptilorhynchus', 'Clanga_clanga', 'Aquila_chrysaetos', 'Accipiter_gularis', 'Accipiter_nisus', 'Circus_aeruginosus', 'Circus_spilonotus', 'Circus_cyaneus', 'Milvus_migrans', 'Haliaeetus_albicilla', 'Buteo_lagopus', 'Buteo_japonicus', 'Otis_tarda', 'Rallus_indicus', 'Gallinula_chloropus', 'Fulica_atra', 'Amaurornis_phoenicurus', 'Antigone_vipio', 'Grus_grus', 'Himantopus_himantopus', 'Vanellus_vanellus', 'Vanellus_cinereus', 'Charadrius_dubius', 'Limosa_limosa', 'Calidris_subminuta', 'Scolopax_rusticola', 'Gallinago_gallinago', 'Actitis_hypoleucos', 'Tringa_ochropus', 'Tringa_glareola', 'Tringa_erythropus', 'Tringa_nebularia', 'Chroicocephalus_ridibundus', 'Sterna_hirundo', 'Chlidonias_hybrida', 'Asio_otus', 'Alcedo_atthis', 'Falco_tinnunculus', 'Falco_amurensis', 'Falco_subbuteo', 'Falco_cherrug', 'Falco_peregrinus', 'Lanius_bucephalus', 'Dicrurus_macrocercus', 'Cyanopica_cyanus', 'Pica_serica', 'Corvus_frugilegus', 'Corvus_corone', 'Corvus_macrorhynchos', 'Pycnonotus_sinensis', 'Phylloscopus_inornatus', 'Phylloscopus_proregulus', 'Phylloscopus_armandii', 'Phylloscopus_fuscatus', 'Phylloscopus_claudiae', 'Zosterops_erythropleurus', 'Zosterops_simplex', 'Spodiopsar_cineraceus', 'Agropsar_sturninus', 'Turdus_hortulorum', 'Turdus_ruficollis', 'Tarsiger_cyanurus', 'Ficedula_albicilla', 'Phoenicurus_auroreus', 'Passer_montanus', 'Motacilla_tschutschensis', 'Motacilla_citreola', 'Motacilla_cinerea', 'Motacilla_alba', 'Anthus_rufulus', 'Anthus_hodgsoni', 'Anthus_spinoletta', 'Emberiza_tristrami', 'Emberiza_chrysophrys', 'Emberiza_rustica', 'Coloeus_dauuricus', 'Spilopelia_chinensis', 'Larus_vegae', 'Bubulcus_coromandus', 'Ciconia_boyciana','ANSERIFORMES', 'Anser_anser', 'Anser_cygnoides', 'Anser_fabalis', 'Cygnus_cygnus', 'Tadorna_tadorna', 'Tadorna_ferruginea', 'Aix_galericulata', 'Sibirionetta_formosa', 'Spatula_querquedula', 'Spatula_clypeata', 'Mareca_strepera', 'Mareca_falcata', 'Mareca_penelope', 'Anas_zonorhyncha', 'Anas_platyrhynchos', 'Anas_acuta', 'Anas_crecca', 'Aythya_ferina', 'Aythya_baeri', 'Aythya_nyroca', 'Aythya_fuligula', 'Bucephala_clangula', 'Mergellus_albellus', 'Mergus_merganser', 'Phasianus_colchicus', 'Tachybaptus_ruficollis', 'Podiceps_cristatus', 'Ciconia_nigra', 'Platalea_leucorodia', 'Botaurus_stellaris', 'Ixobrychus_sinensis', 'Ixobrychus_cinnamomeus', 'Nycticorax_nycticorax', 'Butorides_striata', 'Ardeola_bacchus', 'Ardea_cinerea', 'Ardea_purpurea', 'Ardea_alba', 'Ardea_intermedia', 'Egretta_garzetta', 'Phalacrocorax_carbo', 'Elanus_caeruleus', 'Pernis_ptilorhynchus', 'Clanga_clanga', 'Aquila_chrysaetos', 'Accipiter_gularis', 'Accipiter_nisus', 'Circus_aeruginosus', 'Circus_spilonotus', 'Circus_cyaneus', 'Milvus_migrans', 'Haliaeetus_albicilla', 'Buteo_lagopus', 'Buteo_japonicus', 'Otis_tarda', 'Rallus_indicus', 'Gallinula_chloropus', 'Fulica_atra', 'Amaurornis_phoenicurus', 'Antigone_vipio', 'Grus_grus', 'Himantopus_himantopus', 'Vanellus_vanellus', 'Vanellus_cinereus', 'Charadrius_dubius', 'Limosa_limosa', 'Calidris_subminuta', 'Scolopax_rusticola', 'Gallinago_gallinago', 'Actitis_hypoleucos', 'Tringa_ochropus', 'Tringa_glareola', 'Tringa_erythropus', 'Tringa_nebularia', 'Chroicocephalus_ridibundus', 'Sterna_hirundo', 'Chlidonias_hybrida', 'Asio_otus', 'Alcedo_atthis', 'Falco_tinnunculus', 'Falco_amurensis', 'Falco_subbuteo', 'Falco_cherrug', 'Falco_peregrinus', 'Lanius_bucephalus', 'Dicrurus_macrocercus', 'Cyanopica_cyanus', 'Pica_serica', 'Corvus_frugilegus', 'Corvus_corone', 'Corvus_macrorhynchos', 'Pycnonotus_sinensis', 'Phylloscopus_inornatus', 'Phylloscopus_proregulus', 'Phylloscopus_armandii', 'Phylloscopus_fuscatus', 'Phylloscopus_claudiae', 'Zosterops_erythropleurus', 'Zosterops_simplex', 'Spodiopsar_cineraceus', 'Agropsar_sturninus', 'Turdus_hortulorum', 'Turdus_ruficollis', 'Tarsiger_cyanurus', 'Ficedula_albicilla', 'Phoenicurus_auroreus', 'Passer_montanus', 'Motacilla_tschutschensis', 'Motacilla_citreola', 'Motacilla_cinerea', 'Motacilla_alba', 'Anthus_rufulus', 'Anthus_hodgsoni', 'Anthus_spinoletta', 'Emberiza_tristrami', 'Emberiza_chrysophrys', 'Emberiza_rustica', 'Coloeus_dauuricus', 'Spilopelia_chinensis', 'Larus_vegae', 'Bubulcus_coromandus', 'Ciconia_boyciana','ANSERIFORMES', 'Anser_anser', 'Anser_cygnoides', 'Anser_fabalis', 'Cygnus_cygnus', 'Tadorna_tadorna', 'Tadorna_ferruginea', 'Aix_galericulata', 'Sibirionetta_formosa', 'Spatula_querquedula', 'Spatula_clypeata', 'Mareca_strepera', 'Mareca_falcata', 'Mareca_penelope', 'Anas_zonorhyncha', 'Anas_platyrhynchos', 'Anas_acuta', 'Anas_crecca', 'Aythya_ferina', 'Aythya_baeri', 'Aythya_nyroca', 'Aythya_fuligula', 'Bucephala_clangula', 'Mergellus_albellus', 'Mergus_merganser', 'Phasianus_colchicus', 'Tachybaptus_ruficollis', 'Podiceps_cristatus', 'Ciconia_nigra', 'Platalea_leucorodia', 'Botaurus_stellaris', 'Ixobrychus_sinensis', 'Ixobrychus_cinnamomeus', 'Nycticorax_nycticorax', 'Butorides_striata', 'Ardeola_bacchus', 'Ardea_cinerea', 'Ardea_purpurea', 'Ardea_alba', 'Ardea_intermedia', 'Egretta_garzetta', 'Phalacrocorax_carbo', 'Elanus_caeruleus', 'Pernis_ptilorhynchus', 'Clanga_clanga', 'Aquila_chrysaetos', 'Accipiter_gularis', 'Accipiter_nisus', 'Circus_aeruginosus', 'Circus_spilonotus', 'Circus_cyaneus', 'Milvus_migrans', 'Haliaeetus_albicilla', 'Buteo_lagopus', 'Buteo_japonicus', 'Otis_tarda', 'Rallus_indicus', 'Gallinula_chloropus', 'Fulica_atra', 'Amaurornis_phoenicurus', 'Antigone_vipio', 'Grus_grus', 'Himantopus_himantopus', 'Vanellus_vanellus', 'Vanellus_cinereus', 'Charadrius_dubius', 'Limosa_limosa', 'Calidris_subminuta', 'Scolopax_rusticola', 'Gallinago_gallinago', 'Actitis_hypoleucos', 'Tringa_ochropus', 'Tringa_glareola', 'Tringa_erythropus', 'Tringa_nebularia', 'Chroicocephalus_ridibundus', 'Sterna_hirundo', 'Chlidonias_hybrida', 'Asio_otus', 'Alcedo_atthis', 'Falco_tinnunculus', 'Falco_amurensis', 'Falco_subbuteo', 'Falco_cherrug', 'Falco_peregrinus', 'Lanius_bucephalus', 'Dicrurus_macrocercus', 'Cyanopica_cyanus', 'Pica_serica', 'Corvus_frugilegus', 'Corvus_corone', 'Corvus_macrorhynchos', 'Pycnonotus_sinensis', 'Phylloscopus_inornatus', 'Phylloscopus_proregulus', 'Phylloscopus_armandii', 'Phylloscopus_fuscatus', 'Phylloscopus_claudiae', 'Zosterops_erythropleurus', 'Zosterops_simplex', 'Spodiopsar_cineraceus', 'Agropsar_sturninus', 'Turdus_hortulorum', 'Turdus_ruficollis', 'Tarsiger_cyanurus', 'Ficedula_albicilla', 'Phoenicurus_auroreus', 'Passer_montanus', 'Motacilla_tschutschensis', 'Motacilla_citreola', 'Motacilla_cinerea', 'Motacilla_alba', 'Anthus_rufulus', 'Anthus_hodgsoni', 'Anthus_spinoletta', 'Emberiza_tristrami', 'Emberiza_chrysophrys', 'Emberiza_rustica', 'Coloeus_dauuricus', 'Spilopelia_chinensis', 'Larus_vegae', 'Bubulcus_coromandus', 'Ciconia_boyciana'] + #BHG_chineseName =['Person', 'Bird', 'Caprinae', 'Dog', 'Horse', 'Accipiter_nisus', 'Aquila_nipalensis', 'Bos_mutus', 'Bubo_bubo', 'Buteo_hemilasius', 'Canis_lupus', 'Carpodacus_rubicilla', 'Carpodacus_puniceus', 'Cervus_canadensis', 'Corvus_corax', 'Corvus_corone', 'Emberiza_cia', 'Falco_peregrinus', 'Gypaetus_barbatus', 'Gyps_himalayensis', 'Lepus_oiostolus', 'Marmota_bobak', 'Martes_foina', 'Monticola_semirufus', 'Montifringilla_adamsi', 'Moschus_chrysogaster', 'Mustela_eversmanii', 'Ochotona_curzoniae', 'Onychostruthus_taczanowskii', 'Otocolobus_manul', 'Panthera_uncia', 'Perdix_hodgsoniae', 'Phoenicurus_erythrogastrus', 'Phoenicurus_frontalis', 'Phoenicurus_ochruros', 'Pica_serica', 'Prunella_collaris', 'Prunella_himalayana', 'Prunella_rubeculoides', 'Przewalskium_albirostris', 'Pseudois_nayaur', 'Pseudopodoces_humilis', 'Pyrgilauda_ruficollis', 'Pyrrhocorax_pyrrhocorax', 'Tetraogallus_tibetanus', 'Turdus_kessleri', 'Turdus_obscurus', 'Upupa_epops', 'Ursus_arctos', 'Vulpes_ferrilata', 'Vulpes_vulpes', 'Neofelis_nebulosa'] + BHG_chineseName=['鸟', '羊', '狗', '马', '人', '雀鹰', '牦牛', '雕鸮', '大鵟', '狼', '大朱雀', '红胸朱雀', '渡鸦', '灰眉岩鹀', '胡兀鹫', '高山兀鹫', '高原兔', '旱獭', '石貂', '褐翅雪雀', '马麝', '艾鼬', '高原鼠兔', '白腰雪雀', '兔狲', '雪豹', '高原山鹑', '红腹红尾鸲', '蓝额红尾鸲', '赭红尾鸲', '喜鹊', '领岩鹨', '高原岩鹨', '鸲岩鹨', '白唇鹿', '岩羊', '地山雀', '棕颈雪雀', '藏雪鸡', '棕背黑头鸫', '白眉鸫', '戴胜', '棕熊', '藏狐', ' 赤狐', '豹猫', '红嘴山鸦', '白唇鹿', '岩羊', '地山雀', '棕颈雪雀', '藏雪鸡', '棕背黑头鸫', '白眉鸫', '戴胜', '棕熊', '藏狐', ' 赤狐', '豹猫', '红嘴山鸦', '白唇鹿', '岩羊', '地山雀', '棕颈雪雀', '藏雪鸡', '棕背黑头鸫', '白眉鸫', '戴胜', '棕熊', '藏狐', ' 赤狐', '豹猫', '红嘴山鸦'] + FineClassNum = 169 - BHG_chineseName = ['Kong', '白额雁', '白骨顶', '苍鹭', '苍鹭', '白秋沙鸭', '白腰草鹬', '斑头雁', '斑嘴鸭', '苍鹭', '赤膀鸭', '赤颈鸭', '苍鹭', '大麻鳽', - '豆雁', '反嘴鹬', '凤头鸊鷉', '凤头麦鸡', '凤头潜鸭', '黑鹳', '黑水鸡', '红嘴鸥', '鸿雁', '灰鹤', '灰雁', '绿翅鸭', '绿头鸭', '琵嘴鸭', - '普通鸬鹚', '普通秋沙鸭', '翘鼻麻鸭', '鹊鸭', '扇尾沙锥', '小白额雁', '小天鹅', '针尾鸭', '苍鹭', '暗绿绣眼鸟', '八哥', '白腹鹞', '白鹡鸰', - '白眼潜鸭', '草鹭', '池鹭', '戴胜', '黑翅长脚鹬', '黑鸢', '红隼', '花脸鸭', '环颈雉', '灰头绿啄木鸟', '灰头麦鸡', '矶鹬', '栗苇鳽', - '罗纹鸭', '牛背鹭', '普通翠鸟', '雀鹰', '喜鹊', '苍鹭', '鸳鸯', '棕背伯劳', '红胸秋沙鸭', '普通燕鸥', '小白额燕鸥', '丘鹬', '凤头蜂鹰', - '大天鹅', '大鸨', '小田鸡', '山斑鸠', '帆背潜鸭', '日本松雀鹰', '普通鵟', '松雀鹰', '毛脚鵟', '灰斑鸠', '白头鹞', '白尾鹞', '白眉鸭', - '白鹈鹕', '红头潜鸭', '苍鹰', '蒙古银鸥', '西方秧鸡', '赤嘴潜鸭', '阔嘴鹬', '雕鸮', '鹌鹑', '鹗', '黄苇鳽', '黑颈鹤', '小䴙䴘', '赤麻鸭'] - # BHG_chineseName =["kong","绿头鸭","斑嘴鸭","灰雁","鸿雁","kong","小鷿鷈"] + # BJYYH + # DetWeight = "/data5/Hatcher/data/Detection_weigth/20232/20230204-121567-pixel1000-BJHR_Person_yolov5s6/weights/best.pt" + # FineWeight = "/data5/Hatcher/data/weigth/areaproject_224_202302/convnext_base_in22k-CMB_BJYYH_20230223_64_118883/_22317_Project/best.pth" + # BHG_chineseName = ['Bird', 'Person', 'Other_Object', 'ANSERIFORMES', 'Phasianus_colchicus', 'Anser_fabalis', 'Anser_cygnoides', 'Anser_anser', 'Anser_erythropus', 'Cygnus_olor', 'Cygnus_columbianus', 'Cygnus_cygnus', 'Anas_zonorhyncha', 'Tadorna_ferruginea', 'Aix_galericulata', 'Mareca_strepera', 'Mareca_falcata', 'Anas_platyrhynchos', 'Netta_rufina', 'Aythya_ferina', 'Aythya_fuligula', 'Mergus_merganser', 'Tachybaptus_ruficollis', 'Podiceps_cristatus', 'Gallinula_chloropus', 'Fulica_atra', 'Leucogeranus_leucogeranus', 'Grus_virgo', 'Grus_japonensis', 'Grus_grus', 'Grus_monacha', 'Himantopus_himantopus', 'Calidris_falcinellus', 'Recurvirostra_avosetta', 'Charadrius_alexandrinus', 'Scolopax_rusticola', 'Limosa_limosa', 'Tringa_ochropus', 'Actitis_hypoleucos', 'Calidris_subminuta', 'Chroicocephalus_brunnicephalus', 'Chroicocephalus_ridibundus', 'Ciconia_boyciana', 'Phalacrocorax_carbo', 'Platalea_leucorodia', 'Ixobrychus_sinensis', 'Nycticorax_nycticorax', 'Ardeola_bacchus', 'Ardea_cinerea', 'Ardea_purpurea', 'Ardea_alba', 'Ardea_intermedia', 'Egretta_garzetta', 'Aegypius_monachus', 'Accipiter_gularis', 'Haliaeetus_albicilla', 'Alcedo_atthis', 'Dicrurus_macrocercus', 'Cyanopica_cyanus', 'Corvus_frugilegus', 'Passer_montanus', 'Antigone_vipio', 'Otis_tarda', 'Pica_serica', 'Mergellus_albellus', 'Aythya_baeri', 'Tadorna_tadorna', 'Pelecanus_crispus', 'Buteo_japonicus', 'Elanus_caeruleus', 'Phylloscopus_claudiae', 'Falco_tinnunculus', 'Ficedula_zanthopygia', 'Falco_cherrug', 'Falco_peregrinus', 'Phylloscopus_armandii', 'Emberiza_rustica', 'Mergus_squamatus', 'Spodiopsar_cineraceus', 'Tringa_erythropus', 'Anthus_rufulus', 'Charadrius_dubius', 'Asio_otus', 'Motacilla_alba', 'Platalea_minor', 'Sterna_hirundo', 'Clanga_clanga', 'Bubo_bubo', 'Circus_cyaneus', 'Emberiza_tristrami', 'Botaurus_stellaris', 'Mergus_serrator', 'Ciconia_nigra', 'Motacilla_cinerea', 'Tarsiger_cyanurus', 'Coloeus_dauuricus', 'Turdus_pallidus', 'Milvus_migrans', 'Aquila_heliaca', 'Clangula_hyemalis', 'Spilopelia_chinensis', 'Rallus_indicus', 'Sitta_villosa', 'Falco_amurensis', 'Vanellus_vanellus', 'Phoenicurus_auroreus', 'Pluvialis_squatarola', 'Bucephala_clangula', 'Anas_acuta', 'Hydrophasianus_chirurgus', 'Terpsiphone_incei', 'Phylloscopus_proregulus', 'Aythya_nyroca', 'Gallinago_gallinago', 'Calidris_alpina', 'Gelochelidon_nilotica', 'Phylloscopus_inornatus', 'Tringa_glareola', 'Podiceps_nigricollis', 'Ixobrychus_cinnamomeus', 'Numenius_phaeopus', 'Agropsar_sturninus', 'Pernis_ptilorhynchus', 'Columba_rupestris', 'Lanius_bucephalus', 'Emberiza_chrysophrys', 'Motacilla_citreola', 'Larus_crassirostris', 'Accipiter_nisus', 'Rhopophilus_pekinensis', 'Amaurornis_phoenicurus', 'Coccothraustes_coccothraustes', 'Pycnonotus_sinensis', 'Emberiza_cia', 'Butorides_striata', 'Ficedula_albicilla', 'Anas_crecca', 'Falco_subbuteo', 'Sibirionetta_formosa', 'Emberiza_cioides', 'Vanellus_cinereus', 'Phylloscopus_fuscatus', 'Spatula_querquedula', 'Halcyon_pileata', 'Chlidonias_hybrida', 'Spodiopsar_sericeus', 'Podiceps_auritus', 'Anthus_spinoletta', 'Aquila_chrysaetos', 'Turdus_hortulorum', 'Buteo_lagopus', 'Zosterops_erythropleurus', 'Anthus_hodgsoni', 'Spatula_clypeata', 'Glareola_maldivarum', 'Motacilla_tschutschensis', 'Bombycilla_garrulus', 'Zosterops_simplex', 'Aythya_marila', 'Larus_vegae', 'Bubulcus_coromandus', 'Sitta_europaea', 'Anser_indicus', 'Mareca_penelope', 'Tringa_nebularia', 'Fregata_ariel', 'Circus_spilonotus', 'Corvus_corone'] + # FineClassNum = 64 + + # PYH + # DetWeight = "/data1/Hatcher/model/Detection/yolov5/runs/train/BeijingCuiHu-Bird26/weights/best.pt" + # FineWeight = "/data/Hatcher/data/weigth/areaproject/VIT-BJCH_Bird_94_DDP/_5914_CUI-94-1/best.pth" + # BHG_chineseName = ['Bird', 'Person', 'Other_Object', 'ANSERIFORMES', 'Phasianus_colchicus', 'Anser_fabalis', 'Anser_cygnoides', 'Anser_anser', 'Anser_erythropus', 'Cygnus_olor', 'Cygnus_columbianus', 'Cygnus_cygnus', 'Anas_zonorhyncha', 'Tadorna_ferruginea', 'Aix_galericulata', 'Mareca_strepera', 'Mareca_falcata', 'Anas_platyrhynchos', 'Netta_rufina', 'Aythya_ferina', 'Aythya_fuligula', 'Mergus_merganser', 'Tachybaptus_ruficollis', 'Podiceps_cristatus', 'Gallinula_chloropus', 'Fulica_atra', 'Leucogeranus_leucogeranus', 'Grus_virgo', 'Grus_japonensis', 'Grus_grus', 'Grus_monacha', 'Himantopus_himantopus', 'Calidris_falcinellus', 'Recurvirostra_avosetta', 'Charadrius_alexandrinus', 'Scolopax_rusticola', 'Limosa_limosa', 'Tringa_ochropus', 'Actitis_hypoleucos', 'Calidris_subminuta', 'Chroicocephalus_brunnicephalus', 'Chroicocephalus_ridibundus', 'Ciconia_boyciana', 'Phalacrocorax_carbo', 'Platalea_leucorodia', 'Ixobrychus_sinensis', 'Nycticorax_nycticorax', 'Ardeola_bacchus', 'Ardea_cinerea', 'Ardea_purpurea', 'Ardea_alba', 'Ardea_intermedia', 'Egretta_garzetta', 'Aegypius_monachus', 'Accipiter_gularis', 'Haliaeetus_albicilla', 'Alcedo_atthis', 'Dicrurus_macrocercus', 'Cyanopica_cyanus', 'Corvus_frugilegus', 'Passer_montanus', 'Antigone_vipio', 'Otis_tarda', 'Pica_serica', 'Mergellus_albellus', 'Aythya_baeri', 'Tadorna_tadorna', 'Pelecanus_crispus', 'Buteo_japonicus', 'Elanus_caeruleus', 'Phylloscopus_claudiae', 'Falco_tinnunculus', 'Ficedula_zanthopygia', 'Falco_cherrug', 'Falco_peregrinus', 'Phylloscopus_armandii', 'Emberiza_rustica', 'Mergus_squamatus', 'Spodiopsar_cineraceus', 'Tringa_erythropus', 'Anthus_rufulus', 'Charadrius_dubius', 'Asio_otus', 'Motacilla_alba', 'Platalea_minor', 'Sterna_hirundo', 'Clanga_clanga', 'Bubo_bubo', 'Circus_cyaneus', 'Emberiza_tristrami', 'Botaurus_stellaris', 'Mergus_serrator', 'Ciconia_nigra', 'Motacilla_cinerea', 'Tarsiger_cyanurus', 'Coloeus_dauuricus', 'Turdus_pallidus', 'Milvus_migrans', 'Aquila_heliaca', 'Clangula_hyemalis', 'Spilopelia_chinensis', 'Rallus_indicus', 'Sitta_villosa', 'Falco_amurensis', 'Vanellus_vanellus', 'Phoenicurus_auroreus', 'Pluvialis_squatarola', 'Bucephala_clangula', 'Anas_acuta', 'Hydrophasianus_chirurgus', 'Terpsiphone_incei', 'Phylloscopus_proregulus', 'Aythya_nyroca', 'Gallinago_gallinago', 'Calidris_alpina', 'Gelochelidon_nilotica', 'Phylloscopus_inornatus', 'Tringa_glareola', 'Podiceps_nigricollis', 'Ixobrychus_cinnamomeus', 'Numenius_phaeopus', 'Agropsar_sturninus', 'Pernis_ptilorhynchus', 'Columba_rupestris', 'Lanius_bucephalus', 'Emberiza_chrysophrys', 'Motacilla_citreola', 'Larus_crassirostris', 'Accipiter_nisus', 'Rhopophilus_pekinensis', 'Amaurornis_phoenicurus', 'Coccothraustes_coccothraustes', 'Pycnonotus_sinensis', 'Emberiza_cia', 'Butorides_striata', 'Ficedula_albicilla', 'Anas_crecca', 'Falco_subbuteo', 'Sibirionetta_formosa', 'Emberiza_cioides', 'Vanellus_cinereus', 'Phylloscopus_fuscatus', 'Spatula_querquedula', 'Halcyon_pileata', 'Chlidonias_hybrida', 'Spodiopsar_sericeus', 'Podiceps_auritus', 'Anthus_spinoletta', 'Aquila_chrysaetos', 'Turdus_hortulorum', 'Buteo_lagopus', 'Zosterops_erythropleurus', 'Anthus_hodgsoni', 'Spatula_clypeata', 'Glareola_maldivarum', 'Motacilla_tschutschensis', 'Bombycilla_garrulus', 'Zosterops_simplex', 'Aythya_marila', 'Larus_vegae', 'Bubulcus_coromandus', 'Sitta_europaea', 'Anser_indicus', 'Mareca_penelope', 'Tringa_nebularia', 'Fregata_ariel', 'Circus_spilonotus', 'Corvus_corone'] + # FineClassNum = 64 + + # BJHR + # DetWeight = '/data1/sf/code/data_MPKFNet/weights/CuiHu/nest/20230216-201-BJCH_niaochao_yolov5n4.pt' + # FineWeight = "/data5/Hatcher/data/weigth/areaproject_224_202302/convnext_base_in22k-CMB_BJYYH_20230223_64_118883/_22317_Project/best.pth" #/data/Hatcher/data/weigth/areaproject_224/convnext_base_in22k-YNDC224-bird-21-57030-RP-RC-RP-RR-RH-RC/_10259_YNDC40/best.pth" + # BHG_chineseName = ['Bird', 'Person', 'Other_Object', 'ANSERIFORMES', 'Phasianus_colchicus', 'Anser_fabalis', 'Anser_cygnoides', 'Anser_anser', 'Anser_erythropus', 'Cygnus_olor', 'Cygnus_columbianus', 'Cygnus_cygnus', 'Anas_zonorhyncha', 'Tadorna_ferruginea', 'Aix_galericulata', 'Mareca_strepera', 'Mareca_falcata', 'Anas_platyrhynchos', 'Netta_rufina', 'Aythya_ferina', 'Aythya_fuligula', 'Mergus_merganser', 'Tachybaptus_ruficollis', 'Podiceps_cristatus', 'Gallinula_chloropus', 'Fulica_atra', 'Leucogeranus_leucogeranus', 'Grus_virgo', 'Grus_japonensis', 'Grus_grus', 'Grus_monacha', 'Himantopus_himantopus', 'Calidris_falcinellus', 'Recurvirostra_avosetta', 'Charadrius_alexandrinus', 'Scolopax_rusticola', 'Limosa_limosa', 'Tringa_ochropus', 'Actitis_hypoleucos', 'Calidris_subminuta', 'Chroicocephalus_brunnicephalus', 'Chroicocephalus_ridibundus', 'Ciconia_boyciana', 'Phalacrocorax_carbo', 'Platalea_leucorodia', 'Ixobrychus_sinensis', 'Nycticorax_nycticorax', 'Ardeola_bacchus', 'Ardea_cinerea', 'Ardea_purpurea', 'Ardea_alba', 'Ardea_intermedia', 'Egretta_garzetta', 'Aegypius_monachus', 'Accipiter_gularis', 'Haliaeetus_albicilla', 'Alcedo_atthis', 'Dicrurus_macrocercus', 'Cyanopica_cyanus', 'Corvus_frugilegus', 'Passer_montanus', 'Antigone_vipio', 'Otis_tarda', 'Pica_serica', 'Mergellus_albellus', 'Aythya_baeri', 'Tadorna_tadorna', 'Pelecanus_crispus', 'Buteo_japonicus', 'Elanus_caeruleus', 'Phylloscopus_claudiae', 'Falco_tinnunculus', 'Ficedula_zanthopygia', 'Falco_cherrug', 'Falco_peregrinus', 'Phylloscopus_armandii', 'Emberiza_rustica', 'Mergus_squamatus', 'Spodiopsar_cineraceus', 'Tringa_erythropus', 'Anthus_rufulus', 'Charadrius_dubius', 'Asio_otus', 'Motacilla_alba', 'Platalea_minor', 'Sterna_hirundo', 'Clanga_clanga', 'Bubo_bubo', 'Circus_cyaneus', 'Emberiza_tristrami', 'Botaurus_stellaris', 'Mergus_serrator', 'Ciconia_nigra', 'Motacilla_cinerea', 'Tarsiger_cyanurus', 'Coloeus_dauuricus', 'Turdus_pallidus', 'Milvus_migrans', 'Aquila_heliaca', 'Clangula_hyemalis', 'Spilopelia_chinensis', 'Rallus_indicus', 'Sitta_villosa', 'Falco_amurensis', 'Vanellus_vanellus', 'Phoenicurus_auroreus', 'Pluvialis_squatarola', 'Bucephala_clangula', 'Anas_acuta', 'Hydrophasianus_chirurgus', 'Terpsiphone_incei', 'Phylloscopus_proregulus', 'Aythya_nyroca', 'Gallinago_gallinago', 'Calidris_alpina', 'Gelochelidon_nilotica', 'Phylloscopus_inornatus', 'Tringa_glareola', 'Podiceps_nigricollis', 'Ixobrychus_cinnamomeus', 'Numenius_phaeopus', 'Agropsar_sturninus', 'Pernis_ptilorhynchus', 'Columba_rupestris', 'Lanius_bucephalus', 'Emberiza_chrysophrys', 'Motacilla_citreola', 'Larus_crassirostris', 'Accipiter_nisus', 'Rhopophilus_pekinensis', 'Amaurornis_phoenicurus', 'Coccothraustes_coccothraustes', 'Pycnonotus_sinensis', 'Emberiza_cia', 'Butorides_striata', 'Ficedula_albicilla', 'Anas_crecca', 'Falco_subbuteo', 'Sibirionetta_formosa', 'Emberiza_cioides', 'Vanellus_cinereus', 'Phylloscopus_fuscatus', 'Spatula_querquedula', 'Halcyon_pileata', 'Chlidonias_hybrida', 'Spodiopsar_sericeus', 'Podiceps_auritus', 'Anthus_spinoletta', 'Aquila_chrysaetos', 'Turdus_hortulorum', 'Buteo_lagopus', 'Zosterops_erythropleurus', 'Anthus_hodgsoni', 'Spatula_clypeata', 'Glareola_maldivarum', 'Motacilla_tschutschensis', 'Bombycilla_garrulus', 'Zosterops_simplex', 'Aythya_marila', 'Larus_vegae', 'Bubulcus_coromandus', 'Sitta_europaea', 'Anser_indicus', 'Mareca_penelope', 'Tringa_nebularia', 'Fregata_ariel', 'Circus_spilonotus', 'Corvus_corone'] + # FineClassNum = 64 + + # DetWeight = "/data5/Hatcher/data/Detection_weigth/2023033090/CDB_HHK/20230306-10065_yolov5s6_640_30902/weights/best.pt" + # FineWeight = "/data5/Hatcher/data/weigth/areaproject_224_202302/convnext_base_in22k-CMB_BJYYH_20230223_64_118883/_22317_Project/best.pth" #/data/Hatcher/data/weigth/areaproject_224/convnext_base_in22k-YNDC224-bird-21-57030-RP-RC-RP-RR-RH-RC/_10259_YNDC40/best.pth" + # BHG_chineseName = ['Bird','Person_Boat_Milu','ANSERIFORMES','Ardeidae','PASSERIFORMES','Scolopacidae','GRUIFORMES','Columba_rupestris','Egretta_garzetta','Ardea_cinerea','Pavonini','Corvus_corone','Ciconia_boyciana','Pica_serica','Cyanopica_cyanus','Aix_galericulata','Tringa_ochropus','Himantopus_himantopus','Anser_cygnoides','Anas_platyrhynchos','Anas_zonorhyncha','Tadorna_ferruginea','Grus_grus','Cygnus_atratus','Haliaeetus_albicilla','Coloeus_dauuricus','Corvus_frugilegus','Corvus_macrorhynchos'] + + # DetWeight = "/data5/Hatcher/data/Detection_weigth/20232/20230226-71327-pixel10000-BJYYH_yolov5s6_21764/weights/best.pt" #"/data2080/Hatcher/data/Detection_weigth/20221018/20221107-42624-BJCH_YNDC-Bird-4-42624-2176-s-base8/weights/best.pt" #"/data/Hatcher/data/Detection_weigth/BASE_PYH_SJH-Bird-1-45328-2160-s-base9/weights/best.pt" + # FineWeight = "/data5/Hatcher/data/weigth/areaproject_224_202302/convnext_base_in22k-CMB_BJYYH_20230223_64_118883/_22317_Project/best.pth" #/data/Hatcher/data/weigth/areaproject_224/convnext_base_in22k-YNDC224-bird-21-57030-RP-RC-RP-RR-RH-RC/_10259_YNDC40/best.pth" + # BHG_chineseName = ['Bird', 'ANSERIFORMES', 'Ciconia_boyciana', 'Egretta_garzetta', 'Fulica_atra', 'Ardea_cinerea', 'Himantopus_himantopus', 'Mergellus_albellus', 'Recurvirostra_avosetta', 'Platalea_leucorodia', 'Chroicocephalus_saundersi', 'Anser_anser', 'Haematopus_ostralegus', 'Anas_platyrhynchos', 'Sterna_hirundo', 'Tadorna_tadorna', 'Anas_zonorhyncha', 'Podiceps_cristatus', 'Gelochelidon_nilotica', 'Phalacrocorax_carbo', 'Larus_crassirostris', 'Tadorna_ferruginea', 'Pica_serica', 'Ardea_intermedia', 'Phasianus_colchicus', 'Ardea_purpurea', 'Limosa_limosa', 'Cygnus_cygnus'] + + # DetWeight = "/data3/lwz/project/mmaction2/mmdetection/work_dirs/yolox_20230302/latest.pth" #"/data2080/Hatcher/data/Detection_weigth/20221018/20221107-42624-BJCH_YNDC-Bird-4-42624-2176-s-base8/weights/best.pt" #"/data/Hatcher/data/Detection_weigth/BASE_PYH_SJH-Bird-1-45328-2160-s-base9/weights/best.pt" + # FineWeight = "/data5/Hatcher/data/weigth/areaproject_224_202302/convnext_base_in22k-CMB_BJYYH_20230223_64_118883/_22317_Project/best.pth" #/data/Hatcher/data/weigth/areaproject_224/convnext_base_in22k-YNDC224-bird-21-57030-RP-RC-RP-RR-RH-RC/_10259_YNDC40/best.pth" + # BHG_chineseName = ['others', 'Anser_albifrons', 'Fulica_atra', 'Egretta_garzetta', 'Platalea_leucorodia', 'Mergellus_albellus', 'Tringa_ochropus', 'Anser_indicus', 'Anas_zonorhyncha', 'Ardea_cinerea', 'Mareca_strepera', 'Mareca_penelope', 'Ardea_alba', 'Botaurus_stellaris', 'Anser_fabalis', 'Recurvirostra_avosetta', 'Podiceps_cristatus', 'Vanellus_vanellus', 'Aythya_fuligula', 'Ciconia_nigra', 'Gallinula_chloropus', 'Chroicocephalus_ridibundus', 'Anser_cygnoides', 'Grus_grus', 'Anser_anser', 'Anas_crecca', 'Anas_platyrhynchos', 'Spatula_clypeata', 'Phalacrocorax_carbo', 'Mergus_merganser', 'Tadorna_tadorna', 'Bucephala_clangula', 'Gallinago_gallinago', 'Anser_erythropus', 'Cygnus_columbianus', 'Anas_acuta', 'Ardea_intermedia', 'Zosterops_simplex', 'Acridotheres_cristatellus', 'Circus_spilonotus', 'Motacilla_alba', 'Aythya_nyroca', 'Ardea_purpurea', 'Ardeola_bacchus', 'Upupa_epops', 'Himantopus_himantopus', 'Milvus_migrans', 'Falco_tinnunculus', 'Sibirionetta_formosa', 'Phasianus_colchicus', 'Picus_canus', 'Vanellus_cinereus', 'Actitis_hypoleucos', 'Ixobrychus_cinnamomeus', 'Mareca_falcata', 'Bubulcus_coromandus', 'Alcedo_atthis', 'Accipiter_nisus', 'Pica_serica', 'Nycticorax_nycticorax', 'Aix_galericulata', 'Lanius_schach', 'Mergus_serrator', 'Sterna_hirundo', 'Sternula_antillarum', 'Scolopax_rusticola', 'Pernis_ptilorhynchus', 'Cygnus_cygnus', 'Otis_tarda', 'Zapornia_pusilla', 'Streptopelia_orientalis', 'Aythya_valisineria', 'Accipiter_gularis', 'Buteo_japonicus', 'Accipiter_virgatus', 'Buteo_lagopus', 'Streptopelia_decaocto', 'Circus_aeruginosus', 'Circus_cyaneus', 'Spatula_querquedula', 'Pelecanus_onocrotalus', 'Aythya_ferina', 'Accipiter_gentilis', 'Larus_cachinnans', 'Rallus_aquaticus', 'Netta_rufina', 'Calidris_falcinellus', 'Bubo_bubo', 'Coturnix_japonica', 'Pandion_haliaetus', 'Ixobrychus_sinensis', 'Grus_nigricollis', 'Tachybaptus_ruficollis', 'Tadorna_ferruginea'] + + # DensityWeight = "/data/Hatcher/data/Detection_weigth/BASE_PYH_SJH-Bird-1-45328-2160-s-base9/weights/best.pt" spiec_number_old = [0 for i in range(len(BHG_chineseName))] - FineClassNum = 94 color_show = (255, 255, 255) color_box = (255, 0, 0) - NoneLabel = None#"鹤类" # "鱼" - fine_thresh1 = 10000 - fine_thresh2 = 10000 + NoneLabel = None#"鸟"#"鹤类" # "鱼" + fine_thresh1 = 400 + fine_thresh2 = 400 + detect_Showthresh = 1000 ShowAllNumFlag = True - fontScale = 1 + fontScale = 2 + only_density = True #如果只进行密度估计,则将该标志位置1,并且将所有目标检测和细粒度识别的阈值都提高到很大 """ 1.change weight 2.change BHG_chineseName diff --git a/configs/__pycache__/configs.cpython-36.pyc b/configs/__pycache__/configs.cpython-36.pyc old mode 100644 new mode 100755 index b3e8706..92ac05b Binary files a/configs/__pycache__/configs.cpython-36.pyc and b/configs/__pycache__/configs.cpython-36.pyc differ diff --git a/configs/__pycache__/configs.cpython-37.pyc b/configs/__pycache__/configs.cpython-37.pyc new file mode 100755 index 0000000..083d541 Binary files /dev/null and b/configs/__pycache__/configs.cpython-37.pyc differ diff --git a/configs/__pycache__/configs.cpython-38.pyc b/configs/__pycache__/configs.cpython-38.pyc new file mode 100755 index 0000000..9912575 Binary files /dev/null and b/configs/__pycache__/configs.cpython-38.pyc differ diff --git a/configs/__pycache__/configs.cpython-39.pyc b/configs/__pycache__/configs.cpython-39.pyc new file mode 100755 index 0000000..546d132 Binary files /dev/null and b/configs/__pycache__/configs.cpython-39.pyc differ diff --git a/creat_coco_annotation.py b/creat_coco_annotation.py new file mode 100755 index 0000000..4a41b21 --- /dev/null +++ b/creat_coco_annotation.py @@ -0,0 +1,25 @@ +''' +author : Hatcher W +Email: hcwang@semi.ac.cn +use: 用于根据VOC的images中train和test的图像文件分成annotation 的xml文件,将Annotation分开放到Anno_train,Anno_val中, +input:images/train ,test 图像文件路径 +output:COCO/Anno_train and COCO/Anno_val +''' +import os,shutil +from tqdm import tqdm +rootPath = "/data4/Hatcher/smallobject/voc_class/CDB_vehicle/images/train" +rootPathxml = "/data4/Hatcher/smallobject/voc_class/CDB_vehicle/Annotations" +rootresultpath = "/data4/Hatcher/smallobject/voc_class/CDB_vehicle/COCO/Anno_train" +if not os.path.exists(rootresultpath): + os.makedirs(rootresultpath) +for image in tqdm(os.listdir(rootPath)): + shutil.copy(os.path.join(rootPathxml,image.replace(".jpg",".xml").replace(".png",".xml")),os.path.join(rootresultpath,image.replace(".jpg",".xml").replace(".png",".xml"))) + #exit() + +rootPath = "/data4/Hatcher/smallobject/voc_class/CDB_vehicle/images/test" +rootPathxml = "/data4/Hatcher/smallobject/voc_class/CDB_vehicle/Annotations" +rootresultpath = "/data4/Hatcher/smallobject/voc_class/CDB_vehicle/COCO/Anno_test" +if not os.path.exists(rootresultpath): + os.makedirs(rootresultpath) +for image in tqdm(os.listdir(rootPath)): + shutil.copy(os.path.join(rootPathxml,image.replace(".jpg",".xml").replace(".png",".xml")),os.path.join(rootresultpath,image.replace(".jpg",".xml").replace(".png",".xml"))) diff --git a/creat_xml.py b/creat_xml.py index 624df83..dd9ac97 100755 --- a/creat_xml.py +++ b/creat_xml.py @@ -13,7 +13,7 @@ class GEN_Annotations: self.root = etree.Element("annotation") child1 = etree.SubElement(self.root, "folder") - child1.text = "VOC2007" + child1.text = "./JPEGImages" child2 = etree.SubElement(self.root, "filename") child2.text = filename @@ -21,7 +21,7 @@ class GEN_Annotations: child3 = etree.SubElement(self.root, "source") child4 = etree.SubElement(child3, "annotation") - child4.text = "PASCAL VOC2007" + child4.text = "CDB" child5 = etree.SubElement(child3, "database") child5.text = "Unknown" diff --git a/creat_xml_fordetection.py b/creat_xml_fordetection.py index e3ee1a6..50206c0 100755 --- a/creat_xml_fordetection.py +++ b/creat_xml_fordetection.py @@ -7,8 +7,9 @@ output:xml文件 ''' import numpy as np from lxml import etree - - +from common import global_para as gp +import xmltodict +import json,time class GEN_Annotations: def __init__(self, filename): self.root = etree.Element("annotation") @@ -59,6 +60,7 @@ class GEN_Annotations: ymaxn.text = str(ymax) scoren = etree.SubElement(bndbox, "score") scoren.text = str(score) + def add_pic_attr_bird(self, label, xmin, ymin, xmax, ymax): object = etree.SubElement(self.root, "object") namen = etree.SubElement(object, "name") @@ -81,10 +83,61 @@ class GEN_Annotations: for j in i: density.attrib["att{}".format(num)] = j num+=1 + +class GEN_Annotations_scan(GEN_Annotations): + def __init__(self, record_time,serial_number): + super(GEN_Annotations,self).__init__() + self.root = etree.Element("annotation") + child1 = etree.SubElement(self.root, "record_time") + child1.text = record_time + child2 = etree.SubElement(self.root, "serial_number") + child2.text = serial_number + def add_pic_attr_scan(self, label, xmin, ymin, xmax, ymax): + object = etree.SubElement(self.root, "data") + namen = etree.SubElement(object, "species_name") + namen.text = str(label) + bndbox = etree.SubElement(object, "bndbox") + pos_x = etree.SubElement(bndbox, "site_x") + pos_x.text = str("1") + pos_y = etree.SubElement(bndbox, "site_y") + pos_y.text = str("1") + xminn = etree.SubElement(bndbox, "xmin") + xminn.text = str(xmin) + yminn = etree.SubElement(bndbox, "ymin") + yminn.text = str(ymin) + xmaxn = etree.SubElement(bndbox, "xmax") + xmaxn.text = str(xmax) + ymaxn = etree.SubElement(bndbox, "ymax") + ymaxn.text = str(ymax) + scoren = etree.SubElement(object, "habitat") + scoren.text = str("") +def make_xml_scan(record_time,serial_number, boxes,labels,savename): + anno = GEN_Annotations_scan(record_time,serial_number) + #anno.set_size(size_y, size_x, 3) + for i in range(len(boxes)): + xmin = int(boxes[i][0]) + ymin = int(boxes[i][1]) + xmax = int(boxes[i][2]) + ymax = int(boxes[i][3]) + # size_x1 = size_x[i] + # size_y1 = size_y[i] + anno.add_pic_attr_scan(str(labels[i]), xmin, ymin, xmax, ymax) + + anno.savefile("./temp.xml") + with open("./temp.xml", 'r', encoding='UTF-8')as json_file: + xml_data = json_file.read() + json_file.close() + jsonstr = xmltodict.parse(xml_data, encoding='UTF-8') + json_conversion = json.dumps(jsonstr["annotation"]) # 将python对象编码成Json字符串 + + with open(savename, 'w') as json_file: + json_file.write(json_conversion) # 写入文件 + json_file.close() + return jsonstr["annotation"] def make_xml(filename,size_x,size_y,boxes,labels,scores,savename): anno = GEN_Annotations(filename) @@ -95,7 +148,8 @@ def make_xml(filename,size_x,size_y,boxes,labels,scores,savename): xmax = int(boxes[i][2]) ymax = int(boxes[i][3]) score = int(scores[i]*1000) - anno.add_pic_attr("bird", xmin, ymin, xmax, ymax,score) + anno.add_pic_attr(gp.BHG_chineseName[int(labels[i])], xmin, ymin, xmax, ymax,score) + print("细粒度识别结果为:",gp.BHG_chineseName[int(labels[i])]) anno.savefile(savename) def make_xml_iccv(filename,size_x,size_y,boxes,savename): anno = GEN_Annotations(filename) diff --git a/detection.py b/detection.py index a9e268a..b4a6ebc 100755 --- a/detection.py +++ b/detection.py @@ -26,7 +26,7 @@ from ssd.utils.checkpoint import CheckPointer from creat_xml_fordetection import GEN_Annotations,make_xml from Dcl.models.LoadModel import MainModel from Dcl.DclConfig import LoadConfig, load_data_transformers -os.environ['CUDA_VISIBLE_DEVICES'] = '3' +#os.environ['CUDA_VISIBLE_DEVICES'] = '3' from PIL import ImageFile import time import cv2 diff --git a/detectionCorrectxml.py b/detectionCorrectxml.py new file mode 100755 index 0000000..42b9819 --- /dev/null +++ b/detectionCorrectxml.py @@ -0,0 +1,40 @@ +import os +import cv2 +import xml.dom.minidom +from tqdm import tqdm +from lxml import etree +from creat_xml import GEN_Annotations +xml_path = "/data/DataManagement/Project/CAS_ProjectBird/CDB_ProjectBird/Annotations" +image_path = xml_path.replace("/Annotations","/JPEGImages") +for xmls in tqdm(os.listdir(xml_path)): + anno = GEN_Annotations(xmls.replace(".xml",".jpg")) + dom = xml.dom.minidom.parse(os.path.join(xml_path,xmls)) + try: + size = dom.getElementsByTagName("size") + #print(size[0].getElementsByTagName('width')[0].childNodes[0].data) + width = size[0].getElementsByTagName('width')[0].childNodes[0].data + height = size[0].getElementsByTagName('height')[0].childNodes[0].data + depth = size[0].getElementsByTagName('depth')[0].childNodes[0].data + except: + + print(xmls) + image = cv2.imread(os.path.join(image_path,xmls.replace(".xml",".jpg"))) + width = image.shape[1] + height = image.shape[0] + depth = image.shape[2] + anno.set_size(int(width), int(height), int(depth)) + objects = dom.getElementsByTagName("object") + for object in objects: + bndbox = object.getElementsByTagName('bndbox')[0] + xmin = bndbox.getElementsByTagName('xmin')[0] + ymin = bndbox.getElementsByTagName('ymin')[0] + xmax = bndbox.getElementsByTagName('xmax')[0] + ymax = bndbox.getElementsByTagName('ymax')[0] + + xmin_data = int(xmin.childNodes[0].data) + ymin_data = int(ymin.childNodes[0].data) + xmax_data = int(xmax.childNodes[0].data) + ymax_data = int(ymax.childNodes[0].data) + label_name = object.getElementsByTagName('name')[0].childNodes[0].data + anno.add_pic_attr(label=label_name,xmin=xmin_data,xmax=xmax_data,ymin=ymin_data,ymax=ymax_data) + anno.savefile(os.path.join(xml_path,xmls).replace("/Annotations/","/Annotations_temp/")) \ No newline at end of file diff --git a/detection_negative_samples.py b/detection_negative_samples.py index c77647a..d105851 100755 --- a/detection_negative_samples.py +++ b/detection_negative_samples.py @@ -82,7 +82,7 @@ def negative_samples(path_unit,path_raw): filename = raw_path anno = GEN_Annotations(filename) anno.set_size(raw_img.size[0], raw_img.size[1], 3) - anno.add_pic_attr("person", x_left, y_left, x_right, y_right) + anno.add_pic_attr("bird", x_left, y_left, x_right, y_right) anno.savefile(os.path.join(path_raw,raw_path).replace("/NOObject/","/result/Ground_truth/").replace(".jpg",".xml")) diff --git a/detectiongResizeForTrain.py b/detectiongResizeForTrain.py new file mode 100755 index 0000000..48e1a5e --- /dev/null +++ b/detectiongResizeForTrain.py @@ -0,0 +1,61 @@ +""" +author: Hatcher +email:hcwang@semi.ac.cn +input: +Annotations_Original +JPEGImages_Original +w h +output: +Annotations +Annotations +use: 将目标检测数据集中所有的图像resize为新的目标大小,并对应修改标注文件中的信息 +""" +import os +import cv2 +import xml.dom.minidom +from tqdm import tqdm +from creat_xml import GEN_Annotations +anno_pathRoot = "/data4/Hatcher/airplane-03/small_object/test_data/800*800/Annotations_Original/" +image_pathRoot = anno_pathRoot.replace("/Annotations_Original/","/JPEGImages_Original/") +w = 800 +h = 800 + +def DetResizeForTrain(anno_pathRoot,image_pathRoot,w,h): + annoResultPath = anno_pathRoot.replace("/Annotations_Original/","/Annotations/") + annoJPEGPath = image_pathRoot.replace("/JPEGImages_Original/", "/JPEGImages/") + if not os.path.exists(annoResultPath): + os.makedirs(annoResultPath) + if not os.path.exists(annoJPEGPath): + os.makedirs(annoJPEGPath) + for annopath in tqdm(os.listdir(anno_pathRoot)): + anno = GEN_Annotations(annopath.replace(".xml", ".jpg")) + #print(os.path.join(anno_pathRoot, annopath)) + dom = xml.dom.minidom.parse(os.path.join(anno_pathRoot, annopath)) + size = dom.getElementsByTagName("size") + # print(size[0].getElementsByTagName('width')[0].childNodes[0].data) + width = size[0].getElementsByTagName('width')[0].childNodes[0].data + height = size[0].getElementsByTagName('height')[0].childNodes[0].data + depth = size[0].getElementsByTagName('depth')[0].childNodes[0].data + anno.set_size(int(w), int(h), int(depth)) + objects = dom.getElementsByTagName("object") + for object in objects: + bndbox = object.getElementsByTagName('bndbox')[0] + xmin = bndbox.getElementsByTagName('xmin')[0] + ymin = bndbox.getElementsByTagName('ymin')[0] + xmax = bndbox.getElementsByTagName('xmax')[0] + ymax = bndbox.getElementsByTagName('ymax')[0] + + xmin_data = int(int(xmin.childNodes[0].data)*(w/int(width))) + ymin_data = int(int(ymin.childNodes[0].data)*(h/int(height))) + xmax_data = int(int(xmax.childNodes[0].data)*(w/int(width))) + ymax_data = int(int(ymax.childNodes[0].data)*(h/int(height))) + label_name = object.getElementsByTagName('name')[0].childNodes[0].data + anno.add_pic_attr(label=label_name, xmin=xmin_data, xmax=xmax_data, ymin=ymin_data, ymax=ymax_data) + result_annoPath = os.path.join(annoResultPath, annopath.replace("-","_")) + anno.savefile(result_annoPath) + image = cv2.imread(os.path.join(image_pathRoot,annopath.replace(".xml",".jpg"))) + imageResize = cv2.resize(image,(w,h)) + cv2.imwrite(os.path.join(annoJPEGPath,annopath.replace(".xml",".png").replace("-","_")),imageResize) + +if __name__=="__main__": + DetResizeForTrain(anno_pathRoot,image_pathRoot,w,h) \ No newline at end of file diff --git a/dist/PlayVideo b/dist/PlayVideo deleted file mode 100755 index 0ad0272..0000000 Binary files a/dist/PlayVideo and /dev/null differ diff --git a/dist/imageroot.json b/dist/imageroot.json deleted file mode 100755 index 85dbde7..0000000 --- a/dist/imageroot.json +++ /dev/null @@ -1 +0,0 @@ -["/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0259.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0247.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0415.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0039.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0394.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0443.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0205.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0138.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0387.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0574.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0659.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0022.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0183.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0282.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0823.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0562.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0718.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0738.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0722.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0635.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0417.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0226.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0009.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0350.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0754.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0429.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0529.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0454.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0806.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0322.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0650.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0434.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0423.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0171.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0613.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0006.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0075.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0230.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0801.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0813.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0489.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0614.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0651.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0797.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0218.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0671.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0147.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0065.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0079.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0049.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0621.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0442.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0654.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0283.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0474.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0553.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0213.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0438.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0133.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0345.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0699.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0153.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0266.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0099.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0409.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0314.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0337.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0210.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0683.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0482.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0557.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0066.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0763.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0083.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0302.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0566.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0746.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0289.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0039.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0138.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0022.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0009.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0171.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0006.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0075.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0147.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0065.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0079.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0049.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0133.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0153.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0099.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0066.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0083.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0051.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0167.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0169.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0179.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0095.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0094.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0073.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0003.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0071.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0086.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0121.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0062.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0031.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0061.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0057.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0155.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0129.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0029.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0053.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0077.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0021.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0070.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0166.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0109.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0007.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0081.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0170.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0151.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0063.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0154.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0023.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0017.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0043.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0113.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0107.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0001.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0025.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0142.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0035.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0118.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0101.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0106.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0126.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0059.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0174.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0015.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0145.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0037.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0026.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0033.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0150.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0097.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0093.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0110.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0018.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0105.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0157.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0111.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0143.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0135.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0074.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0098.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0149.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0131.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0046.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0089.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0137.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0102.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0014.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0123.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0085.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0090.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0058.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0078.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0011.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0027.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0045.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0178.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0103.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0038.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0165.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0115.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0159.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0069.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0175.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0002.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0125.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0042.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0158.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0013.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0054.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0130.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0127.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0162.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0139.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0041.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0146.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0082.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0173.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0134.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0010.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0067.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0034.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0091.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0161.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0119.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0047.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0163.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0117.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0055.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0005.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0087.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0141.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0019.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0050.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0122.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0030.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0177.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0114.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0051.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0377.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0167.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0726.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0169.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0359.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0217.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0323.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0179.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0095.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0094.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0238.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0317.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0591.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0277.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0645.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0311.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0073.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0294.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0003.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0561.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0637.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0511.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0071.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0663.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0785.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0793.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0655.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0715.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0086.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0305.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0625.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0121.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0777.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0354.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0297.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0457.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0062.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0519.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0330.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0275.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0723.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0211.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0473.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0575.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0435.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0703.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0278.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0483.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0403.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0031.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0469.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0326.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0427.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0061.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0530.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0690.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0693.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0191.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0057.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0447.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0346.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0369.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0271.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0605.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0495.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0674.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0729.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0319.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0190.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0601.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0245.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0535.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0709.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0262.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0298.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0554.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0239.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0383.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0401.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0678.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0395.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0549.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0155.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0546.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0505.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0727.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0343.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0379.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0802.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0498.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0129.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0673.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0426.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0203.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0029.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0751.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0331.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0375.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0747.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0767.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0819.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0053.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0310.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0187.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0750.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0381.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0077.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0021.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0357.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0070.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0281.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0189.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0555.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0741.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0661.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0219.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0465.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0595.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0166.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0463.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0491.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0570.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0109.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0007.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0422.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0081.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0766.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0242.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0586.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0743.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0615.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0706.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0223.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0170.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0249.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0731.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0261.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0202.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0534.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0235.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0803.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0221.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0367.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0626.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0151.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0269.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0063.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0279.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0775.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0761.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0391.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0630.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0478.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0657.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0602.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0154.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0733.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0713.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0433.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0486.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0778.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0411.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0818.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0353.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0437.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0735.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0194.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0398.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0541.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0790.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0821.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0334.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0538.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0698.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0023.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0017.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0229.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0719.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0274.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0439.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0043.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0113.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0755.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0515.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0665.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0551.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0550.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0811.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0425.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0107.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0514.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0001.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0533.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0206.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0301.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0597.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0675.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0677.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0446.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0025.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0333.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0622.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0606.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0339.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0418.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0646.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0309.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0611.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0809.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0142.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0725.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0035.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0705.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0118.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0101.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0106.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0126.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0679.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0059.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0365.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0466.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0254.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0807.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0406.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0815.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0542.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0174.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0617.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0730.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0342.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0182.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0739.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0742.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0195.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0599.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0251.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0490.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0015.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0594.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0145.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0037.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0610.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0241.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0243.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0026.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0033.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0526.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0822.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0307.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0603.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0687.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0702.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0458.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0258.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0783.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0150.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0390.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0097.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0214.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0431.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0487.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0571.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0666.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0421.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0093.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0669.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0794.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0518.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0609.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0475.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0710.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0507.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0749.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0531.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0795.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0110.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0547.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0234.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0583.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0769.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0467.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0697.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0263.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0782.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0018.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0290.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0373.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0810.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0639.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0105.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0527.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0642.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0799.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0374.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0246.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0523.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0157.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0513.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0111.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0774.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0450.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0143.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0762.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0430.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0619.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0135.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0074.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0295.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0779.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0578.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0667.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0098.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0565.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0149.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0510.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0682.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0225.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0131.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0215.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0641.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0481.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0046.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0502.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0089.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0589.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0647.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0393.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0789.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0649.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0459.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0451.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0714.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0185.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0522.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0137.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0231.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0273.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0558.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0335.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0721.JPG", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001226.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001436.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003471.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002009.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001473.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001837.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003295.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000763.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000567.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000744.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002576.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003046.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001880.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002417.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000789.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001127.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001152.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002979.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003080.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002205.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000561.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000824.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002110.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001980.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000072.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000731.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001805.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001435.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003441.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001274.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003079.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001004.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002840.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002609.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001372.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003101.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002755.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002551.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000021.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003154.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002741.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002089.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000958.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002956.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000302.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003452.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003315.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003355.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000113.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001853.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000356.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001817.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002382.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002380.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002777.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000666.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003485.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002935.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000705.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002926.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000161.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000108.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002878.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000718.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003481.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000661.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000048.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001460.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000155.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001838.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001850.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001747.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001732.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002852.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003308.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001298.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002794.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002577.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001593.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002292.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003023.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001143.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000218.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003422.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003377.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001491.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000312.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000380.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002572.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000430.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003061.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003214.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003087.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003456.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002946.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002656.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002245.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000491.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001673.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002019.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000438.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001181.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001663.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000099.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002899.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002153.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002438.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001943.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002630.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001361.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002163.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003129.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001533.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000856.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001540.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001232.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000061.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002130.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001975.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000611.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002670.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001455.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001706.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001605.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003283.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000303.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001920.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000169.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000589.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001712.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002246.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001555.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000643.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002076.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000001.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001548.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001094.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000250.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002809.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002134.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003428.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000098.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003030.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002323.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001038.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002135.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000364.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000569.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001572.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002625.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000998.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000990.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002463.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002425.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000626.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001535.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000410.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000943.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002020.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000179.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002098.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001118.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000068.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001608.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003367.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003107.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003132.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001646.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001541.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001044.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001111.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000321.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002399.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002613.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001107.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000910.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000737.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002106.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001885.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003529.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002900.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001856.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001147.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002700.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000709.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001643.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000921.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003378.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003372.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000265.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002804.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002514.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001755.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000062.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000046.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002485.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003451.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001299.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002585.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003426.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000550.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001705.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000970.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003576.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002550.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002881.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001441.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003138.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002596.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003220.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003418.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002226.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000686.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003472.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000266.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002823.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001391.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003423.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001545.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001264.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002766.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002428.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003297.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000821.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000581.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002232.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000762.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002640.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000054.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003018.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002655.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002744.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001409.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002661.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001530.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000377.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001517.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000359.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002214.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000445.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001622.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000368.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002506.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003475.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001131.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002458.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003466.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000949.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003406.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001417.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000158.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001683.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003433.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003506.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002447.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001212.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002340.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000468.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000362.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000840.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002995.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003284.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000984.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001808.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001014.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001711.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000085.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001490.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001512.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000447.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001320.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000137.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000739.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000791.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001486.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000164.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002108.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000553.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001889.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000409.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001451.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000479.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000500.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001576.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000959.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001539.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000967.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000220.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001013.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002199.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003139.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001668.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001309.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001463.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002387.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002048.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000747.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003363.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001940.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000934.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000845.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002275.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000768.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003286.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001403.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000515.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000844.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001821.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000669.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000759.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000648.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001763.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003043.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001874.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003319.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000091.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000805.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003407.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000658.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001677.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001419.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001537.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003379.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002553.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002304.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003144.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000040.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001955.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000748.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000112.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000721.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002234.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000810.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002147.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001793.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003336.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002859.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003329.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002318.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002688.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000679.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000195.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000665.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003159.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001032.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003205.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001066.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000610.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000600.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001405.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001565.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001281.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000333.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002068.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000627.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001944.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001985.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002870.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002597.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003068.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001335.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001804.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002452.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002761.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000841.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000564.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001569.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000754.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002121.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001443.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001585.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002818.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001862.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000492.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000751.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003060.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002657.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001034.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001307.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001598.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000494.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002258.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000419.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000044.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000369.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000599.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002350.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002562.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000706.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000783.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002343.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000864.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002451.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000965.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000635.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002236.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000060.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001972.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001596.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001894.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002821.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001918.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001977.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001743.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003147.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003006.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000631.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000233.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002257.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002952.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002678.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000722.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001960.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000332.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002040.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003020.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003483.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001000.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001238.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000354.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003385.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002066.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001937.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001011.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000663.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000326.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003011.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001692.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002224.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001007.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003427.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001165.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000566.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002862.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002389.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002128.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003111.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000202.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001323.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002004.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002174.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002223.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000245.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002278.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000529.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000790.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003199.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003479.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002513.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001384.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003038.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001826.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000211.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002336.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000578.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001636.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000892.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002212.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000585.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003180.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002296.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000726.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003317.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003556.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001519.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003021.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001028.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002614.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000049.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002683.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000596.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000224.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003411.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002780.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002065.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003507.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002322.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000349.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002982.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001129.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001774.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003039.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002229.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000913.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001369.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002041.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000873.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000103.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001734.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000832.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000699.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002136.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001562.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003170.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002240.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002204.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002770.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001902.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000804.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001476.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003335.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002889.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002728.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003405.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001632.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003228.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000178.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003300.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000031.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000047.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000219.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002694.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001368.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001351.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002024.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002218.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000848.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001394.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003522.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000674.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001467.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000019.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000843.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002879.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003460.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001523.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002416.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000469.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001768.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001589.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003313.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002592.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003128.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002654.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002937.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002056.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002160.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001690.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001685.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000011.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002306.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001072.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000925.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003135.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000495.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002752.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001660.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002998.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000341.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000671.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000260.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001611.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003074.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000279.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003395.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001275.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001336.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002466.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000847.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002487.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003396.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001525.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003024.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001887.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000764.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000275.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001063.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001844.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000975.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000347.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000879.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002638.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001989.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001249.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001098.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000514.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002843.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000185.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003500.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002249.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001140.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002385.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002887.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002593.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000541.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000717.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002910.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002090.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000104.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001570.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001471.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003270.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000642.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001224.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002893.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002405.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000435.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000006.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000733.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002183.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000544.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002109.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002023.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003019.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001675.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000792.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000346.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000328.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000683.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001771.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000411.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000535.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000388.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001253.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000736.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003014.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001871.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001382.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003204.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000771.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001273.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000157.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001892.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002532.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003542.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000366.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002626.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000989.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002707.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000075.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001205.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002709.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000459.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003445.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000584.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002248.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003328.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002914.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001546.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000205.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001290.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001938.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002876.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002742.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002588.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001469.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003229.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002045.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000875.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002724.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003113.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003497.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001069.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000811.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003432.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000128.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002132.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000386.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000309.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002217.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000450.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002518.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002461.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002997.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000692.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002746.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003206.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001282.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002944.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001231.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000729.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000904.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000684.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001392.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000460.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003519.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003516.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002327.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001302.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003266.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002612.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002627.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000232.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002797.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000146.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002181.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003348.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000734.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000809.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001988.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003050.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000753.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000448.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000681.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001640.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001990.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000662.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002792.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002730.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003148.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001230.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003062.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001035.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000097.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000939.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003334.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002566.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000963.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000647.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000590.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001861.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002187.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001723.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000284.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000716.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000825.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003007.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002860.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002698.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000831.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001002.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003036.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000720.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001785.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002842.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000911.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003207.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003227.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002072.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003316.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000690.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001984.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003188.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000750.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000160.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002548.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000337.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002964.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000115.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002895.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001753.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001803.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002149.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002400.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001389.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002344.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001967.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000723.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002002.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000444.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001136.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000174.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001177.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002203.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001782.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000895.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001549.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001261.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002397.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001504.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001054.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002105.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002328.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002815.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001428.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003302.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002928.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000114.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001708.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001503.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003202.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002043.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000797.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002791.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003069.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000325.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000582.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000543.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002733.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000176.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001719.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003326.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001617.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000472.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000816.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001252.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001122.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001180.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003513.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002594.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003404.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000020.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000700.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003230.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001781.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003414.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002118.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002750.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000888.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001208.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002685.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003119.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000012.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003369.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001667.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001915.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000991.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002170.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002537.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001414.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000193.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002482.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002137.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002456.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000806.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000696.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001067.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001488.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001437.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003102.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002182.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002489.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000023.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002948.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003358.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000976.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002687.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002266.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003251.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001341.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002221.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001487.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000524.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002776.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002372.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001333.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002001.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002753.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001639.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002866.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002672.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002035.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000846.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002059.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001373.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001597.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002619.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000111.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001318.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001748.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002831.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002689.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000859.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003288.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000914.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001991.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000781.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000283.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001222.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001217.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002800.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000556.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001462.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001284.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003567.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001614.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002977.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000007.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000434.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003322.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001787.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000499.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001695.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000216.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003557.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000711.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001791.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003130.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002413.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000119.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002151.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000482.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002265.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001958.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001551.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001910.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002005.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001881.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000058.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003158.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002404.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002719.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001289.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002547.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000931.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003467.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001500.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001724.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000554.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000163.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001240.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002320.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002811.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001155.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000339.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002991.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001715.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002618.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000996.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001010.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002717.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002568.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003173.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001542.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001873.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002282.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000290.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000971.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002139.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000540.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000295.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002958.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002435.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000223.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001876.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003054.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000291.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002091.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001153.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002401.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003340.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001882.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000470.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002331.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001710.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002277.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002930.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000536.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000757.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000254.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000100.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002054.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002938.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003047.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000749.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002933.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000956.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000299.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001472.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001100.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003275.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001908.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003521.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000880.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002545.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002291.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002083.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000730.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000351.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001022.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003248.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000408.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003172.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000513.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002969.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001587.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002408.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003553.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000142.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003387.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003141.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003337.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002559.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001514.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002069.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003246.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002411.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002201.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000416.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0001251.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000557.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0000817.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002884.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0003400.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002680.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184/0002903.jpg", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 01 \ No newline at end of file diff --git a/dist/libQt5XcbQpa-70670cdb.so.5.15.0 b/dist/libQt5XcbQpa-70670cdb.so.5.15.0 deleted file mode 100755 index d45a26a..0000000 Binary files a/dist/libQt5XcbQpa-70670cdb.so.5.15.0 and /dev/null differ diff --git a/dist/libcaffe2_nvrtc.so b/dist/libcaffe2_nvrtc.so deleted file mode 100755 index dda5bc9..0000000 Binary files a/dist/libcaffe2_nvrtc.so and /dev/null differ diff --git a/dist/platforms/libqxcb.so b/dist/platforms/libqxcb.so deleted file mode 100755 index 0decf3d..0000000 Binary files a/dist/platforms/libqxcb.so and /dev/null differ diff --git a/dist/qt/fonts/DejaVuSans-Bold.ttf b/dist/qt/fonts/DejaVuSans-Bold.ttf deleted file mode 100755 index 9d70947..0000000 Binary files a/dist/qt/fonts/DejaVuSans-Bold.ttf and /dev/null differ diff --git a/dist/qt/fonts/DejaVuSans-BoldOblique.ttf b/dist/qt/fonts/DejaVuSans-BoldOblique.ttf deleted file mode 100755 index 1199f09..0000000 Binary files a/dist/qt/fonts/DejaVuSans-BoldOblique.ttf and /dev/null differ diff --git a/dist/qt/fonts/DejaVuSans-ExtraLight.ttf b/dist/qt/fonts/DejaVuSans-ExtraLight.ttf deleted file mode 100755 index 48ed755..0000000 Binary files a/dist/qt/fonts/DejaVuSans-ExtraLight.ttf and /dev/null differ diff --git a/dist/qt/fonts/DejaVuSans-Oblique.ttf b/dist/qt/fonts/DejaVuSans-Oblique.ttf deleted file mode 100755 index 90b9327..0000000 Binary files a/dist/qt/fonts/DejaVuSans-Oblique.ttf and /dev/null differ diff --git a/dist/qt/fonts/DejaVuSans.ttf b/dist/qt/fonts/DejaVuSans.ttf deleted file mode 100755 index 2b9ad32..0000000 Binary files a/dist/qt/fonts/DejaVuSans.ttf and /dev/null differ diff --git a/dist/qt/fonts/DejaVuSansCondensed-Bold.ttf b/dist/qt/fonts/DejaVuSansCondensed-Bold.ttf deleted file mode 100755 index 437f2f5..0000000 Binary files a/dist/qt/fonts/DejaVuSansCondensed-Bold.ttf and /dev/null differ diff --git a/dist/qt/fonts/DejaVuSansCondensed-BoldOblique.ttf b/dist/qt/fonts/DejaVuSansCondensed-BoldOblique.ttf deleted file mode 100755 index 4f4ca07..0000000 Binary files a/dist/qt/fonts/DejaVuSansCondensed-BoldOblique.ttf and /dev/null differ diff --git a/dist/qt/fonts/DejaVuSansCondensed-Oblique.ttf b/dist/qt/fonts/DejaVuSansCondensed-Oblique.ttf deleted file mode 100755 index c986d52..0000000 Binary files a/dist/qt/fonts/DejaVuSansCondensed-Oblique.ttf and /dev/null differ diff --git a/dist/qt/fonts/DejaVuSansCondensed.ttf b/dist/qt/fonts/DejaVuSansCondensed.ttf deleted file mode 100755 index 3f518ee..0000000 Binary files a/dist/qt/fonts/DejaVuSansCondensed.ttf and /dev/null differ diff --git a/dist/qt/plugins/platforms/libqxcb.so b/dist/qt/plugins/platforms/libqxcb.so deleted file mode 100755 index 0decf3d..0000000 Binary files a/dist/qt/plugins/platforms/libqxcb.so and /dev/null differ diff --git a/dist/vedioroot.json b/dist/vedioroot.json deleted file mode 100755 index e13c271..0000000 --- a/dist/vedioroot.json +++ /dev/null @@ -1 +0,0 @@ -["/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0184.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0084.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0600.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0180.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0052.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0524.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0588.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0536.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0812.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0136.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0448.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0168.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0416.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0364.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0644.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0668.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0084.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0180.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0052.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0136.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0168.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0040.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0172.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0092.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0116.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0096.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0004.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0104.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0144.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0140.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0132.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0088.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0164.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0068.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0156.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0128.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0176.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0152.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0112.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0020.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0120.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0028.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0064.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0108.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0032.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0056.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0044.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0008.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0076.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0080.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0124.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0160.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0016.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0072.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0100.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/2\u53f7\u76f8\u673a20191114-1122/Ere 0148.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0252.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0240.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0748.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0380.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0776.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0792.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0040.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0332.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0708.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0468.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0548.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0172.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0092.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0796.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0744.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0372.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0496.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0540.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0516.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0368.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0632.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0460.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0712.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0256.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0248.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0232.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0324.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0488.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0408.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0692.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0276.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0116.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0432.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0732.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0280.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0224.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0096.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0004.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0356.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0752.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0104.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0144.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0428.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0728.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0208.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0440.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0140.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0704.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0132.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0576.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0680.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0236.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0620.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0624.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0804.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0088.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0764.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0596.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0320.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0164.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0412.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0420.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0068.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0688.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0476.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0604.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0156.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0756.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0296.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0388.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0328.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0444.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0128.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0292.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0176.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0520.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0584.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0152.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0300.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0532.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0676.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0664.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0800.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0112.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0500.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0772.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0424.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0220.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0192.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0020.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0556.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0260.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0508.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0760.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0788.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0452.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0608.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0640.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0316.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0472.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0312.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0120.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0028.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0064.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0740.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0108.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0560.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0384.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0568.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0212.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0484.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0736.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0032.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0376.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0348.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0824.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0204.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0724.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0716.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0056.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0216.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0564.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0816.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0628.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0044.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0008.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0768.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0544.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0272.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0464.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0188.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0396.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0652.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0400.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0612.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0076.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0436.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0780.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0268.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0784.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0636.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0808.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0244.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0080.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0124.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0616.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0480.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0648.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0160.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0308.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0512.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0392.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0504.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0672.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0572.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0016.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0552.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0336.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0656.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0492.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0592.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0340.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0360.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0196.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0344.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0072.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0684.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0100.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0696.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0264.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0228.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0304.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0404.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0660.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0820.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0200.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0288.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0720.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0456.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0580.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0352.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0284.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0528.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0148.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx02-20191108-1113/Ere 0700.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0057.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0084.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0033.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0171.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0063.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0180.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0174.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0147.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0099.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0168.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0141.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0162.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0039.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0066.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0009.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0090.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0102.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0018.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0135.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0075.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0183.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0096.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0030.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0081.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0144.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0051.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0045.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0132.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0153.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0138.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0156.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0093.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0042.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0159.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0021.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0123.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0150.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0069.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0120.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0105.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0111.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0108.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0054.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0003.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0015.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0114.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0126.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0129.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0006.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0186.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0027.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0072.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0117.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0165.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0078.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0177.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_e1b_20191201-1213/Ere 0087.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0035.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0123.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0155.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0031.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0135.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0147.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0239.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0231.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0159.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0235.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0063.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0083.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0283.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0103.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0027.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0191.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0267.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0059.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0287.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0008.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0211.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0255.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0179.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0275.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0279.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0111.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0271.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0127.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0107.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0183.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0091.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0223.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0055.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0207.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0219.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0291.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0043.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0199.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0203.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0004.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0079.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0115.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0215.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0187.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0247.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0047.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0051.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0163.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0131.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0023.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0095.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0019.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0012.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0067.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0307.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0314.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0056.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0298.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0395.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0274.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0359.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0239.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0231.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0168.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0235.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0383.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0180.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0020.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0064.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0318.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0302.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0060.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0363.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0008.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0068.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0044.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0032.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0048.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0148.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0140.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0278.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0255.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0136.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0306.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0152.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0322.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0192.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0282.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0220.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0286.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0212.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0351.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0270.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0367.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0310.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0188.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0216.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0355.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0072.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0016.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0052.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0132.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0084.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0176.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0080.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0208.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0076.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0196.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0204.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0004.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0399.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0247.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0036.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0294.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0379.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0387.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0012.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0184.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0024.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0251.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0172.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0160.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0164.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0088.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0391.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0290.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0259.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0144.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0040.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0200.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0266.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0371.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0347.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0243.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0028.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0227.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0375.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0156.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/4\u53f7\u76f8\u673a20191114-1122/IMAG0092.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0167.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0251.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0087.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0263.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0259.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0075.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0039.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0299.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0099.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0151.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0171.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0195.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0071.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0243.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0227.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0175.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0119.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0303.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0143.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0139.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0311.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-XX4\u53f7-20191108-1113/IMAG0295.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0065.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0035.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0050.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0009.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0038.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0003.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0017.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0023.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0029.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0071.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0032.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0077.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0062.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0006.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0044.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0014.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0041.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0059.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0080.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0020.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0074.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0026.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0047.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0068.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0053.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx13_e3h_20191201-1213/ECSP0056.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0123.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0155.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0135.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0147.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0231.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0159.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0235.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0063.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0020.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0083.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0103.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0191.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0059.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0008.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0044.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0032.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0048.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0211.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0179.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0111.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0127.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0107.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0183.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0091.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0223.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0055.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0207.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0219.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0016.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0199.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0203.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0004.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0079.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0115.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0215.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0187.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0036.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0163.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0131.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0095.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0012.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0024.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0067.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0167.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0087.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0075.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0040.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0099.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0151.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0171.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0195.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0071.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0028.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0227.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0175.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0119.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0143.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191215-1230/IMAG0139.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0067.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0063.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0031.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0023.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0043.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0083.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0039.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0059.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0055.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0075.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0004.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0051.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0079.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0035.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0008.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0047.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0027.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0019.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx06_e1b_20191201-1213/Ere 0071.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0184.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0084.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0600.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0180.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0052.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0524.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0588.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0536.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0136.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0448.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0168.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0416.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0364.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0644.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0668.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0252.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0240.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0380.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0040.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0332.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0708.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0468.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0548.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0172.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0092.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0372.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0496.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0540.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0516.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0368.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0632.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0460.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0712.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0256.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0248.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0232.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0324.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0488.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0408.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0692.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0276.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0116.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0432.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0732.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0280.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0224.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0096.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0004.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0356.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0104.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0144.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0428.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0728.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0208.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0440.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0140.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0704.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0132.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0576.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0680.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0236.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0620.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0624.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0088.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0596.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0320.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0164.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0412.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0420.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0068.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0688.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0476.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0604.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0156.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0296.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0388.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0328.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0444.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0128.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0292.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0176.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0520.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0584.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0152.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0300.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0532.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0676.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0664.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0112.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0500.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0424.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0220.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0192.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0020.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0556.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0260.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0508.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0452.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0608.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0640.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0316.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0472.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0312.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0120.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0028.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0064.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0740.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0108.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0560.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0384.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0568.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0212.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0484.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0736.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0032.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0376.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0348.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0204.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0724.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0716.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0056.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0216.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0564.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0628.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0044.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0008.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0544.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0272.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0464.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0188.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0396.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0652.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0400.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0612.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0076.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0436.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0268.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0636.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0244.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0080.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0124.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0616.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0480.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0648.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0160.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0308.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0184.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0084.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0600.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0180.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0052.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0524.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0588.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0536.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0136.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0448.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0168.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0416.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0364.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0644.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0668.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0252.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0240.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0380.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0040.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0332.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0468.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0548.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0172.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0092.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0372.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0496.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0540.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0516.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0368.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0632.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0460.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0256.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0248.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0232.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0324.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0488.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0408.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0276.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0116.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0432.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0280.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0224.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0096.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0004.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0356.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0104.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0144.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0428.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0208.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0440.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0140.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0132.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0576.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0236.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0620.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0624.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0088.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0596.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0320.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0164.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0412.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0420.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0068.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0476.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0604.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0156.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0296.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0388.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0328.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0444.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0128.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0292.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0176.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0520.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0584.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0152.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0300.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0532.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0664.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0112.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0500.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0424.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0220.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0192.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0020.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0556.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0260.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0508.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0452.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0608.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0640.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0316.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0472.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0312.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0120.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0028.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0064.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0108.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0560.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0384.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0568.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0212.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0484.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0032.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0376.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0348.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0204.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0056.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0216.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0564.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0628.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0044.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0008.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0544.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0272.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0464.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0188.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0396.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0652.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0400.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0612.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0076.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0436.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0268.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0636.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0244.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0080.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0124.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0616.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0480.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0648.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0160.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0308.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0512.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0392.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0504.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0572.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0016.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0552.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0336.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0656.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0492.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0592.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0340.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0360.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0196.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0344.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0072.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0100.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0264.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0228.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0304.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0404.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0660.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0200.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0288.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0456.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0580.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0352.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0284.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0528.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/20191114-1122/Ere 0148.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0512.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0392.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0504.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0672.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0572.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0016.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0552.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0336.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0656.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0492.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0592.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0340.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0360.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0196.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0344.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0072.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0684.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0100.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0696.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0264.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0228.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0304.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0404.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0660.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0200.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0288.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0720.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0456.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0580.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0352.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0284.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0528.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0148.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx01-20191108-1113/Ere 0700.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0280.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0056.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0268.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0395.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0169.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0120.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0153.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0364.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0180.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0020.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0339.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0064.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0382.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0060.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0133.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0008.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0288.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0068.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0032.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0173.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0048.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0116.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0141.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0192.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0161.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0100.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0272.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0188.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0072.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0296.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0016.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0052.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0145.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0084.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0335.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0080.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0076.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0196.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0204.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0004.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0399.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0149.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0292.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0284.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0264.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0012.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0184.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0024.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0096.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0088.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0256.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0200.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0260.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0371.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0112.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0028.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0108.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0157.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0137.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0331.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0375.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0104.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0165.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0276.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO_xx03\u53f7_20191201-1213/IMAG0092.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0280.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0056.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0268.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0244.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0224.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0120.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0168.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0180.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0020.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0064.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0060.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0008.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0288.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0068.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0044.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0032.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0048.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0148.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0116.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0140.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0136.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0152.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0192.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0220.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0212.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0100.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0272.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0188.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0216.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0072.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0016.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0052.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0132.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0084.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0176.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0080.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0208.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0076.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0196.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0204.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0004.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0228.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0292.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0036.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0284.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0232.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0264.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0012.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0184.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0024.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0248.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0096.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0172.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0160.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0164.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0088.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0256.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0144.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0040.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0200.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0124.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0260.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0240.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0112.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0028.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0108.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0252.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0104.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0156.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0276.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0236.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0092.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx04_1215_1230/IMAG0128.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0056.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0123.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0495.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0419.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0390.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0409.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0405.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0168.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0180.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0020.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0427.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0339.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0491.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0064.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0191.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0060.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0507.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0008.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0499.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0068.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0327.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0044.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0032.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0048.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0148.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0140.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0211.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0431.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0511.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0136.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0479.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0152.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0447.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0207.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0100.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0351.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0519.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0471.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0423.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0291.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0475.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0355.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0072.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0016.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0052.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0315.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0084.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0176.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0335.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0080.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0199.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0076.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0439.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0203.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0004.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0187.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0443.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0455.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0036.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0284.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0463.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0487.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0012.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0024.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0307.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0451.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0096.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0435.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0172.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0160.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0164.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0088.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0401.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0144.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0040.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0523.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0299.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0503.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0386.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0467.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0515.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0343.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0319.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0347.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0195.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0112.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0028.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0397.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0527.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0108.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0459.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0331.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0104.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0119.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0483.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0156.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0323.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0303.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0092.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0311.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05\u53f7_20191201_1213/IMAG0295.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx08_e1b_20191201_1213/Ere 0033.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx08_e1b_20191201_1213/Ere 0009.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx08_e1b_20191201_1213/Ere 0018.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx08_e1b_20191201_1213/Ere 0030.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx08_e1b_20191201_1213/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx08_e1b_20191201_1213/Ere 0021.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx08_e1b_20191201_1213/Ere 0003.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx08_e1b_20191201_1213/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx08_e1b_20191201_1213/Ere 0015.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx08_e1b_20191201_1213/Ere 0006.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere-xx08_e1b_20191201_1213/Ere 0027.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0052.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0028.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0034.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0010.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0067.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0088.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0007.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0049.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0091.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0016.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0082.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0076.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0061.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0085.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0040.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0073.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0046.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0043.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0022.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0037.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0079.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0070.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0019.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0031.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0013.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0058.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0055.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0064.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx12_20191201_1230/ECSP0025.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0033.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0009.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0018.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0030.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0021.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0003.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0015.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0006.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx07_1215_1230/Ere 0027.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0085.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0067.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0031.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0052.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0023.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0073.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0043.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0040.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0011.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0026.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0055.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0017.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0088.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0079.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0005.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0020.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0091.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0064.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0008.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0049.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0046.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0076.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0037.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0034.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0082.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0070.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0061.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0014.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_10_20191201-1230/Ere 0058.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0066.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0021.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0009.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0003.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0024.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0036.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0039.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0027.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0060.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0033.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0063.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0006.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0057.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0042.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0054.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0048.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0045.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0030.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0012.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0015.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0018.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e3h_xx13_20191215_1230/ECSP0051.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0057.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0084.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0033.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0171.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0063.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0180.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0174.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0147.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0099.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0168.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0141.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0162.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0198.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0207.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0189.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0039.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0066.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0009.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0090.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0102.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0018.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0213.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0135.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0075.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0195.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0183.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0096.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0030.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0081.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0144.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0051.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0045.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0210.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0132.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0153.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0138.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0156.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0093.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0192.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0042.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0159.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0021.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0123.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0150.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0069.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0120.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0105.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0111.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0108.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0054.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0003.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0015.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0204.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0114.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0216.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0126.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0129.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0006.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0201.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0186.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0027.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0072.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0117.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0165.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0078.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0177.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx07_20200101-0316/Ere 0087.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0056.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0224.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0120.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0168.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0180.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0020.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0064.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0060.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0008.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0068.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0044.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0032.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0048.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0148.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0116.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0140.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0136.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0152.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0192.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0220.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0212.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0100.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0188.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0216.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0072.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0016.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0052.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0132.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0084.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0176.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0080.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0208.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0076.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0196.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0204.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0004.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0228.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0036.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0012.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0184.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0024.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0096.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0172.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0160.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0164.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0088.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0144.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0040.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0200.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0124.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0112.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0028.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0108.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0056.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0298.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0222.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0320.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0246.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0274.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0360.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0254.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0166.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0120.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0316.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0364.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0158.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0020.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0174.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0250.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0356.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0064.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0302.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0060.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0008.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0344.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0068.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0044.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0032.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0048.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0206.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0148.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0116.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0140.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0278.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0186.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0178.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0136.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0306.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0202.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0282.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0286.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0182.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0162.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0100.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0270.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0072.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0332.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0016.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0052.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0132.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0084.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0080.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0076.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0198.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0004.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0036.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0242.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0294.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0194.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0328.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0012.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0226.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0024.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0096.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0214.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0088.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0290.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0336.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0144.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0040.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0258.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0266.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0124.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0352.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0340.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0348.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0112.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0218.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0028.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0190.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0210.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0108.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0170.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0104.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0092.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0128.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0324.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/3\u53f7\u76f8\u673a20191114-1122/IMAG0262.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0104.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0156.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0092.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx3\u53f7-20191108-1113/IMAG0128.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0184.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0084.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0180.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0052.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0136.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0168.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0040.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0172.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0092.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0116.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0096.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0004.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0104.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0144.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0208.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0140.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0132.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0088.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0164.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0068.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0156.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0128.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0176.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0152.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0112.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0192.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0020.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0120.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0028.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0064.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0108.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0212.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0032.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0204.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0056.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0044.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0008.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0188.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0076.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0080.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0124.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0160.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0016.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0196.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0072.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0100.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0200.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx02_20191201_1213/Ere 0148.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0084.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0052.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0136.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0040.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0092.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0116.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0096.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0004.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0104.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0144.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0140.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0132.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0088.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0068.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0156.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0128.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0152.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0112.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0020.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0120.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0028.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0064.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0108.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0032.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0056.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0044.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0008.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0076.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0080.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0124.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0016.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0072.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0100.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx02_1215_1230/Ere 0148.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0035.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0628.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0298.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0015.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0320.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0246.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0274.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0552.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0031.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0007.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0419.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0254.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0169.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0197.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0568.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0620.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0316.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0407.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0312.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0193.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0652.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0473.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0450.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0688.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0063.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0083.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0205.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0592.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0250.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0427.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0238.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0103.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0027.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0185.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0668.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0506.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0217.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0486.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0624.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0572.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0604.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0059.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0548.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0344.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0173.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0564.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0278.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0431.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0640.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0201.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0596.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0111.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0660.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0612.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0107.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0672.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0282.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0161.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0286.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0608.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0091.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0055.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0680.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0411.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0270.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0415.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0189.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0560.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0423.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0616.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0544.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0332.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0308.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0043.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0209.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0648.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0439.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0684.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0221.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0079.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0676.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0584.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0213.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0443.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0469.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0242.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0580.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0047.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0051.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0490.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0294.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0632.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0023.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0095.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0328.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0019.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0067.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0664.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0556.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0498.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0600.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0435.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0087.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0011.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0532.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0225.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0290.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0336.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0075.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0258.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0266.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0039.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0576.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0502.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0099.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0494.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0181.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0352.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0536.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0340.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0636.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0071.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0348.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0588.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0157.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0644.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0880.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0165.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0656.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0540.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0528.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0324.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0262.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORILLO_xx04_20191201-1213/IMAG0177.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0057.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0084.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0033.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0063.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0099.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0039.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0066.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0009.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0090.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0102.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0018.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0075.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0096.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0030.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0081.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0051.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0045.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0093.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0042.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0021.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0123.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0069.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0120.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0105.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0111.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0108.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0054.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0003.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0015.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0114.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0126.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0006.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0027.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0072.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0117.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0078.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/Ere_xx08_20200101-0316/Ere 0087.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0057.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0033.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0063.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0039.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0066.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0009.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0018.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0030.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0051.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0045.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0042.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0021.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0069.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0054.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0003.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0015.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0006.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx09_1201_1230/Ere 0027.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0123.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0155.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0135.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0147.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0239.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0231.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0159.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0235.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0063.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0020.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0083.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0103.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0191.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0267.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0059.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0008.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0032.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0211.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0255.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0179.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0275.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0111.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0271.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0127.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0107.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0183.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0091.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0223.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0055.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0207.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0219.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0016.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0043.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0199.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0203.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0004.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0079.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0115.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0215.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0187.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0247.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0036.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0047.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0051.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0163.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0131.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0095.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0012.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0024.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0067.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0167.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0251.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0087.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0263.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0259.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0075.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0081.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0414.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0361.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0065.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0341.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0442.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0462.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0109.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0305.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0450.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0418.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0269.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0385.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0077.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0470.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0191.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0357.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0045.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0293.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0325.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0105.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0085.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0393.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0211.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0434.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0053.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0289.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0093.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0454.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0369.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0373.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0309.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0365.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0329.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0381.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0349.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0073.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0207.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0422.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0219.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0069.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0029.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0199.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0203.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0317.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0297.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0215.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0037.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0313.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0033.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0353.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0377.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0438.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0321.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0101.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0458.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0049.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0466.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0025.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0057.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0401.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0345.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0259.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0430.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0061.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0446.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0089.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0195.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0389.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0301.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0097.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0397.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0273.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0337.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0333.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0426.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/5\u53f7\u76f8\u673a20191114-1122/IMAG0041.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0099.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0151.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0171.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0195.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0071.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0243.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0028.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0227.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0175.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0119.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0143.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLO-xx05\u53f7-20191108-1113/IMAG0139.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0057.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0033.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0039.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0009.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0018.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0030.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0051.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0045.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0042.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0021.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0054.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0003.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0015.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0006.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx08_1215_1230/Ere 0027.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0184.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0084.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0180.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0052.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0136.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0168.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0364.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0252.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0240.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0380.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0040.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0332.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0172.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0092.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0372.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0368.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0256.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0036.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0248.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0232.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0324.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0276.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0060.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0116.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0280.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0224.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0096.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0004.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0356.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0104.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0144.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0208.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0140.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0012.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0132.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0236.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0088.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0320.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0164.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0068.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0156.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0296.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0388.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0328.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0128.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0292.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0176.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0152.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0300.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0112.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0220.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0192.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0020.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0260.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0316.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0312.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0120.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0028.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0064.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0108.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0384.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0212.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0032.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0024.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0376.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0348.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0204.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0056.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0216.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0044.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0008.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0272.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0188.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0396.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0400.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0048.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0076.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0268.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0244.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0080.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0124.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0160.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0308.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0392.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0016.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0336.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0340.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0360.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0196.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0344.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0072.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0100.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0264.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0228.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0304.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0200.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0288.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0352.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0284.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/e1b_xx01_1201_1230/Ere 0148.MP4", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0056.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0244.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0224.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0120.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0168.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0180.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0020.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0064.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0060.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0008.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0068.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0044.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0032.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0048.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0148.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0116.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0140.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0136.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0152.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0192.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0220.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0212.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0100.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0188.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0216.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0072.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0016.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0052.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0132.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0084.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0176.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0080.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0208.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0076.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0196.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0204.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0004.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0228.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0036.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0232.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0264.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0012.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0184.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0024.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0248.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0096.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0172.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0160.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0164.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0088.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0256.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0144.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0040.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0200.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0124.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0260.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0240.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0112.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0028.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0108.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0252.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0104.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0156.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0236.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0092.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/red-camera-2019-2020/ORLLI_xx05_20191215_1230/IMAG0128.MOV", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5c0f\u767d.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5c0f\u897f\u6e56\u897f_1611302565_559752B8/\u5c0f\u897f\u6e56\u897f_1F16C2F8_1611302565_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/20161205_20161205163044_20161205163110_163044.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/DJI_0002.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u897f\u6e56\u5480_19652948_1572160673_9.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5f55\u50cf\u76d1\u63a7-\u767d\u7435\u9e6d.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_1F7210C0_1611302361_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1611300568_E1BAC1DB/\u5927\u897f\u6e56_195BC980_1611300568_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20181017171702254E6678_1539767822_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u96ea\u5730\u9e45.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/20161205_20161205162742_20161205162950_162742.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_20161231120051200C9508_1483156851_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/4\u53f7\u4e91\u53f0_20161217130610200F5AE0_1481951170_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_20161231162339262D19F0_1483172619_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_201701171712201F60F4E8_1484644340_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_201701171717141F60F4E8_1484644634_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_2017011717071112BF4920_1484644031_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/3\u53f7\u4e91\u53f0_20161231120215200C7800_1483156935_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_20161231162606262D19F0_1483172766_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_201612261650172A97ABB0_1482742217_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_20161231160150262D19F0_1483171310_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_20161231162010262D19F0_1483172410_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_201701171707111F60F4E8_1484644031_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_2017011717122012BF4920_1484644340_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_201701171716351F60F4E8_1484644595_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/5\u53f7\u4e91\u53f0_20161231120215200C9508_1483156935_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/4\u53f7\u4e91\u53f0_20161217130414200F5AE0_1481951054_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/\u65b0\u5efa\u6587\u4ef6\u5939/20161207_20161207131448_20161207131545_131448.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/\u65b0\u5efa\u6587\u4ef6\u5939/20161208_20161208130714_20161208130844_130714.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/\u65b0\u5efa\u6587\u4ef6\u5939/20161207_20161207134252_20161207134334_134252.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/\u65b0\u5efa\u6587\u4ef6\u5939/20161207_20161207131815_20161207131902_131815.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/birdmp4/\u65b0\u5efa\u6587\u4ef6\u5939/20161207_20161207130500_20161207130534_130502.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180129142300122E67D8_1517206980_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1611302403_B5A3B946/\u5927\u897f\u6e56_1EE5CB28_1611302403_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180129144321122E67D8_1517208201_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180129141906122E67D8_1517206746_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_195BC980_1611300568_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/20161205_20161205155256_20161205155530_155256.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u96ea\u5730\u8c46\u96c1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u897f\u6e56\u5480_1911B5E0_1610621990_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5c0f\u5929\u9e452.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_1611302361_CCE20CBA/\u4e1c\u95f8_1F7210C0_1611302361_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u897f\u6e56\u5480_18C47CD8_1610621670_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_201802171545012051B0A0_1518853501_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_2018120216460619914C70_1543740366_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5f55\u50cf\u76d1\u63a7-\u6c5f\u8c5a 1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180129144118122E67D8_1517208078_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u9ec4\u82b1\u5c16_201704140926272A321C28_1492133187_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/20161205_20161205162411_20161205162416_162411.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u897f\u6e56\u5480_193126B8_1577329190_2.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180129150545122E67D8_1517209545_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5c0f\u897f\u6e56\u897f_1F16C2F8_1611302565_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5c0f\u767d1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u53cd\u5634\u9e6c.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u6fe0\u6cb3_201704140926272A323860_1492133187_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180129150638122E67D8_1517209598_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_2018120215560219914C70_1543737362_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1611286705_0AA1491B/\u5927\u897f\u6e56_19A1C118_1611286706_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1611286705_0AA1491B/\u5927\u897f\u6e56_19A1C118_1611286706_2.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180129142746122E67D8_1517207266_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/20161205_20161205161240_20161205161448_161240.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u897f\u6e56\u5480_1611302500_D654C574/\u897f\u6e56\u5480_1F76B800_1611302500_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u9047\u9e7f\u96c6.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u897f\u6e56\u5480_1F76B800_1611302500_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180204151919122E67D8_1517728759_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u767d\u7435\u9e6d2.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_201811091011211BE9CB48_1541729481_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180208095128122E67D8_1518054688_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u96ea\u5730\u9e453.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180129150119122E67D8_1517209279_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180204153843122E67D8_1517729923_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180208110225122828E8_1518058945_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u4e1c\u95f8_20180129132506122E67D8_1517203506_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u897f\u6e56\u5480_193126B8_1577329190_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1611285388_AD1CF1DF/\u5927\u897f\u6e56_19A38A10_1611285388_4.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1611285388_AD1CF1DF/\u5927\u897f\u6e56_19A38A10_1611285388_3.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1611285388_AD1CF1DF/\u5927\u897f\u6e56_19A38A10_1611285388_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1611285388_AD1CF1DF/\u5927\u897f\u6e56_19A38A10_1611285388_7.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1611285388_AD1CF1DF/\u5927\u897f\u6e56_19A38A10_1611285388_2.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1611285388_AD1CF1DF/\u5927\u897f\u6e56_19A38A10_1611285388_6.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1611285388_AD1CF1DF/\u5927\u897f\u6e56_19A38A10_1611285388_5.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5c0f\u5929\u9e45.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5927\u897f\u6e56_1EE5CB28_1611302403_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u6fe0\u6cb3_20180208110225122F27D8_1518058945_1.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5f55\u50cf\u76d1\u63a7-\u6c5f\u8c5a .mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u96ea\u5730\u9e452.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u767d\u7435\u9e6d.mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u5c0f\u767d (2).mp4", "/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/\u7070\u9e64.mp4"] \ No newline at end of file diff --git a/featuremap.py b/featuremap.py new file mode 100755 index 0000000..b171aa5 --- /dev/null +++ b/featuremap.py @@ -0,0 +1,67 @@ +# 返回输出结果 +import cv2 +import torchvision +import torch +from matplotlib import pyplot as plt +import numpy as np +import torchvision.transforms as transforms +import torch +import torchvision +import torch.nn as nn +import torchvision.transforms as transforms +import torchvision.models as models +from matplotlib import pyplot as plt +import random +#定义函数,随机从0-end的一个序列中抽取size个不同的数 +def random_num(size,end): + range_ls=[i for i in range(end)] + num_ls=[] + for i in range(size): + num=random.choice(range_ls) + range_ls.remove(num) + num_ls.append(num) + return num_ls + + + +path = "/data1/Hatcher/DATA/test13/train_data/images/HatIMG_668.jpg" +transformss = transforms.Compose( + [transforms.ToTensor(), + transforms.Resize((224, 224)), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) + +#注意如果有中文路径需要先解码,最好不要用中文 +img = cv2.imread(path) +img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + +#转换维度 +img = transformss(img).unsqueeze(0) + +model = torchvision.models.resnet50(pretrained=True) +#new_model = torchvision.models._utils.IntermediateLayerGetter(model, {'layer1': '1', 'layer2': '2',"layer3":"3"}) +out = model(img) + +tensor_ls=[(k,v) for k,v in out.items()] + +#这里选取layer2的输出画特征图 +v=tensor_ls[1][1] + +""" +如果要选layer3的输出特征图只需把第一个索引值改为2,即: +v=tensor_ls[2][1] +只需把第一个索引更换为需要输出的特征层对应的位置索引即可 +""" +#取消Tensor的梯度并转成三维tensor,否则无法绘图 +v=v.data.squeeze(0) + +print(v.shape) # torch.Size([512, 28, 28]) + + +#随机选取25个通道的特征图 +channel_num = random_num(25,v.shape[0]) +plt.figure(figsize=(10, 10)) +for index, channel in enumerate(channel_num): + ax = plt.subplot(5, 5, index+1,) + plt.imshow(v[channel, :, :]) +plt.savefig("feature.jpg",dpi=300) + diff --git a/fine/__pycache__/fineConfig.cpython-36.pyc b/fine/__pycache__/fineConfig.cpython-36.pyc old mode 100644 new mode 100755 index d27ae16..6fe8886 Binary files a/fine/__pycache__/fineConfig.cpython-36.pyc and b/fine/__pycache__/fineConfig.cpython-36.pyc differ diff --git a/fine/__pycache__/fineConfig.cpython-37.pyc b/fine/__pycache__/fineConfig.cpython-37.pyc new file mode 100755 index 0000000..388232b Binary files /dev/null and b/fine/__pycache__/fineConfig.cpython-37.pyc differ diff --git a/fine/__pycache__/fineConfig.cpython-38.pyc b/fine/__pycache__/fineConfig.cpython-38.pyc new file mode 100755 index 0000000..6010d5d Binary files /dev/null and b/fine/__pycache__/fineConfig.cpython-38.pyc differ diff --git a/fine/__pycache__/fineConfig.cpython-39.pyc b/fine/__pycache__/fineConfig.cpython-39.pyc new file mode 100755 index 0000000..6d4f0a1 Binary files /dev/null and b/fine/__pycache__/fineConfig.cpython-39.pyc differ diff --git a/fine/fineConfig.py b/fine/fineConfig.py index c9a8aca..9caf97a 100755 --- a/fine/fineConfig.py +++ b/fine/fineConfig.py @@ -2,7 +2,7 @@ import os import pandas as pd import torch -from fine.transforms import transforms +from torchvision import transforms @@ -14,9 +14,7 @@ def load_data_transformers(resize_reso=512, crop_reso=448, swap_num=[7, 7]): center_resize = 600 Normalize = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) data_transforms = { - 'swap': transforms.Compose([ - transforms.Randomswap((swap_num[0], swap_num[1])), - ]), + 'common_aug': transforms.Compose([ transforms.Resize((resize_reso, resize_reso)), transforms.RandomRotation(degrees=15), # 将图片进行随机旋转 @@ -35,8 +33,7 @@ def load_data_transformers(resize_reso=512, crop_reso=448, swap_num=[7, 7]): transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), ]), 'test_totensor': transforms.Compose([ - transforms.Resize((resize_reso, resize_reso)), - transforms.CenterCrop((crop_reso, crop_reso)), + transforms.Resizepadding((crop_reso, crop_reso)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), ]), diff --git a/fine/models/__pycache__/LoadModel.cpython-36.pyc b/fine/models/__pycache__/LoadModel.cpython-36.pyc old mode 100644 new mode 100755 index dc530fd..350915e Binary files a/fine/models/__pycache__/LoadModel.cpython-36.pyc and b/fine/models/__pycache__/LoadModel.cpython-36.pyc differ diff --git a/fine/models/__pycache__/LoadModel.cpython-37.pyc b/fine/models/__pycache__/LoadModel.cpython-37.pyc new file mode 100755 index 0000000..de30e9d Binary files /dev/null and b/fine/models/__pycache__/LoadModel.cpython-37.pyc differ diff --git a/fine/models/__pycache__/LoadModel.cpython-38.pyc b/fine/models/__pycache__/LoadModel.cpython-38.pyc new file mode 100755 index 0000000..a6f1cb1 Binary files /dev/null and b/fine/models/__pycache__/LoadModel.cpython-38.pyc differ diff --git a/fine/transforms/__pycache__/__init__.cpython-36.pyc b/fine/transforms/__pycache__/__init__.cpython-36.pyc old mode 100644 new mode 100755 index d55ab35..85c2bcc Binary files a/fine/transforms/__pycache__/__init__.cpython-36.pyc and b/fine/transforms/__pycache__/__init__.cpython-36.pyc differ diff --git a/fine/transforms/__pycache__/__init__.cpython-37.pyc b/fine/transforms/__pycache__/__init__.cpython-37.pyc new file mode 100755 index 0000000..2ffa9f2 Binary files /dev/null and b/fine/transforms/__pycache__/__init__.cpython-37.pyc differ diff --git a/fine/transforms/__pycache__/__init__.cpython-38.pyc b/fine/transforms/__pycache__/__init__.cpython-38.pyc new file mode 100755 index 0000000..a97ccc1 Binary files /dev/null and b/fine/transforms/__pycache__/__init__.cpython-38.pyc differ diff --git a/fine/transforms/__pycache__/functional.cpython-36.pyc b/fine/transforms/__pycache__/functional.cpython-36.pyc old mode 100644 new mode 100755 index f24a306..de657c0 Binary files a/fine/transforms/__pycache__/functional.cpython-36.pyc and b/fine/transforms/__pycache__/functional.cpython-36.pyc differ diff --git a/fine/transforms/__pycache__/functional.cpython-37.pyc b/fine/transforms/__pycache__/functional.cpython-37.pyc new file mode 100755 index 0000000..802bff4 Binary files /dev/null and b/fine/transforms/__pycache__/functional.cpython-37.pyc differ diff --git a/fine/transforms/__pycache__/functional.cpython-38.pyc b/fine/transforms/__pycache__/functional.cpython-38.pyc new file mode 100755 index 0000000..a00ac61 Binary files /dev/null and b/fine/transforms/__pycache__/functional.cpython-38.pyc differ diff --git a/fine/transforms/__pycache__/transforms.cpython-36.pyc b/fine/transforms/__pycache__/transforms.cpython-36.pyc old mode 100644 new mode 100755 index 92d14bf..8ef0b40 Binary files a/fine/transforms/__pycache__/transforms.cpython-36.pyc and b/fine/transforms/__pycache__/transforms.cpython-36.pyc differ diff --git a/fine/transforms/__pycache__/transforms.cpython-37.pyc b/fine/transforms/__pycache__/transforms.cpython-37.pyc new file mode 100755 index 0000000..f9ce49e Binary files /dev/null and b/fine/transforms/__pycache__/transforms.cpython-37.pyc differ diff --git a/fine/transforms/__pycache__/transforms.cpython-38.pyc b/fine/transforms/__pycache__/transforms.cpython-38.pyc new file mode 100755 index 0000000..e4d600e Binary files /dev/null and b/fine/transforms/__pycache__/transforms.cpython-38.pyc differ diff --git a/frame_1047.jpg b/frame_1047.jpg new file mode 100644 index 0000000..6eabe10 Binary files /dev/null and b/frame_1047.jpg differ diff --git a/frame_13.jpg b/frame_13.jpg new file mode 100644 index 0000000..6934850 Binary files /dev/null and b/frame_13.jpg differ diff --git a/frame_196.jpg b/frame_196.jpg new file mode 100644 index 0000000..7f1ac49 Binary files /dev/null and b/frame_196.jpg differ diff --git a/frame_290.jpg b/frame_290.jpg new file mode 100644 index 0000000..15d6b44 Binary files /dev/null and b/frame_290.jpg differ diff --git a/frame_381.jpg b/frame_381.jpg new file mode 100644 index 0000000..a7c3149 Binary files /dev/null and b/frame_381.jpg differ diff --git a/frame_483.jpg b/frame_483.jpg new file mode 100644 index 0000000..6371547 Binary files /dev/null and b/frame_483.jpg differ diff --git a/frame_697.jpg b/frame_697.jpg new file mode 100644 index 0000000..407d2f2 Binary files /dev/null and b/frame_697.jpg differ diff --git a/frame_798.jpg b/frame_798.jpg new file mode 100644 index 0000000..db6b66b Binary files /dev/null and b/frame_798.jpg differ diff --git a/frame_82.jpg b/frame_82.jpg new file mode 100644 index 0000000..88a5ada Binary files /dev/null and b/frame_82.jpg differ diff --git a/frame_893.jpg b/frame_893.jpg new file mode 100644 index 0000000..6ed0305 Binary files /dev/null and b/frame_893.jpg differ diff --git a/get_fine_dataset.py b/get_fine_dataset.py index adfe9a8..ad412f1 100755 --- a/get_fine_dataset.py +++ b/get_fine_dataset.py @@ -53,7 +53,7 @@ def VocToFineWithLabel(num_count,root_path,image_T): ymin = object_id.getElementsByTagName('bndbox')[0].getElementsByTagName('ymin')[0].childNodes[0].data xmax = object_id.getElementsByTagName('bndbox')[0].getElementsByTagName('xmax')[0].childNodes[0].data ymax = object_id.getElementsByTagName('bndbox')[0].getElementsByTagName('ymax')[0].childNodes[0].data - name = object_id.getElementsByTagName('name')[0].childNodes[0].data + name = "bird"#object_id.getElementsByTagName('name')[0].childNodes[0].data ratio_x = (3840.0/3840.0) ratio_y = (2160.0/2160.0) #print(ratio_x," ",ratio_y) @@ -65,7 +65,10 @@ def VocToFineWithLabel(num_count,root_path,image_T): ymax = int(float(ymax)*ratio_y) if ((xmax - xmin)2: + # break + if os.path.isdir(folder_path): # Ensure it's a directory + # Iterate through all audio files in the folder + + for audio_name in os.listdir(folder_path): + if audio_name.lower().endswith(('.mp4')): # Check audio extensions + audio_path = os.path.join(folder_path, audio_name) + + # Fill the Excel sheet + sheet.cell(row=last_row, column=1, value=last_row - 1) # Sequence number + sheet.cell(row=last_row, column=2, value=audio_path) # Audio data + sheet.cell(row=last_row, column=3, value=folder_name) # Label (folder name) + sheet.cell(row=last_row, column=4, value=0) # Data function type is always 1 + + # Increment the row index for the next entry + last_row += 1 + + # Save the updated workbook + workbook.save(workbook_path) # Save the changes to the same file + +# Uncomment the following line to run the function with actual file paths in a real environment +update_excel_with_audio_data(audio_base_path, sheet) \ No newline at end of file diff --git a/qijian_image_det_mysql.py b/qijian_image_det_mysql.py new file mode 100755 index 0000000..adb4850 --- /dev/null +++ b/qijian_image_det_mysql.py @@ -0,0 +1,47 @@ +import os +from PIL import Image +from openpyxl import load_workbook +from tqdm import tqdm + +# Define the base paths for images and labels +base_path = "/data5/Temp_ProjectData/QiJianProject/2022ZD0116304-202405/Images/CDB" +image_folder = os.path.join(base_path, "JPEGImages") +label_folder = os.path.join(base_path, "txt") + +# Load the Excel workbook and select the first sheet +workbook_path = "/data1/Hatcher/model/project/MPKFNet/大规模数据库-图像.xlsx" # Update this with the actual path to the Excel file +workbook = load_workbook(workbook_path) +sheet = workbook.active # Assuming the first sheet is the target one + +# Helper function to get image dimensions +def get_image_dimensions(image_path): + with Image.open(image_path) as img: + return img.size # Returns (width, height) + +# Start filling the Excel from row 2 (row 1 is the header) +row_index = 2 + +# Iterate over images and corresponding label files +for image_name in tqdm(os.listdir(image_folder)): + if image_name.endswith(".jpg"): # Ensure the file is a JPEG image + # Construct full paths for the image and label + image_path = os.path.join(image_folder, image_name) + label_name = os.path.splitext(image_name)[0] + ".txt" + label_path = os.path.join(label_folder, label_name) + + # Get image dimensions + dimensions = get_image_dimensions(image_path) + + # Fill in the Excel sheet + sheet.cell(row=row_index, column=1, value=row_index - 1) # Sequence number + sheet.cell(row=row_index, column=2, value=image_path) # Original image data + sheet.cell(row=row_index, column=3, value=label_path) # Label + sheet.cell(row=row_index, column=4, value=f"{dimensions[0]}x{dimensions[1]}") # Image size + sheet.cell(row=row_index, column=5, value=0) # Data function type + + # Increment the row index for the next entry + row_index += 1 + + +# Save the updated workbook +workbook.save(workbook_path) \ No newline at end of file diff --git a/qijian_image_fine_mysql.py b/qijian_image_fine_mysql.py new file mode 100755 index 0000000..6719f62 --- /dev/null +++ b/qijian_image_fine_mysql.py @@ -0,0 +1,51 @@ +import os +from PIL import Image +from openpyxl import load_workbook +from tqdm import tqdm +# Define the base path for the dataset +base_path = "/data5/Temp_ProjectData/QiJianProject/2022ZD0116304-202405/Images/CMB/OrginalData" + +# Load the Excel workbook and select the active sheet +workbook_path = "/data1/Hatcher/model/project/MPKFNet/大规模数据库-图像.xlsx" # Update this with the actual path to the Excel file +workbook = load_workbook(workbook_path) +sheet = workbook.active # Assuming the active sheet is the one we need + +# Function to get image dimensions +def get_image_dimensions(image_path): + with Image.open(image_path) as img: + return img.size # Returns (width, height) + +# Find the last row with data to continue from there +last_row = sheet.max_row + 1 + +# Function to update the Excel with new image data +def update_excel_with_images(base_path, start_row): + # Iterate through all subfolders in the base directory + a = 0 + for folder_name in tqdm(os.listdir(base_path)): + folder_path = os.path.join(base_path, folder_name) + if os.path.isdir(folder_path): # Ensure it's a directory + # Iterate through all images in the folder + + for image_name in os.listdir(folder_path): + try: + if image_name.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')): # Check image extensions + image_path = os.path.join(folder_path, image_name) + dimensions = get_image_dimensions(image_path) + size_format = f"{dimensions[0]}x{dimensions[1]}" # Format as 'WidthxHeight' + + # Fill the Excel sheet + sheet.cell(row=start_row, column=1, value=start_row - 1) # Sequence number + sheet.cell(row=start_row, column=2, value=image_path) # Original image data + sheet.cell(row=start_row, column=3, value=folder_name) # Label (folder name) + sheet.cell(row=start_row, column=4, value=size_format) # Image size + sheet.cell(row=start_row, column=5, value=1) # Data function type is always 1 + + # Increment the row index for the next entry + start_row += 1 + except: + pass + + return start_row +update_excel_with_images(base_path, last_row) +workbook.save(workbook_path) \ No newline at end of file diff --git a/qijian_quchuchognfu.py b/qijian_quchuchognfu.py new file mode 100755 index 0000000..da73aab --- /dev/null +++ b/qijian_quchuchognfu.py @@ -0,0 +1,23 @@ +text = ("a small bird standing on the ground near some rocks and dirt in the sand and dirt area of the beach or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or field or,") + +# Function to remove excessive duplicates and count them +def remove_duplicates(text): + words = text.split(", ") # Split text into list of phrases by comma + unique_words = [] # List to hold unique phrases + count_dict = {} # Dictionary to hold phrase counts + + # Iterate through words and count occurrences + for word in words: + if word in count_dict: + count_dict[word] += 1 + else: + count_dict[word] = 1 + unique_words.append(word) # Add to unique list only the first time + + # Rejoin the unique words with commas + clean_text = ", ".join(unique_words) + return clean_text, count_dict + +# Call the function and get results +cleaned_text, word_counts = remove_duplicates(text) +print(cleaned_text) \ No newline at end of file diff --git a/qijian_test_sheng_mysql.py b/qijian_test_sheng_mysql.py new file mode 100755 index 0000000..28f35f8 --- /dev/null +++ b/qijian_test_sheng_mysql.py @@ -0,0 +1,46 @@ +import os +import json +from openpyxl import load_workbook +from tqdm import tqdm +def update_excel_with_data(excel_path, data_root): + # 加载工作簿并获取活动工作表 + workbook = load_workbook(excel_path) + sheet = workbook.active + + # 确定开始行 + last_row = sheet.max_row + 1 + + # 遍历目录和文件 + for root, dirs, files in tqdm(os.walk(data_root)): + for file in files: + if file.endswith('.json'): + json_path = os.path.join(root, file) + image_path = os.path.splitext(json_path)[0] + '.jpg' # 假设图像文件是jpg格式 + + # 读取JSON文件 + with open(json_path, 'r', encoding='utf-8') as json_file: + data = json.load(json_file) + content = data.get('content', '') + + # 提取文件夹名称作为关键字 + keyword = os.path.basename(root) + + # 填充Excel表格 + sheet.cell(row=last_row, column=1, value=last_row - 1) # 序号 + sheet.cell(row=last_row, column=2, value=keyword) # 关键字 + sheet.cell(row=last_row, column=3, value=content) # 文本内容 + sheet.cell(row=last_row, column=4, value=1) # 数据功能类型 + sheet.cell(row=last_row, column=5, value=image_path) # 对应图片路径 + + # 为下一条记录增加行索引 + last_row += 1 + + # 保存更新后的工作簿 + workbook.save(excel_path) + +# 路径需要根据您的实际情况调整 +excel_path = '/data1/Hatcher/model/project/MPKFNet/大规模数据库-文本.xlsx' +data_root = '/data5/Hatcher/data/llma/result' + +# 调用此函数以运行 +update_excel_with_data(excel_path, data_root) diff --git a/qijian_video_tsfine_mysql.py b/qijian_video_tsfine_mysql.py new file mode 100755 index 0000000..ed1502b --- /dev/null +++ b/qijian_video_tsfine_mysql.py @@ -0,0 +1,46 @@ +import os +from openpyxl import load_workbook +from tqdm import tqdm +# Define the base paths for the dataset +base_path = "/data5/Temp_ProjectData/QiJianProject/2022ZD0116304-202405/Videos/VOD" +workbook_path = "/data1/Hatcher/model/project/MPKFNet/大规模数据库-视频.xlsx" # Update this with the actual path to the Excel file + +# Load the Excel workbook and select the active sheet +workbook = load_workbook(workbook_path) +sheet = workbook.active # Assuming the active sheet is the one we need + +# Function to update the Excel with new video data +def update_excel_with_video_data(base_path, sheet): + # Find the last row with data to continue from there + last_row = sheet.max_row + 1 + a = 0 + # Iterate through all subfolders in the base directory + for folder_name in tqdm(os.listdir(base_path)): + video_folder_path = os.path.join(base_path, folder_name, "videos") + label_folder_path = os.path.join(base_path, folder_name, "videos_csv") + # a = a+1 + # if a>2: + # break + if os.path.isdir(video_folder_path) and os.path.isdir(label_folder_path): + video_files = os.listdir(video_folder_path) + + # Iterate through all video files in the video folder + for video_name in video_files: + video_path = os.path.join(video_folder_path, video_name) + label_path = os.path.join(label_folder_path, os.path.splitext(video_name)[0] + '.csv') + + if os.path.isfile(video_path) and os.path.isfile(label_path): + # Fill the Excel sheet + sheet.cell(row=last_row, column=1, value=last_row) # Sequence number + sheet.cell(row=last_row, column=2, value=video_path) # Video data + sheet.cell(row=last_row, column=3, value=label_path) # Label (CSV path) + sheet.cell(row=last_row, column=4, value=1) # Data function type is always 1 + + # Increment the row index for the next entry + last_row += 1 + + # Save the updated workbook + workbook.save(workbook_path) # Save the changes to the same file + +# Uncomment the following line to run the function with actual file paths in a real environment +update_excel_with_video_data(base_path, sheet) diff --git a/scan_dealimages.py b/scan_dealimages.py new file mode 100755 index 0000000..6b3f7b8 --- /dev/null +++ b/scan_dealimages.py @@ -0,0 +1,74 @@ +""" +author:Hatcher +e-mail:hcwang@semi.ac.cn +功能:扫描文件夹下面的所有图像,并以文件夹为单位统计鸟类数量 +文件夹格式: + images + data + images.jpg +输出:每个文件夹中保存一个txt文件,每个种类鸟类的数量,所有鸟类种类的数量 + +""" +import os +import torch +import cv2 +from System_I import Detection_Y5,Fine_grained_T +from common import global_para as gp +import json +from tqdm import tqdm +from creat_xml_fordetection import make_xml_scan +root_path = "/data5/Project/scanData/YNDC/scanData/" +save_root = "/data5/Project/scanData/YNDC/result/" +save_json = "/data5/Project/scanData/YNDC/JSON/" +os.environ['CUDA_VISIBLE_DEVICES'] = '7' +devices = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') +Detection = Detection_Y5(devices,root_path) +Fine = Fine_grained_T(devices) +if not os.path.exists(os.path.join(save_json, "ForDataBase")): + os.makedirs(os.path.join(save_json, "ForDataBase")) +if not os.path.exists(os.path.join(save_json, "ForTest")): + os.makedirs(os.path.join(save_json, "ForTest")) +for file_paths in tqdm(os.listdir(root_path)): + box_all = [] + label_all = [] + record_time = file_paths.replace("_","-",2) + record_time = record_time.replace("_"," ",1) + record_time = record_time.replace("_",":") + file_path = os.path.join(root_path,file_paths) + labels_fineall = [] + resultDict = {} + allimageresult =[0 for i in range(len(gp.BHG_chineseName))] + if not os.path.exists(os.path.join(save_root,file_paths)): + os.makedirs(os.path.join(save_root,file_paths)) + for imagepath in os.listdir(file_path): + image = cv2.imread(os.path.join(file_path,imagepath)) + img_show,boxes_fine, labels_fine = Detection.inference_scan(image=image,fine_grained=Fine) + for m in range(len(labels_fine)): + box_all.append(boxes_fine[m]) + label_all.append(gp.BHG_chineseName[int(labels_fine[m])]) + cv2.imwrite(os.path.join(save_root,file_paths,imagepath),img_show) + oneimageresultcdict = {} + oneimageresult =[0 for i in range(len(gp.BHG_chineseName))] + for i in labels_fine: + oneimageresult[int(i)]+=1 + allimageresult[int(i)]+=1 + for i in range(len(oneimageresult)): + if not (int(oneimageresult[i]) == 0): + oneimageresultcdict[gp.BHG_chineseName[i]]=int(oneimageresult[i]) + resultDict[imagepath] = oneimageresultcdict + allimageresultcdict = {} + for i in range(len(allimageresult)): + if not (int(allimageresult[i]) == 0): + allimageresultcdict[gp.BHG_chineseName[i]]=int(allimageresult[i]) + resultDict[file_paths] = allimageresultcdict + json_str = json.dumps(resultDict, indent=4) + with open(os.path.join(save_json,"ForTest",file_paths + "_Test.json"), 'w',encoding='utf-8') as json_file: + #json_file.write(json_str) + json.dump(resultDict,json_file,indent=4,ensure_ascii=False) + json_conversion = make_xml_scan(record_time=record_time, serial_number="iDS-2DF8C840IXS-AFW/SP20220507CCCHJ90488961",boxes=box_all,labels=label_all, savename=os.path.join(save_json,"ForDataBase" ,file_paths + "_DataBase.json")) + + + + + + diff --git a/scanforgao.py b/scanforgao.py new file mode 100755 index 0000000..a54726c --- /dev/null +++ b/scanforgao.py @@ -0,0 +1,179 @@ +import json +import time + +import zeep +from onvif import ONVIFCamera + + + +hangshu =7 +lieshu = 60 +#cv2.namedWindow("AI-ECO",cv2.WINDOW_FREERATIO)#WINDOW_FREERATIO +record_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) +def zeep_pythonvalue(self, xmlvalue): + return xmlvalue + + +class Onvif_hik(object): + + def __init__(self, ip: str, username: str, password: str): + self.ip = ip + self.username = username + self.password = password + self.save_path = "./{}T{}.jpg".format(self.ip, str(time.time())) # ½ØÍ¼±£´æÂ·¾¶ + self.content_cam() + + def content_cam(self): + """ + Á´½ÓÏà»úµØÖ· + :return: + """ + try: + self.mycam = ONVIFCamera(self.ip,1024 , self.username, self.password) + self.media = self.mycam.create_media_service() # ´´½¨Ã½Ìå·þÎñ + # µÃµ½Ä¿±ê¸ÅÒªÎļþ + zeep.xsd.simple.AnySimpleType.pythonvalue = zeep_pythonvalue + self.media_profile = self.media.GetProfiles()[0] # »ñÈ¡ÅäÖÃÐÅÏ¢ + self.ptz = self.mycam.create_ptz_service() # ´´½¨¿ØÖÆÌ¨·þÎñ + return True + except Exception as e: + return False + + def Snapshot(self): + """ + ½ØÍ¼ + :return: + """ + res = self.media.GetSnapshotUri({'ProfileToken': self.media_profile.token}) + + response = requests.get(res.Uri, auth=HTTPDigestAuth(self.username, self.password)) + with open(self.save_path, 'wb') as f: # ±£´æ½ØÍ¼ + f.write(response.content) + + def get_presets(self): + """ + »ñȡԤÖõãÁбí + :return:Ô¤ÖõãÁбí--ËùÓеÄÔ¤Öõã + """ + presets = self.ptz.GetPresets({'ProfileToken': self.media_profile.token}) # »ñÈ¡ËùÓÐÔ¤Öõã,·µ»ØÖµ£ºlist + return presets + + def goto_preset(self, presets_token: int): + """ + ÒÆ¶¯µ½Ö¸¶¨Ô¤Öõã + :param presets_token: Ä¿µÄλÖõÄtoken£¬»ñȡԤÖõ㷵»ØÖµÖÐ + :return: + """ + try: + # self.ptz.GotoPreset( + # {'ProfileToken': self.media_profile.token, "PresetToken": presets_token}) # ÒÆ¶¯µ½Ö¸¶¨Ô¤ÖõãλÖà + params = self.ptz.create_type('GotoPreset') + params.ProfileToken = self.media_profile.token + params.PresetToken = presets_token + self.ptz.GotoPreset(params) + except Exception as e: + print(e) + + def zoom(self, zoom: str, timeout: int = 1): + """ + ±ä½¹ + :param zoom: 1ΪÀ­½ü»ò-1ΪԶÀë + :param timeout: ÉúЧʱ¼ä + :return: + """ + request = self.ptz.create_type('ContinuousMove') + request.ProfileToken = self.media_profile.token + request.Velocity = {"Zoom": zoom} + self.ptz.ContinuousMove(request) + time.sleep(timeout) + self.ptz.Stop({'ProfileToken': request.ProfileToken}) + + def get_status(self): + """ + »ñÈ¡µ±Ç°Ô¤ÖõãµÄÐÅÏ¢ + :return: + """ + params = self.ptz.create_type('GetStatus') + params.ProfileToken = self.media_profile.token + res = self.ptz.GetStatus(params) + print(res.MoveStatus.PanTilt) + return res + + def absolute_move(self,p=180,t=0,z=0): + pan = p/180.0#0.988889 #- left + right + pan_speed = 1 + tilt = 0.618182 - t/55.0 #+up -down 0~1 + tilt_speed = 1 + zoom = 1-z + zoom_speed = 1 + + # Create media service object + # Get target profile + request = self.ptz.create_type('AbsoluteMove') + request.ProfileToken = self.media_profile.token + self.ptz.Stop({'ProfileToken': self.media_profile.token}) + if request.Position is None: + request.Position = self.ptz.GetStatus({'ProfileToken': self.media_profile.token}).Position + if request.Speed is None: + request.Speed = self.ptz.GetStatus({'ProfileToken': self.media_profile.token}).Position + request.Position.PanTilt.x = pan + request.Speed.PanTilt.x = pan_speed + request.Position.PanTilt.y = tilt + request.Speed.PanTilt.y = tilt_speed + request.Position.Zoom = zoom + request.Speed.Zoom = zoom_speed + self.ptz.AbsoluteMove(request) + print('finish') + +def deal (p,t,z,o,cap,num,Detection,Fine,img,start): + print(p, " ", t, " ", z) + o.absolute_move(p, t, z) + #time.sleep(1) + label = [] + errorNum = 0 + while (o.get_status().MoveStatus.PanTilt != "IDLE"): + print("camera is moving") + if start: + time.sleep(5) + while True: + cap = cv2.VideoCapture("rtsp://admin:whc123456@192.0.0.30:554/h264/ch1/main/av_stream") + if cap.isOpened(): + #time.sleep(1) + + # allcount = cap.get(cv2.CAP_PROP_FRAME_COUNT) + # cap.set(cv2.CAP_PROP_POS_FRAMES,allcount) + res, frame = cap.read() + #a = cap.get(cv2.CAP_PROP_BUFFERSIZE) + + # print(allcount) + # while not res: + # res, frame = cap.read() + if res: + + img_show, label,box = Detection.inference(frame, Fine) + img_show = cv2.resize(img_show,(1024,768)) + # cv2.imshow("AI-ECO",img_show) + # cv2.waitKey(1) + img.append( Image.fromarray(cv2.cvtColor(img_show, cv2.COLOR_BGR2RGB))) + #cv2.imwrite("./test/{}_{}.jpg".format(str(j).zfill(2), str(i).zfill(2)), img_show) + num += 1 + break + else: + print("empty") + errorNum+=1 + if errorNum>=2: + cap = cv2.VideoCapture("rtsp://admin:whc123456@192.0.0.30:554/h264/ch1/main/av_stream") + + return num,img,label,box +def long_pic_paste(image): + image_result = Image.new(image[0][0].mode, ( 1024 * lieshu,hangshu * 768), 0xffffff) + for j in range(hangshu): + for i in range(lieshu): + #print(j," ",i) + image_result.paste(image[j][i], (i*1024, j*768)) + image_result.save("../data_MPKFNet/result/{}.jpg".format(record_time)) +if __name__ == '__main__': + + + o = Onvif_hik(ip="117.178.217.84", username="admin", password="Aa123456") + o.absolute_move(1, 0.5, 0.5) \ No newline at end of file diff --git a/small_object/aitod_getclass.py b/small_object/aitod_getclass.py new file mode 100755 index 0000000..dada9bf --- /dev/null +++ b/small_object/aitod_getclass.py @@ -0,0 +1,57 @@ +""" +author:Hatcher +email:hcwang@semi.ac.cn +use:将aitod小目标检测数据集按照类别分开 +input: +voc + train_images + train_annos + .... + test&val +output: +voc_class + classname1 + images + annos + classname2 + iamges + annos + ..... + +""" +import os +from tqdm import tqdm +import xml.dom.minidom +import shutil +source_path_root = "/data4/Hatcher/smallobject/voc/test_annos/" +det_path_root = "/data4/Hatcher/smallobject/voc_class/" +class_names = ["airplane"]#os.listdir(det_path_root) +for class_name in class_names: + for source_path_anno in tqdm(os.listdir(source_path_root)): + source_path = os.path.join(source_path_root,source_path_anno) + dom = xml.dom.minidom.parse(source_path) + root = dom.documentElement + objects=dom.getElementsByTagName("object") + for object in objects: + bndbox = object.getElementsByTagName('bndbox')[0] + xmin = bndbox.getElementsByTagName('xmin')[0] + ymin = bndbox.getElementsByTagName('ymin')[0] + xmax = bndbox.getElementsByTagName('xmax')[0] + ymax = bndbox.getElementsByTagName('ymax')[0] + #print(xmin.childNodes[0].data) + #print(type(xmin.childNodes[0].data)) + xmin_data=int(xmin.childNodes[0].data) + ymin_data=int(ymin.childNodes[0].data) + xmax_data=int(xmax.childNodes[0].data) + ymax_data=int(ymax.childNodes[0].data) + label_name=object.getElementsByTagName('name')[0].childNodes[0].data + if not (label_name==class_name): + dom.documentElement.removeChild(object) + objects=dom.getElementsByTagName("object") + if not (len(objects)==0): + #存储xml,复制图像 + xml_path = os.path.join(det_path_root,class_name,"annos",source_path_anno) + fp = open(xml_path, 'w', encoding='utf-8') + dom.writexml(fp, indent='', addindent='\t', newl='\n', encoding='utf-8') + fp.close() + shutil.copy(source_path.replace("test_annos","test_images").replace(".xml",".png"),os.path.join(det_path_root,class_name,"images",source_path_anno.replace(".xml",".png"))) diff --git a/sort/__pycache__/sort.cpython-36.pyc b/sort/__pycache__/sort.cpython-36.pyc old mode 100644 new mode 100755 index 7b5d1b4..e7c3418 Binary files a/sort/__pycache__/sort.cpython-36.pyc and b/sort/__pycache__/sort.cpython-36.pyc differ diff --git a/sort/__pycache__/sort.cpython-37.pyc b/sort/__pycache__/sort.cpython-37.pyc new file mode 100755 index 0000000..8d8f62c Binary files /dev/null and b/sort/__pycache__/sort.cpython-37.pyc differ diff --git a/sort/__pycache__/sort.cpython-38.pyc b/sort/__pycache__/sort.cpython-38.pyc new file mode 100755 index 0000000..3ec2566 Binary files /dev/null and b/sort/__pycache__/sort.cpython-38.pyc differ diff --git a/sort/sort.py b/sort/sort.py index 7c6c0b3..afc3331 100755 --- a/sort/sort.py +++ b/sort/sort.py @@ -20,7 +20,7 @@ from __future__ import print_function import os import numpy as np import matplotlib -matplotlib.use('TkAgg') +#matplotlib.use('TkAgg') import matplotlib.pyplot as plt import matplotlib.patches as patches from skimage import io diff --git a/ssd/__pycache__/__init__.cpython-37.pyc b/ssd/__pycache__/__init__.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/config/__pycache__/__init__.cpython-37.pyc b/ssd/config/__pycache__/__init__.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/config/__pycache__/defaults.cpython-37.pyc b/ssd/config/__pycache__/defaults.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/config/__pycache__/path_catlog.cpython-36.pyc b/ssd/config/__pycache__/path_catlog.cpython-36.pyc old mode 100644 new mode 100755 diff --git a/ssd/config/__pycache__/path_catlog.cpython-37.pyc b/ssd/config/__pycache__/path_catlog.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/data/__pycache__/__init__.cpython-37.pyc b/ssd/data/__pycache__/__init__.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/data/datasets/__pycache__/__init__.cpython-37.pyc b/ssd/data/datasets/__pycache__/__init__.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/data/datasets/__pycache__/coco.cpython-37.pyc b/ssd/data/datasets/__pycache__/coco.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/data/datasets/__pycache__/voc.cpython-37.pyc b/ssd/data/datasets/__pycache__/voc.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/data/transforms/__pycache__/__init__.cpython-37.pyc b/ssd/data/transforms/__pycache__/__init__.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/data/transforms/__pycache__/target_transform.cpython-37.pyc b/ssd/data/transforms/__pycache__/target_transform.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/data/transforms/__pycache__/transforms.cpython-37.pyc b/ssd/data/transforms/__pycache__/transforms.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/modeling/__pycache__/__init__.cpython-37.pyc b/ssd/modeling/__pycache__/__init__.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/modeling/anchors/__pycache__/__init__.cpython-37.pyc b/ssd/modeling/anchors/__pycache__/__init__.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/modeling/anchors/__pycache__/prior_box.cpython-37.pyc b/ssd/modeling/anchors/__pycache__/prior_box.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/structures/__pycache__/__init__.cpython-37.pyc b/ssd/structures/__pycache__/__init__.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/structures/__pycache__/container.cpython-37.pyc b/ssd/structures/__pycache__/container.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/utils/__pycache__/__init__.cpython-37.pyc b/ssd/utils/__pycache__/__init__.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/utils/__pycache__/box_utils.cpython-37.pyc b/ssd/utils/__pycache__/box_utils.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/ssd/utils/__pycache__/misc.cpython-37.pyc b/ssd/utils/__pycache__/misc.cpython-37.pyc old mode 100644 new mode 100755 diff --git a/static_map.png b/static_map.png new file mode 100755 index 0000000..d4484ac Binary files /dev/null and b/static_map.png differ diff --git a/sys_long_crowd_jiekou.py b/sys_long_crowd_jiekou.py new file mode 100644 index 0000000..dca1a45 --- /dev/null +++ b/sys_long_crowd_jiekou.py @@ -0,0 +1,294 @@ +import torch +import cv2 +import os +import glob +import numpy as np +import onnxruntime as ort +from tqdm import tqdm +from concurrent.futures import ThreadPoolExecutor +import threading +def preview_frame(video_path, frame_number): + """预览指定帧的图像""" + cap = cv2.VideoCapture(video_path) + cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number) + ret, frame = cap.read() + cap.release() + + if ret: + cv2.imwrite(f'frame_{frame_number}.jpg', frame) + print(f"已保存第 {frame_number} 帧的预览图像") + else: + print(f"无法读取第 {frame_number} 帧") + +def extract_specific_frames(video_path, frame_numbers): + """从视频中提取指定帧号的图像""" + cap = cv2.VideoCapture(video_path) + + # 获取视频基本信息 + frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + + print(f"视频信息:\n分辨率: {frame_width}x{frame_height}\n总帧数: {total_frames}") + + # 创建画布 - 宽度为单帧宽度乘以要提取的帧数 + canvas_width = frame_width * len(frame_numbers) + canvas = np.zeros((frame_height, canvas_width, 3), dtype=np.uint8) + + current_frame = 0 + canvas_position = 0 + + # 按顺序处理指定的帧 + for target_frame in sorted(frame_numbers): + print(f"正在处理第 {target_frame} 帧...") + + # 快进到目标帧 + while current_frame < target_frame: + ret = cap.grab() # 使用grab()而不是read()来快速跳过帧 + if not ret: + print(f"无法读取到第 {target_frame} 帧") + break + current_frame += 1 + + # 读取目标帧 + ret, frame = cap.retrieve() # 获取当前帧的图像数据 + if ret: + # 将帧放入画布 + canvas[:, canvas_position:canvas_position+frame_width] = frame + canvas_position += frame_width + + # 保存每个提取的帧(可选) + cv2.imwrite(f'frame_{target_frame}.jpg', frame) + else: + print(f"无法读取第 {target_frame} 帧的图像数据") + + cap.release() + + # 如果canvas_position小于预期的canvas_width,裁剪未使用的部分 + if canvas_position < canvas_width: + canvas = canvas[:, :canvas_position] + + return canvas + +def preview_all_frames(video_path, interval=10): + """每隔一定间隔预览并保存帧,用于选择合适的帧""" + cap = cv2.VideoCapture(video_path) + total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + + frame_count = 0 + while True: + ret, frame = cap.read() + if not ret: + break + + if frame_count % interval == 0: + cv2.imwrite(f'preview_frame_{frame_count}.jpg', frame) + print(f"已保存第 {frame_count} 帧的预览图像") + + frame_count += 1 + + cap.release() + print(f"总共处理了 {frame_count} 帧") + +def get_longimage(video_path2,output_path): + video_path = video_path2 + + # 是否需要预览帧 + need_preview = False + if need_preview: + # 预览特定帧 + preview_frames = [13, 82, 196, 290, 381] + for frame_num in preview_frames: + preview_frame(video_path, frame_num) + + # 或者每隔10帧预览一次 + # preview_all_frames(video_path, interval=10) + return + + # 指定要提取的帧号 + frame_numbers = [13, 82, 196, 290, 381, 483, 697, 798, 893, 1047] + + # 提取帧并拼接 + panorama = extract_specific_frames(video_path, frame_numbers) + + # 保存结果 + cv2.imwrite(os.path.join(output_path,'panorama.jpg'), panorama) + print(f"全景图已保存,尺寸: {panorama.shape[1]}x{panorama.shape[0]}") +def init_onnx(): + """Initialize ONNX Runtime session""" + test_weights = "/data1/Hatcher/model/PopulationCounting/Bayesian_project_ours/sim-CAS-base-test.onnx" + + if 'CUDAExecutionProvider' in ort.get_available_providers(): + print("CUDA is available. Using GPU.") + providers = ["CUDAExecutionProvider"] if ort.get_device() == "GPU" else ["CPUExecutionProvider"] + else: + print("CUDA not available. Using CPU.") + providers = ["CPUExecutionProvider"] + + ort_session = ort.InferenceSession(test_weights, providers=providers) + return ort_session + +def split_image(image): + """Split large image into 800x800 patches""" + h, w = image.shape[:2] + + # Calculate optimal width for resizing + n_segments = max(1, w // 800) + target_w = n_segments * 800 + scale = target_w / w + + # Resize image to make width divisible by 800 + new_w = target_w + new_h = int(h * scale) + resized_img = cv2.resize(image, (new_w, new_h)) + + # Split into patches + patches = [] + positions = [] # Store original positions for reconstruction + + for i in range(0, new_w, 800): + patch = resized_img[:, i:i+800] + if patch.shape[1] < 800: # Handle last patch if smaller than 800 + continue + patches.append(patch) + positions.append((i, i+800)) + + return patches, positions, scale, (new_h, new_w) + +def process_patch(patch, ort_session): + """Process a single 800x800 patch""" + # Preprocess patch + img = cv2.resize(patch, (800, 800))/255.0 + img = img[np.newaxis, :, :].transpose(0,3,1,2) + input_blob = np.array(img, dtype=np.float32) + + # Run inference + onnx_input_name = ort_session.get_inputs()[0].name + onnx_outputs_names = ort_session.get_outputs()[0].name + onnx_result = ort_session.run([onnx_outputs_names], + input_feed={onnx_input_name: input_blob}) + + # Get density map + density_map = onnx_result[0][0][0] + density_map[density_map<1e-6] = 0 + + return density_map + +def process_single_image(image_path, save_root, ort_session, file_lock): + """Process a single large image""" + try: + # Get image name + image_name = os.path.basename(image_path) + result_name = f"result_{image_name}" + + # Read image + img_or = cv2.imread(image_path) + if img_or is None: + print(f"Failed to read image: {image_path}") + return False + + # Split image into patches + patches, positions, scale, (new_h, new_w) = split_image(img_or) + + # Process each patch + density_maps = [] + total_count = 0 + + for patch in patches: + density_map = process_patch(patch, ort_session) + density_maps.append(density_map) + total_count += np.sum(density_map) + + # Combine density maps + combined_density = np.zeros((new_h, new_w)) + for density_map, (start_x, end_x) in zip(density_maps, positions): + resized_density = cv2.resize(density_map, (800, new_h)) + combined_density[:, start_x:end_x] = resized_density + + # Resize combined density map back to original size + combined_density = cv2.resize(combined_density, (img_or.shape[1], img_or.shape[0])) + + # Create heatmap + heatmap = combined_density/np.max(combined_density) + heatmap = np.power(heatmap, 0.7) # 降低gamma值会使颜色更深 + heatmap = np.uint8(heatmap*255) + heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET) + + # Create visualization + imgheatmap_W = int(img_or.shape[1]/3) + imgheatmap_H = int(img_or.shape[0]/3) + density_result = cv2.resize(heatmap,(imgheatmap_W,imgheatmap_H)) + + # Add density map to top-left corner + img_or[0:imgheatmap_H, 0:imgheatmap_W] = density_result + + # Add count text + + cv2.putText(img_or, f"Count: {int(total_count)}", (50,200), + cv2.FONT_HERSHEY_SIMPLEX, 4, (0,0,255), 8) + + # Save result + save_path = os.path.join(save_root, result_name) + with file_lock: + cv2.imwrite(save_path, img_or) + print(save_path) + + return True + + except Exception as e: + print(f"Error processing {image_path}: {str(e)}") + + return False + +def process_images_batch(input_folder, num_threads=4): + """Process images in parallel""" + # Initialize ONNX session + ort_session = init_onnx() + + # Create output directory + save_root = os.path.join(input_folder, "results") + os.makedirs(save_root, exist_ok=True) + + # Get image paths + image_paths = glob.glob(os.path.join(input_folder, "*.jpg")) + \ + glob.glob(os.path.join(input_folder, "*.png")) + + print(f"Found {len(image_paths)} images to process") + + # Initialize counters and locks + success_count = 0 + counter_lock = threading.Lock() + file_lock = threading.Lock() + + # Create progress bar + pbar = tqdm(total=len(image_paths), desc="Processing images") + + def process_with_progress(image_path): + nonlocal success_count + result = process_single_image(image_path, save_root, ort_session, file_lock) + + with counter_lock: + if result: + success_count += 1 + pbar.update(1) + pbar.set_postfix({'succeeded': success_count}) + + # Process images in parallel + with ThreadPoolExecutor(max_workers=num_threads) as executor: + executor.map(process_with_progress, image_paths) + + pbar.close() + print(f"Processing complete. Successfully processed {success_count} images") + + + +if __name__ == "__main__": + + video_path = "/data1/Hatcher/model/project/MPKFNet/mmexport1733810879708.mp4" + out_put_path = "./20251105001" + if not os.path.exists(out_put_path): + os.makedirs(out_put_path) + get_longimage(video_path,out_put_path) + + # Start processing + process_images_batch(out_put_path) \ No newline at end of file diff --git a/temp.xml b/temp.xml new file mode 100755 index 0000000..2338ab1 --- /dev/null +++ b/temp.xml @@ -0,0 +1,25180 @@ + + 2022-11-13 17:00:37 + iDS-2DF8C840IXS-AFW/SP20220507CCCHJ90488961 + + 红嘴鸥 + + 1 + 1 + 3390 + 1953 + 3471 + 2067 + + + + + 苍鹭 + + 1 + 1 + 964 + 1408 + 1032 + 1560 + + + + + 苍鹭 + + 1 + 1 + 3225 + 1392 + 3305 + 1551 + + + + + 红嘴鸥 + + 1 + 1 + 3060 + 1981 + 3159 + 2057 + + + + + 红嘴鸥 + + 1 + 1 + 2909 + 1477 + 2953 + 1548 + + + + + 苍鹭 + + 1 + 1 + 180 + 1377 + 251 + 1556 + + + + + 红嘴鸥 + + 1 + 1 + 3679 + 1972 + 3761 + 2055 + + + + + 红嘴鸥 + + 1 + 1 + 1527 + 1963 + 1593 + 2047 + + + + + 苍鹭 + + 1 + 1 + 2518 + 1403 + 2579 + 1551 + + + + + 红嘴鸥 + + 1 + 1 + 2562 + 1960 + 2630 + 2046 + + + + + 苍鹭 + + 1 + 1 + 1866 + 1398 + 1929 + 1549 + + + + + 红嘴鸥 + + 1 + 1 + 1322 + 1966 + 1385 + 2050 + + + + + 红嘴鸥 + + 1 + 1 + 1761 + 1956 + 1821 + 2043 + + + + + 红嘴鸥 + + 1 + 1 + 2235 + 1952 + 2293 + 2046 + + + + + 红嘴鸥 + + 1 + 1 + 3667 + 1478 + 3716 + 1551 + + + + + 红嘴鸥 + + 1 + 1 + 123 + 1976 + 181 + 2058 + + + + + 红嘴鸥 + + 1 + 1 + 650 + 1483 + 688 + 1552 + + + + + 红嘴鸥 + + 1 + 1 + 356 + 1980 + 406 + 2051 + + + + + 红嘴鸥 + + 1 + 1 + 796 + 1975 + 860 + 2049 + + + + + 苍鹭 + + 1 + 1 + 3515 + 1484 + 3575 + 1548 + + + + + 红嘴鸥 + + 1 + 1 + 2775 + 1478 + 2816 + 1547 + + + + + 红嘴鸥 + + 1 + 1 + 2147 + 1495 + 2197 + 1547 + + + + + 红嘴鸥 + + 1 + 1 + 1468 + 1490 + 1514 + 1549 + + + + + 红嘴鸥 + + 1 + 1 + 3820 + 1486 + 3839 + 1550 + + + + + 苍鹭 + + 1 + 1 + 1814 + 981 + 1839 + 1049 + + + + + 红嘴鸥 + + 1 + 1 + 471 + 257 + 603 + 298 + + + + + 鸟 + + 1 + 1 + 1229 + 336 + 1321 + 477 + + + + + 鸟 + + 1 + 1 + 2317 + 296 + 2437 + 427 + + + + + 鸟 + + 1 + 1 + 95 + 390 + 189 + 525 + + + + + 鸟 + + 1 + 1 + 2569 + 269 + 2711 + 373 + + + + + 鸟 + + 1 + 1 + 2948 + 263 + 3129 + 415 + + + + + 鸟 + + 1 + 1 + 503 + 359 + 569 + 516 + + + + + 红嘴鸥 + + 1 + 1 + 661 + 2065 + 685 + 2113 + + + + + 红嘴鸥 + + 1 + 1 + 28 + 2039 + 62 + 2072 + + + + + 红嘴鸥 + + 1 + 1 + 1044 + 2088 + 1081 + 2123 + + + + + 红嘴鸥 + + 1 + 1 + 726 + 2070 + 761 + 2102 + + + + + 红嘴鸥 + + 1 + 1 + 361 + 2056 + 409 + 2094 + + + + + 红嘴鸥 + + 1 + 1 + 2949 + 369 + 3030 + 420 + + + + + 红嘴鸥 + + 1 + 1 + 681 + 214 + 711 + 268 + + + + + 红嘴鸥 + + 1 + 1 + 3135 + 387 + 3197 + 430 + + + + + 红嘴鸥 + + 1 + 1 + 605 + 216 + 659 + 267 + + + + + 红嘴鸥 + + 1 + 1 + 1020 + 256 + 1089 + 297 + + + + + 红嘴鸥 + + 1 + 1 + 3273 + 388 + 3341 + 434 + + + + + 红嘴鸥 + + 1 + 1 + 2059 + 311 + 2113 + 363 + + + + + 红嘴鸥 + + 1 + 1 + 1 + 167 + 64 + 221 + + + + + 红嘴鸥 + + 1 + 1 + 1542 + 273 + 1606 + 329 + + + + + 红嘴鸥 + + 1 + 1 + 870 + 234 + 911 + 283 + + + + + 红嘴鸥 + + 1 + 1 + 2896 + 363 + 2928 + 412 + + + + + 鸟 + + 1 + 1 + 173 + 191 + 214 + 231 + + + + + 红嘴鸥 + + 1 + 1 + 758 + 237 + 825 + 275 + + + + + 红嘴鸥 + + 1 + 1 + 1101 + 252 + 1151 + 296 + + + + + 红嘴鸥 + + 1 + 1 + 950 + 242 + 983 + 289 + + + + + 鸟 + + 1 + 1 + 2248 + 318 + 2280 + 371 + + + + + 红嘴鸥 + + 1 + 1 + 1398 + 267 + 1433 + 318 + + + + + 红嘴鸥 + + 1 + 1 + 1171 + 266 + 1222 + 309 + + + + + 红嘴鸥 + + 1 + 1 + 2555 + 342 + 2615 + 389 + + + + + 红嘴鸥 + + 1 + 1 + 2651 + 352 + 2693 + 396 + + + + + 鸟 + + 1 + 1 + 2401 + 752 + 2470 + 785 + + + + + 红嘴鸥 + + 1 + 1 + 288 + 200 + 321 + 240 + + + + + 红嘴鸥 + + 1 + 1 + 229 + 195 + 279 + 236 + + + + + 鸟 + + 1 + 1 + 3044 + 833 + 3111 + 886 + + + + + 红嘴鸥 + + 1 + 1 + 107 + 183 + 145 + 230 + + + + + 鸟 + + 1 + 1 + 2169 + 753 + 2250 + 791 + + + + + 红嘴鸥 + + 1 + 1 + 1224 + 262 + 1268 + 317 + + + + + 红嘴鸥 + + 1 + 1 + 3094 + 325 + 3163 + 358 + + + + + 鸟 + + 1 + 1 + 532 + 213 + 577 + 258 + + + + + 鸟 + + 1 + 1 + 414 + 208 + 479 + 250 + + + + + 鸟 + + 1 + 1 + 3133 + 833 + 3192 + 884 + + + + + 红嘴鸥 + + 1 + 1 + 2433 + 335 + 2501 + 386 + + + + + 鸟 + + 1 + 1 + 3430 + 844 + 3540 + 887 + + + + + 红嘴鸥 + + 1 + 1 + 2704 + 356 + 2774 + 402 + + + + + 红嘴鸥 + + 1 + 1 + 2073 + 107 + 2127 + 146 + + + + + 红嘴鸥 + + 1 + 1 + 3748 + 410 + 3819 + 458 + + + + + 红嘴鸥 + + 1 + 1 + 3638 + 424 + 3675 + 460 + + + + + 鸟 + + 1 + 1 + 2935 + 813 + 3022 + 857 + + + + + 红嘴鸥 + + 1 + 1 + 3325 + 802 + 3391 + 834 + + + + + 鸟 + + 1 + 1 + 3189 + 797 + 3238 + 830 + + + + + 鸟 + + 1 + 1 + 2645 + 733 + 2727 + 772 + + + + + 红嘴鸥 + + 1 + 1 + 2502 + 331 + 2549 + 380 + + + + + 鸟 + + 1 + 1 + 2769 + 354 + 2818 + 403 + + + + + 红嘴鸥 + + 1 + 1 + 2810 + 355 + 2883 + 404 + + + + + 红嘴鸥 + + 1 + 1 + 3045 + 377 + 3093 + 424 + + + + + 红嘴鸥 + + 1 + 1 + 2167 + 316 + 2199 + 358 + + + + + 鸟 + + 1 + 1 + 2310 + 116 + 2356 + 163 + + + + + 鸟 + + 1 + 1 + 2193 + 633 + 2251 + 699 + + + + + 红嘴鸥 + + 1 + 1 + 3318 + 162 + 3345 + 208 + + + + + 鸟 + + 1 + 1 + 1125 + 711 + 1182 + 743 + + + + + 鸟 + + 1 + 1 + 1307 + 261 + 1342 + 317 + + + + + 鸟 + + 1 + 1 + 3408 + 904 + 3502 + 948 + + + + + 红嘴鸥 + + 1 + 1 + 1685 + 281 + 1723 + 335 + + + + + 鸟 + + 1 + 1 + 2526 + 779 + 2610 + 822 + + + + + 红嘴鸥 + + 1 + 1 + 2370 + 332 + 2416 + 374 + + + + + 鸟 + + 1 + 1 + 1627 + 268 + 1675 + 330 + + + + + 红嘴鸥 + + 1 + 1 + 3376 + 395 + 3415 + 431 + + + + + 红嘴鸥 + + 1 + 1 + 2312 + 327 + 2371 + 370 + + + + + 鸟 + + 1 + 1 + 3535 + 900 + 3616 + 943 + + + + + 红嘴鸥 + + 1 + 1 + 1571 + 87 + 1619 + 115 + + + + + 红嘴鸥 + + 1 + 1 + 3531 + 413 + 3570 + 450 + + + + + 红嘴鸥 + + 1 + 1 + 3651 + 801 + 3711 + 843 + + + + + 红嘴鸥 + + 1 + 1 + 2800 + 149 + 2837 + 192 + + + + + 红嘴鸥 + + 1 + 1 + 1344 + 94 + 1380 + 134 + + + + + 红嘴鸥 + + 1 + 1 + 995 + 18 + 1021 + 57 + + + + + 红嘴鸥 + + 1 + 1 + 487 + 621 + 534 + 646 + + + + + 红嘴鸥 + + 1 + 1 + 3227 + 165 + 3257 + 206 + + + + + 红嘴鸥 + + 1 + 1 + 2897 + 100 + 2940 + 141 + + + + + 红嘴鸥 + + 1 + 1 + 2936 + 151 + 2972 + 197 + + + + + 红嘴鸥 + + 1 + 1 + 2151 + 119 + 2183 + 162 + + + + + 鸟 + + 1 + 1 + 1444 + 737 + 1509 + 781 + + + + + 红嘴鸥 + + 1 + 1 + 2391 + 124 + 2419 + 174 + + + + + 红嘴鸥 + + 1 + 1 + 2728 + 142 + 2757 + 174 + + + + + 红嘴鸥 + + 1 + 1 + 3039 + 148 + 3067 + 199 + + + + + 鸟 + + 1 + 1 + 150 + 555 + 195 + 612 + + + + + 红嘴鸥 + + 1 + 1 + 416 + 8 + 470 + 49 + + + + + 红嘴鸥 + + 1 + 1 + 1673 + 90 + 1720 + 123 + + + + + 红嘴鸥 + + 1 + 1 + 874 + 3 + 900 + 40 + + + + + 鸟 + + 1 + 1 + 3766 + 186 + 3822 + 229 + + + + + 红嘴鸥 + + 1 + 1 + 3125 + 185 + 3161 + 221 + + + + + 红嘴鸥 + + 1 + 1 + 2866 + 144 + 2898 + 182 + + + + + 鸟 + + 1 + 1 + 1355 + 719 + 1458 + 757 + + + + + 红嘴鸥 + + 1 + 1 + 2532 + 129 + 2564 + 162 + + + + + 红嘴鸥 + + 1 + 1 + 911 + 6 + 942 + 42 + + + + + 红嘴鸥 + + 1 + 1 + 1483 + 77 + 1526 + 117 + + + + + 红嘴鸥 + + 1 + 1 + 1187 + 144 + 1238 + 186 + + + + + 红嘴鸥 + + 1 + 1 + 1828 + 96 + 1853 + 141 + + + + + 红嘴鸥 + + 1 + 1 + 2589 + 144 + 2627 + 176 + + + + + 红嘴鸥 + + 1 + 1 + 2449 + 184 + 2485 + 223 + + + + + 红嘴鸥 + + 1 + 1 + 2229 + 122 + 2268 + 165 + + + + + 红嘴鸥 + + 1 + 1 + 186 + 2 + 225 + 32 + + + + + 红嘴鸥 + + 1 + 1 + 3639 + 179 + 3660 + 217 + + + + + 红嘴鸥 + + 1 + 1 + 1426 + 77 + 1454 + 129 + + + + + 红嘴鸥 + + 1 + 1 + 1914 + 101 + 1943 + 138 + + + + + 红嘴鸥 + + 1 + 1 + 1758 + 93 + 1796 + 128 + + + + + 红嘴鸥 + + 1 + 1 + 1389 + 1846 + 1508 + 1930 + + + + + 苍鹭 + + 1 + 1 + 3522 + 1313 + 3583 + 1469 + + + + + 苍鹭 + + 1 + 1 + 1412 + 1307 + 1482 + 1456 + + + + + 苍鹭 + + 1 + 1 + 603 + 1264 + 672 + 1461 + + + + + 红嘴鸥 + + 1 + 1 + 3592 + 1838 + 3650 + 1939 + + + + + 红嘴鸥 + + 1 + 1 + 202 + 1854 + 288 + 1940 + + + + + 红嘴鸥 + + 1 + 1 + 2406 + 1841 + 2489 + 1935 + + + + + 红嘴鸥 + + 1 + 1 + 998 + 1845 + 1056 + 1935 + + + + + 红嘴鸥 + + 1 + 1 + 761 + 1848 + 828 + 1935 + + + + + 红嘴鸥 + + 1 + 1 + 2962 + 1862 + 3031 + 1942 + + + + + 苍鹭 + + 1 + 1 + 2473 + 1301 + 2535 + 1456 + + + + + 红嘴鸥 + + 1 + 1 + 2003 + 1395 + 2045 + 1457 + + + + + 苍鹭 + + 1 + 1 + 2871 + 1304 + 2932 + 1459 + + + + + 苍鹭 + + 1 + 1 + 3221 + 1391 + 3266 + 1461 + + + + + 红嘴鸥 + + 1 + 1 + 1905 + 1386 + 1943 + 1459 + + + + + 红嘴鸥 + + 1 + 1 + 2677 + 1397 + 2737 + 1455 + + + + + 红嘴鸥 + + 1 + 1 + 2274 + 1389 + 2311 + 1456 + + + + + 红嘴鸥 + + 1 + 1 + 1107 + 1377 + 1147 + 1453 + + + + + 红嘴鸥 + + 1 + 1 + 2112 + 1392 + 2148 + 1456 + + + + + 鸟 + + 1 + 1 + 919 + 1402 + 966 + 1454 + + + + + 红嘴鸥 + + 1 + 1 + 272 + 1387 + 311 + 1455 + + + + + 红嘴鸥 + + 1 + 1 + 1720 + 1410 + 1766 + 1459 + + + + + 白鹭 + + 1 + 1 + 700 + 1542 + 766 + 1638 + + + + + 苍鹭 + + 1 + 1 + 3723 + 1001 + 3816 + 1131 + + + + + 红嘴鸥 + + 1 + 1 + 1414 + 1178 + 1484 + 1243 + + + + + 红嘴鸥 + + 1 + 1 + 1890 + 1159 + 1968 + 1220 + + + + + 红嘴鸥 + + 1 + 1 + 2739 + 1125 + 2806 + 1176 + + + + + 红嘴鸥 + + 1 + 1 + 1302 + 1191 + 1368 + 1244 + + + + + 红嘴鸥 + + 1 + 1 + 2526 + 1129 + 2592 + 1190 + + + + + 红嘴鸥 + + 1 + 1 + 1488 + 1183 + 1566 + 1234 + + + + + 红嘴鸥 + + 1 + 1 + 2843 + 1110 + 2928 + 1173 + + + + + 红嘴鸥 + + 1 + 1 + 2941 + 1097 + 3020 + 1169 + + + + + 红嘴鸥 + + 1 + 1 + 2071 + 1160 + 2143 + 1215 + + + + + 红嘴鸥 + + 1 + 1 + 1709 + 1175 + 1779 + 1228 + + + + + 红嘴鸥 + + 1 + 1 + 2273 + 1147 + 2336 + 1200 + + + + + 红嘴鸥 + + 1 + 1 + 2598 + 1129 + 2654 + 1183 + + + + + 红嘴鸥 + + 1 + 1 + 3319 + 1095 + 3384 + 1150 + + + + + 红嘴鸥 + + 1 + 1 + 1603 + 1183 + 1644 + 1231 + + + + + 红嘴鸥 + + 1 + 1 + 1800 + 1165 + 1871 + 1225 + + + + + 红嘴鸥 + + 1 + 1 + 3418 + 1082 + 3496 + 1145 + + + + + 红嘴鸥 + + 1 + 1 + 2176 + 1147 + 2260 + 1204 + + + + + 红嘴鸥 + + 1 + 1 + 2356 + 1132 + 2422 + 1197 + + + + + 红嘴鸥 + + 1 + 1 + 1969 + 1163 + 2054 + 1216 + + + + + 红嘴鸥 + + 1 + 1 + 1206 + 1195 + 1270 + 1251 + + + + + 红嘴鸥 + + 1 + 1 + 863 + 1213 + 923 + 1268 + + + + + 红嘴鸥 + + 1 + 1 + 940 + 1214 + 1010 + 1260 + + + + + 红嘴鸥 + + 1 + 1 + 321 + 1240 + 391 + 1290 + + + + + 红嘴鸥 + + 1 + 1 + 742 + 1216 + 810 + 1272 + + + + + 红嘴鸥 + + 1 + 1 + 1137 + 1199 + 1205 + 1250 + + + + + 红嘴鸥 + + 1 + 1 + 2440 + 1139 + 2504 + 1194 + + + + + 红嘴鸥 + + 1 + 1 + 543 + 1226 + 612 + 1283 + + + + + 红嘴鸥 + + 1 + 1 + 199 + 1249 + 261 + 1293 + + + + + 红嘴鸥 + + 1 + 1 + 3198 + 1086 + 3271 + 1155 + + + + + 红嘴鸥 + + 1 + 1 + 1031 + 1203 + 1099 + 1254 + + + + + 鸟 + + 1 + 1 + 3052 + 1115 + 3114 + 1165 + + + + + 鸟 + + 1 + 1 + 288 + 1335 + 400 + 1428 + + + + + 红嘴鸥 + + 1 + 1 + 2843 + 1455 + 2942 + 1541 + + + + + 红嘴鸥 + + 1 + 1 + 3203 + 1442 + 3281 + 1529 + + + + + 红嘴鸥 + + 1 + 1 + 2477 + 1473 + 2563 + 1555 + + + + + 红嘴鸥 + + 1 + 1 + 3344 + 1450 + 3461 + 1525 + + + + + 红嘴鸥 + + 1 + 1 + 3523 + 1437 + 3613 + 1517 + + + + + 红嘴鸥 + + 1 + 1 + 3029 + 1440 + 3088 + 1535 + + + + + 红嘴鸥 + + 1 + 1 + 3783 + 1423 + 3840 + 1510 + + + + + 苍鹭 + + 1 + 1 + 687 + 1440 + 773 + 1630 + + + + + 红嘴鸥 + + 1 + 1 + 3649 + 1444 + 3749 + 1514 + + + + + 红嘴鸥 + + 1 + 1 + 231 + 1565 + 319 + 1643 + + + + + 红嘴鸥 + + 1 + 1 + 1921 + 1497 + 2025 + 1573 + + + + + 红嘴鸥 + + 1 + 1 + 1670 + 1513 + 1775 + 1586 + + + + + 红嘴鸥 + + 1 + 1 + 376 + 1550 + 456 + 1637 + + + + + 红嘴鸥 + + 1 + 1 + 1307 + 1527 + 1390 + 1597 + + + + + 红嘴鸥 + + 1 + 1 + 2199 + 1488 + 2283 + 1561 + + + + + 红嘴鸥 + + 1 + 1 + 2616 + 1464 + 2682 + 1547 + + + + + 红嘴鸥 + + 1 + 1 + 1145 + 1534 + 1209 + 1603 + + + + + 鸟 + + 1 + 1 + 1864 + 108 + 2170 + 200 + + + + + 红嘴鸥 + + 1 + 1 + 2387 + 212 + 2501 + 273 + + + + + 红嘴鸥 + + 1 + 1 + 2649 + 191 + 2758 + 243 + + + + + 红嘴鸥 + + 1 + 1 + 3057 + 213 + 3123 + 255 + + + + + 红嘴鸥 + + 1 + 1 + 2777 + 1900 + 2856 + 1986 + + + + + 苍鹭 + + 1 + 1 + 1061 + 1891 + 1126 + 1974 + + + + + 红嘴鸥 + + 1 + 1 + 922 + 1495 + 968 + 1561 + + + + + 红嘴鸥 + + 1 + 1 + 3191 + 1917 + 3257 + 1990 + + + + + 红嘴鸥 + + 1 + 1 + 2427 + 1911 + 2511 + 1979 + + + + + 红嘴鸥 + + 1 + 1 + 1073 + 1496 + 1110 + 1557 + + + + + 鸟 + + 1 + 1 + 34 + 1492 + 119 + 1550 + + + + + 红嘴鸥 + + 1 + 1 + 2087 + 1890 + 2135 + 1971 + + + + + 红嘴鸥 + + 1 + 1 + 1973 + 1500 + 2012 + 1570 + + + + + 红嘴鸥 + + 1 + 1 + 1760 + 1895 + 1806 + 1970 + + + + + 鸟 + + 1 + 1 + 858 + 1487 + 904 + 1559 + + + + + 红嘴鸥 + + 1 + 1 + 1141 + 1497 + 1182 + 1559 + + + + + 红嘴鸥 + + 1 + 1 + 24 + 1902 + 101 + 1970 + + + + + 红嘴鸥 + + 1 + 1 + 1233 + 1503 + 1284 + 1557 + + + + + 鸟 + + 1 + 1 + 1630 + 1517 + 1672 + 1568 + + + + + 红嘴鸥 + + 1 + 1 + 3422 + 1761 + 3517 + 1818 + + + + + 红嘴鸥 + + 1 + 1 + 3154 + 1555 + 3195 + 1614 + + + + + 红嘴鸥 + + 1 + 1 + 2640 + 1523 + 2676 + 1583 + + + + + 红嘴鸥 + + 1 + 1 + 1471 + 1489 + 1536 + 1560 + + + + + 红嘴鸥 + + 1 + 1 + 771 + 1491 + 825 + 1558 + + + + + 鸟 + + 1 + 1 + 3274 + 1540 + 3323 + 1605 + + + + + 鸟 + + 1 + 1 + 676 + 1498 + 767 + 1555 + + + + + 红嘴鸥 + + 1 + 1 + 3756 + 1906 + 3839 + 1983 + + + + + 红嘴鸥 + + 1 + 1 + 1927 + 1161 + 1956 + 1193 + + + + + 红嘴鸥 + + 1 + 1 + 540 + 1495 + 611 + 1541 + + + + + 红嘴鸥 + + 1 + 1 + 1801 + 1154 + 1834 + 1183 + + + + + 红嘴鸥 + + 1 + 1 + 3187 + 1190 + 3215 + 1221 + + + + + 红嘴鸥 + + 1 + 1 + 2919 + 1176 + 2943 + 1214 + + + + + 红嘴鸥 + + 1 + 1 + 1377 + 1505 + 1411 + 1558 + + + + + 红嘴鸥 + + 1 + 1 + 3008 + 1126 + 3045 + 1150 + + + + + 红嘴鸥 + + 1 + 1 + 2342 + 1102 + 2363 + 1139 + + + + + 红嘴鸥 + + 1 + 1 + 236 + 1063 + 275 + 1090 + + + + + 鸟 + + 1 + 1 + 410 + 1473 + 465 + 1548 + + + + + 红嘴鸥 + + 1 + 1 + 1092 + 1132 + 1125 + 1169 + + + + + 红嘴鸥 + + 1 + 1 + 2103 + 1106 + 2125 + 1131 + + + + + 红嘴鸥 + + 1 + 1 + 180 + 1061 + 208 + 1092 + + + + + 鸟 + + 1 + 1 + 2244 + 1512 + 2281 + 1569 + + + + + 红嘴鸥 + + 1 + 1 + 113 + 1115 + 158 + 1143 + + + + + 红嘴鸥 + + 1 + 1 + 2876 + 1122 + 2908 + 1144 + + + + + 红嘴鸥 + + 1 + 1 + 3527 + 1191 + 3553 + 1230 + + + + + 红嘴鸥 + + 1 + 1 + 3513 + 1544 + 3549 + 1612 + + + + + 红嘴鸥 + + 1 + 1 + 1868 + 1163 + 1901 + 1187 + + + + + 红嘴鸥 + + 1 + 1 + 3460 + 1202 + 3493 + 1226 + + + + + 鸟 + + 1 + 1 + 992 + 1510 + 1044 + 1558 + + + + + 红嘴鸥 + + 1 + 1 + 2991 + 1188 + 3016 + 1216 + + + + + 红嘴鸥 + + 1 + 1 + 3242 + 1123 + 3266 + 1153 + + + + + 红嘴鸥 + + 1 + 1 + 855 + 1132 + 887 + 1166 + + + + + 红嘴鸥 + + 1 + 1 + 1733 + 1155 + 1756 + 1182 + + + + + 红嘴鸥 + + 1 + 1 + 2192 + 1103 + 2220 + 1131 + + + + + 红嘴鸥 + + 1 + 1 + 1974 + 1098 + 1996 + 1125 + + + + + 红嘴鸥 + + 1 + 1 + 2718 + 1106 + 2742 + 1142 + + + + + 红嘴鸥 + + 1 + 1 + 2506 + 1111 + 2534 + 1137 + + + + + 红嘴鸥 + + 1 + 1 + 3266 + 1191 + 3291 + 1227 + + + + + 红嘴鸥 + + 1 + 1 + 2429 + 1104 + 2452 + 1133 + + + + + 鸟 + + 1 + 1 + 839 + 1080 + 871 + 1109 + + + + + 红嘴鸥 + + 1 + 1 + 2095 + 1160 + 2122 + 1194 + + + + + 红嘴鸥 + + 1 + 1 + 1836 + 1517 + 1867 + 1574 + + + + + 鸟 + + 1 + 1 + 1245 + 1079 + 1278 + 1113 + + + + + 红嘴鸥 + + 1 + 1 + 2783 + 1538 + 2821 + 1589 + + + + + 红嘴鸥 + + 1 + 1 + 1535 + 1145 + 1569 + 1178 + + + + + 鸟 + + 1 + 1 + 201 + 1495 + 255 + 1544 + + + + + 红嘴鸥 + + 1 + 1 + 2832 + 1182 + 2858 + 1211 + + + + + 红嘴鸥 + + 1 + 1 + 1015 + 1133 + 1039 + 1165 + + + + + 红嘴鸥 + + 1 + 1 + 3690 + 1199 + 3715 + 1233 + + + + + 红嘴鸥 + + 1 + 1 + 2761 + 1177 + 2787 + 1209 + + + + + 红嘴鸥 + + 1 + 1 + 2316 + 1163 + 2339 + 1198 + + + + + 红嘴鸥 + + 1 + 1 + 1650 + 1152 + 1675 + 1181 + + + + + 鸟 + + 1 + 1 + 3649 + 1570 + 3692 + 1614 + + + + + 红嘴鸥 + + 1 + 1 + 915 + 1067 + 961 + 1103 + + + + + 红嘴鸥 + + 1 + 1 + 679 + 1074 + 706 + 1100 + + + + + 鸟 + + 1 + 1 + 3394 + 1190 + 3418 + 1231 + + + + + 红嘴鸥 + + 1 + 1 + 3092 + 1187 + 3130 + 1216 + + + + + 红嘴鸥 + + 1 + 1 + 1351 + 1092 + 1376 + 1121 + + + + + 红嘴鸥 + + 1 + 1 + 2700 + 1169 + 2724 + 1203 + + + + + 红嘴鸥 + + 1 + 1 + 2576 + 1111 + 2598 + 1138 + + + + + 红嘴鸥 + + 1 + 1 + 1509 + 1084 + 1528 + 1115 + + + + + 红嘴鸥 + + 1 + 1 + 1289 + 1143 + 1328 + 1172 + + + + + 红嘴鸥 + + 1 + 1 + 2216 + 1159 + 2238 + 1195 + + + + + 红嘴鸥 + + 1 + 1 + 2293 + 1100 + 2313 + 1134 + + + + + 红嘴鸥 + + 1 + 1 + 1833 + 1098 + 1862 + 1122 + + + + + 红嘴鸥 + + 1 + 1 + 760 + 1068 + 792 + 1103 + + + + + 红嘴鸥 + + 1 + 1 + 3611 + 1205 + 3645 + 1234 + + + + + 红嘴鸥 + + 1 + 1 + 2489 + 1165 + 2516 + 1200 + + + + + 红嘴鸥 + + 1 + 1 + 1418 + 1086 + 1451 + 1113 + + + + + 红嘴鸥 + + 1 + 1 + 383 + 1065 + 416 + 1091 + + + + + 红嘴鸥 + + 1 + 1 + 1697 + 1087 + 1721 + 1119 + + + + + 红嘴鸥 + + 1 + 1 + 2615 + 1175 + 2641 + 1200 + + + + + 红嘴鸥 + + 1 + 1 + 1612 + 1091 + 1637 + 1119 + + + + + 红嘴鸥 + + 1 + 1 + 437 + 1070 + 465 + 1094 + + + + + 红嘴鸥 + + 1 + 1 + 1138 + 1080 + 1167 + 1108 + + + + + 红嘴鸥 + + 1 + 1 + 2390 + 1162 + 2410 + 1199 + + + + + 红嘴鸥 + + 1 + 1 + 1912 + 1099 + 1931 + 1121 + + + + + 红嘴鸥 + + 1 + 1 + 3577 + 1121 + 3602 + 1159 + + + + + 红嘴鸥 + + 1 + 1 + 1218 + 1077 + 1239 + 1101 + + + + + 红嘴鸥 + + 1 + 1 + 3318 + 1125 + 3339 + 1151 + + + + + 红嘴鸥 + + 1 + 1 + 2 + 1062 + 30 + 1088 + + + + + 红嘴鸥 + + 1 + 1 + 3745 + 1208 + 3773 + 1238 + + + + + 白鹭 + + 1 + 1 + 3130 + 1117 + 3149 + 1152 + + + + + 鸟 + + 1 + 1 + 1377 + 1073 + 1399 + 1102 + + + + + 红嘴鸥 + + 1 + 1 + 1656 + 1071 + 1674 + 1100 + + + + + 红嘴鸥 + + 1 + 1 + 3390 + 1131 + 3411 + 1156 + + + + + 红嘴鸥 + + 1 + 1 + 303 + 1069 + 329 + 1095 + + + + + 红嘴鸥 + + 1 + 1 + 3444 + 1134 + 3467 + 1156 + + + + + 红嘴鸥 + + 1 + 1 + 3660 + 1138 + 3681 + 1160 + + + + + 红嘴鸥 + + 1 + 1 + 2440 + 1529 + 2473 + 1570 + + + + + 红嘴鸥 + + 1 + 1 + 3495 + 1133 + 3515 + 1158 + + + + + 鸟 + + 1 + 1 + 1536 + 1825 + 1607 + 1892 + + + + + 红嘴鸥 + + 1 + 1 + 2421 + 1773 + 2524 + 1856 + + + + + 红嘴鸥 + + 1 + 1 + 3527 + 1755 + 3630 + 1828 + + + + + 红嘴鸥 + + 1 + 1 + 3151 + 1765 + 3258 + 1835 + + + + + 红嘴鸥 + + 1 + 1 + 3741 + 1724 + 3812 + 1820 + + + + + 红嘴鸥 + + 1 + 1 + 2986 + 1758 + 3056 + 1839 + + + + + 红嘴鸥 + + 1 + 1 + 2228 + 1784 + 2311 + 1862 + + + + + 红嘴鸥 + + 1 + 1 + 3365 + 1751 + 3468 + 1828 + + + + + 红嘴鸥 + + 1 + 1 + 2554 + 1771 + 2634 + 1846 + + + + + 鸟 + + 1 + 1 + 250 + 1681 + 373 + 1809 + + + + + 红嘴鸥 + + 1 + 1 + 3388 + 363 + 3526 + 458 + + + + + 红嘴鸥 + + 1 + 1 + 2863 + 1781 + 2942 + 1840 + + + + + 红嘴鸥 + + 1 + 1 + 1167 + 1816 + 1277 + 1904 + + + + + 红嘴鸥 + + 1 + 1 + 2090 + 1802 + 2202 + 1868 + + + + + 红嘴鸥 + + 1 + 1 + 2704 + 1789 + 2781 + 1850 + + + + + 红嘴鸥 + + 1 + 1 + 2829 + 63 + 2889 + 164 + + + + + 红嘴鸥 + + 1 + 1 + 3469 + 54 + 3537 + 149 + + + + + 红嘴鸥 + + 1 + 1 + 1898 + 95 + 1971 + 186 + + + + + 红嘴鸥 + + 1 + 1 + 3718 + 66 + 3821 + 146 + + + + + 鸟 + + 1 + 1 + 2401 + 75 + 2463 + 174 + + + + + 红嘴鸥 + + 1 + 1 + 2021 + 96 + 2087 + 180 + + + + + 鸟 + + 1 + 1 + 2215 + 89 + 2299 + 178 + + + + + 红嘴鸥 + + 1 + 1 + 3185 + 72 + 3249 + 160 + + + + + 鸟 + + 1 + 1 + 1339 + 98 + 1407 + 188 + + + + + 鸟 + + 1 + 1 + 1565 + 115 + 1629 + 197 + + + + + 鸟 + + 1 + 1 + 568 + 104 + 668 + 199 + + + + + 红嘴鸥 + + 1 + 1 + 959 + 82 + 1028 + 201 + + + + + 红嘴鸥 + + 1 + 1 + 74 + 124 + 140 + 201 + + + + + 苍鹭 + + 1 + 1 + 1632 + 1299 + 1682 + 1422 + + + + + 红嘴鸥 + + 1 + 1 + 3775 + 1260 + 3840 + 1342 + + + + + 红嘴鸥 + + 1 + 1 + 2783 + 1286 + 2878 + 1382 + + + + + 红嘴鸥 + + 1 + 1 + 1598 + 1339 + 1672 + 1418 + + + + + 红嘴鸥 + + 1 + 1 + 762 + 1371 + 846 + 1446 + + + + + 红嘴鸥 + + 1 + 1 + 1442 + 1349 + 1530 + 1421 + + + + + 红嘴鸥 + + 1 + 1 + 2077 + 1333 + 2180 + 1406 + + + + + 红嘴鸥 + + 1 + 1 + 101 + 1406 + 205 + 1474 + + + + + 红嘴鸥 + + 1 + 1 + 1719 + 1339 + 1773 + 1418 + + + + + 红嘴鸥 + + 1 + 1 + 2533 + 1311 + 2638 + 1379 + + + + + 红嘴鸥 + + 1 + 1 + 3477 + 1281 + 3557 + 1349 + + + + + 红嘴鸥 + + 1 + 1 + 576 + 1382 + 644 + 1445 + + + + + 红嘴鸥 + + 1 + 1 + 1002 + 1355 + 1057 + 1434 + + + + + 红嘴鸥 + + 1 + 1 + 1875 + 1334 + 1933 + 1415 + + + + + 红嘴鸥 + + 1 + 1 + 3224 + 1276 + 3277 + 1343 + + + + + 红嘴鸥 + + 1 + 1 + 258 + 1389 + 350 + 1459 + + + + + 红嘴鸥 + + 1 + 1 + 391 + 1399 + 447 + 1456 + + + + + 红嘴鸥 + + 1 + 1 + 1242 + 1354 + 1297 + 1423 + + + + + 红嘴鸥 + + 1 + 1 + 2326 + 1329 + 2407 + 1400 + + + + + 红嘴鸥 + + 1 + 1 + 2991 + 1300 + 3055 + 1358 + + + + + 鸟 + + 1 + 1 + 3180 + 1184 + 3353 + 1357 + + + + + 红嘴鸥 + + 1 + 1 + 836 + 2087 + 901 + 2138 + + + + + 红嘴鸥 + + 1 + 1 + 597 + 2087 + 628 + 2134 + + + + + 红嘴鸥 + + 1 + 1 + 254 + 2081 + 306 + 2126 + + + + + 红嘴鸥 + + 1 + 1 + 98 + 2087 + 128 + 2131 + + + + + 白鹭 + + 1 + 1 + 2130 + 2093 + 2183 + 2160 + + + + + 红嘴鸥 + + 1 + 1 + 767 + 2092 + 796 + 2133 + + + + + 红嘴鸥 + + 1 + 1 + 927 + 2092 + 954 + 2136 + + + + + 红嘴鸥 + + 1 + 1 + 216 + 2087 + 248 + 2124 + + + + + 红嘴鸥 + + 1 + 1 + 355 + 2076 + 424 + 2131 + + + + + 红嘴鸥 + + 1 + 1 + 1020 + 2097 + 1059 + 2138 + + + + + 红嘴鸥 + + 1 + 1 + 1142 + 2097 + 1170 + 2146 + + + + + 红嘴鸥 + + 1 + 1 + 708 + 2090 + 743 + 2131 + + + + + 红嘴鸥 + + 1 + 1 + 1217 + 2116 + 1293 + 2151 + + + + + 红嘴鸥 + + 1 + 1 + 530 + 2096 + 558 + 2129 + + + + + 红嘴鸥 + + 1 + 1 + 498 + 1967 + 529 + 2007 + + + + + 红嘴鸥 + + 1 + 1 + 110 + 1953 + 136 + 1982 + + + + + 红嘴鸥 + + 1 + 1 + 424 + 2076 + 484 + 2128 + + + + + 红嘴鸥 + + 1 + 1 + 49 + 2093 + 87 + 2129 + + + + + 红嘴鸥 + + 1 + 1 + 1707 + 1955 + 1740 + 1994 + + + + + 红嘴鸥 + + 1 + 1 + 1624 + 2119 + 1654 + 2151 + + + + + 红嘴鸥 + + 1 + 1 + 1481 + 2117 + 1517 + 2150 + + + + + 红嘴鸥 + + 1 + 1 + 200 + 1953 + 227 + 1989 + + + + + 红嘴鸥 + + 1 + 1 + 723 + 1972 + 753 + 2013 + + + + + 红嘴鸥 + + 1 + 1 + 1889 + 1942 + 1930 + 1976 + + + + + 红嘴鸥 + + 1 + 1 + 829 + 1976 + 862 + 2015 + + + + + 红嘴鸥 + + 1 + 1 + 1 + 1952 + 28 + 1994 + + + + + 红嘴鸥 + + 1 + 1 + 267 + 1963 + 297 + 1993 + + + + + 红嘴鸥 + + 1 + 1 + 2000 + 1942 + 2023 + 1972 + + + + + 红嘴鸥 + + 1 + 1 + 663 + 2089 + 690 + 2132 + + + + + 红嘴鸥 + + 1 + 1 + 1332 + 2110 + 1365 + 2147 + + + + + 红嘴鸥 + + 1 + 1 + 614 + 1965 + 643 + 2009 + + + + + 红嘴鸥 + + 1 + 1 + 949 + 1989 + 981 + 2021 + + + + + 红嘴鸥 + + 1 + 1 + 2719 + 1976 + 2756 + 2012 + + + + + 红嘴鸥 + + 1 + 1 + 1292 + 1997 + 1327 + 2037 + + + + + 红嘴鸥 + + 1 + 1 + 1557 + 2007 + 1583 + 2045 + + + + + 红嘴鸥 + + 1 + 1 + 726 + 1918 + 758 + 1954 + + + + + 红嘴鸥 + + 1 + 1 + 1064 + 1989 + 1095 + 2021 + + + + + 红嘴鸥 + + 1 + 1 + 2021 + 2037 + 2041 + 2060 + + + + + 红嘴鸥 + + 1 + 1 + 2464 + 2043 + 2498 + 2086 + + + + + 红嘴鸥 + + 1 + 1 + 1391 + 2113 + 1422 + 2144 + + + + + 红嘴鸥 + + 1 + 1 + 1738 + 2015 + 1762 + 2055 + + + + + 鸟 + + 1 + 1 + 613 + 1877 + 648 + 1911 + + + + + 红嘴鸥 + + 1 + 1 + 1352 + 1932 + 1381 + 1982 + + + + + 红嘴鸥 + + 1 + 1 + 2375 + 2047 + 2411 + 2082 + + + + + 红嘴鸥 + + 1 + 1 + 2190 + 2138 + 2222 + 2160 + + + + + 红嘴鸥 + + 1 + 1 + 2930 + 2081 + 2954 + 2112 + + + + + 红嘴鸥 + + 1 + 1 + 497 + 1859 + 521 + 1904 + + + + + 红嘴鸥 + + 1 + 1 + 380 + 1961 + 408 + 1996 + + + + + 红嘴鸥 + + 1 + 1 + 1794 + 1961 + 1813 + 1995 + + + + + 红嘴鸥 + + 1 + 1 + 64 + 1863 + 93 + 1889 + + + + + 红嘴鸥 + + 1 + 1 + 1639 + 2019 + 1665 + 2046 + + + + + 红嘴鸥 + + 1 + 1 + 231 + 1893 + 272 + 1923 + + + + + 红嘴鸥 + + 1 + 1 + 2578 + 1971 + 2604 + 2007 + + + + + 红嘴鸥 + + 1 + 1 + 2522 + 651 + 2613 + 747 + + + + + 红嘴鸥 + + 1 + 1 + 3360 + 628 + 3431 + 723 + + + + + 红嘴鸥 + + 1 + 1 + 2195 + 665 + 2280 + 757 + + + + + 红嘴鸥 + + 1 + 1 + 2712 + 662 + 2798 + 741 + + + + + 红嘴鸥 + + 1 + 1 + 23 + 702 + 78 + 812 + + + + + 红嘴鸥 + + 1 + 1 + 3166 + 643 + 3244 + 728 + + + + + 红嘴鸥 + + 1 + 1 + 2370 + 667 + 2427 + 753 + + + + + 红嘴鸥 + + 1 + 1 + 3783 + 627 + 3840 + 715 + + + + + 红嘴鸥 + + 1 + 1 + 1607 + 681 + 1739 + 763 + + + + + 红嘴鸥 + + 1 + 1 + 2007 + 684 + 2126 + 758 + + + + + 红嘴鸥 + + 1 + 1 + 1838 + 670 + 1953 + 765 + + + + + 苍鹭 + + 1 + 1 + 377 + 572 + 604 + 930 + + + + + 红嘴鸥 + + 1 + 1 + 1251 + 702 + 1317 + 782 + + + + + 苍鹭 + + 1 + 1 + 3585 + 624 + 3664 + 718 + + + + + 红嘴鸥 + + 1 + 1 + 1957 + 370 + 2084 + 470 + + + + + 红嘴鸥 + + 1 + 1 + 3541 + 652 + 3606 + 724 + + + + + 红嘴鸥 + + 1 + 1 + 1440 + 665 + 1507 + 773 + + + + + 红嘴鸥 + + 1 + 1 + 639 + 1040 + 849 + 1162 + + + + + 红嘴鸥 + + 1 + 1 + 2624 + 716 + 2819 + 830 + + + + + 红嘴鸥 + + 1 + 1 + 1444 + 1760 + 1502 + 1808 + + + + + 白鹭 + + 1 + 1 + 565 + 1758 + 619 + 1863 + + + + + 红嘴鸥 + + 1 + 1 + 1323 + 1756 + 1384 + 1820 + + + + + 红嘴鸥 + + 1 + 1 + 707 + 1800 + 764 + 1843 + + + + + 苍鹭 + + 1 + 1 + 793 + 277 + 939 + 505 + + + + + 红嘴鸥 + + 1 + 1 + 269 + 401 + 327 + 504 + + + + + 红嘴鸥 + + 1 + 1 + 2862 + 351 + 2926 + 448 + + + + + 红嘴鸥 + + 1 + 1 + 3628 + 329 + 3685 + 428 + + + + + 红嘴鸥 + + 1 + 1 + 1703 + 380 + 1768 + 476 + + + + + 红嘴鸥 + + 1 + 1 + 1971 + 382 + 2045 + 471 + + + + + 红嘴鸥 + + 1 + 1 + 2239 + 368 + 2296 + 463 + + + + + 红嘴鸥 + + 1 + 1 + 1280 + 399 + 1336 + 487 + + + + + 红嘴鸥 + + 1 + 1 + 3371 + 357 + 3433 + 435 + + + + + 鸟 + + 1 + 1 + 74 + 415 + 165 + 504 + + + + + 红嘴鸥 + + 1 + 1 + 1550 + 389 + 1607 + 481 + + + + + 苍鹭 + + 1 + 1 + 2549 + 379 + 2618 + 457 + + + + + 红嘴鸥 + + 1 + 1 + 3044 + 360 + 3115 + 446 + + + + + 红嘴鸥 + + 1 + 1 + 0 + 435 + 30 + 519 + + + + + 鸟 + + 1 + 1 + 270 + 1654 + 366 + 1749 + + + + + 鸟 + + 1 + 1 + 674 + 1702 + 756 + 1778 + + + + + 鸟 + + 1 + 1 + 419 + 1672 + 482 + 1755 + + + + + 苍鹭 + + 1 + 1 + 1262 + 1278 + 1318 + 1443 + + + + + 苍鹭 + + 1 + 1 + 2437 + 1291 + 2486 + 1444 + + + + + 苍鹭 + + 1 + 1 + 3460 + 1313 + 3522 + 1457 + + + + + 苍鹭 + + 1 + 1 + 1728 + 1303 + 1798 + 1443 + + + + + 苍鹭 + + 1 + 1 + 2912 + 1288 + 2964 + 1447 + + + + + 红嘴鸥 + + 1 + 1 + 1255 + 1804 + 1310 + 1902 + + + + + 红嘴鸥 + + 1 + 1 + 20 + 1815 + 158 + 1905 + + + + + 红嘴鸥 + + 1 + 1 + 878 + 1802 + 933 + 1904 + + + + + 红嘴鸥 + + 1 + 1 + 3039 + 1823 + 3096 + 1908 + + + + + 红嘴鸥 + + 1 + 1 + 3397 + 1821 + 3454 + 1913 + + + + + 鸟 + + 1 + 1 + 1556 + 1821 + 1656 + 1902 + + + + + 苍鹭 + + 1 + 1 + 250 + 1302 + 310 + 1437 + + + + + 鸟 + + 1 + 1 + 2885 + 1661 + 3055 + 1826 + + + + + 苍鹭 + + 1 + 1 + 870 + 1061 + 921 + 1180 + + + + + 苍鹭 + + 1 + 1 + 826 + 1302 + 879 + 1437 + + + + + 鸟 + + 1 + 1 + 2759 + 1816 + 2845 + 1904 + + + + + 红嘴鸥 + + 1 + 1 + 1049 + 1832 + 1106 + 1906 + + + + + 红嘴鸥 + + 1 + 1 + 3614 + 1833 + 3664 + 1915 + + + + + 红嘴鸥 + + 1 + 1 + 2492 + 1817 + 2573 + 1903 + + + + + 红嘴鸥 + + 1 + 1 + 1407 + 1827 + 1464 + 1903 + + + + + 红嘴鸥 + + 1 + 1 + 539 + 1366 + 579 + 1433 + + + + + 红嘴鸥 + + 1 + 1 + 1903 + 1049 + 1994 + 1089 + + + + + 鸟 + + 1 + 1 + 2308 + 1826 + 2372 + 1901 + + + + + 红嘴鸥 + + 1 + 1 + 1795 + 1803 + 1854 + 1902 + + + + + 鸟 + + 1 + 1 + 1 + 1364 + 64 + 1428 + + + + + 鸟 + + 1 + 1 + 2114 + 1831 + 2181 + 1903 + + + + + 红嘴鸥 + + 1 + 1 + 3567 + 865 + 3590 + 894 + + + + + 红嘴鸥 + + 1 + 1 + 3485 + 869 + 3510 + 896 + + + + + 红嘴鸥 + + 1 + 1 + 3356 + 436 + 3445 + 529 + + + + + 红嘴鸥 + + 1 + 1 + 2327 + 459 + 2405 + 554 + + + + + 红嘴鸥 + + 1 + 1 + 2666 + 444 + 2720 + 541 + + + + + 红嘴鸥 + + 1 + 1 + 1478 + 476 + 1528 + 567 + + + + + 红嘴鸥 + + 1 + 1 + 1020 + 490 + 1105 + 581 + + + + + 苍鹭 + + 1 + 1 + 3765 + 428 + 3838 + 523 + + + + + 红嘴鸥 + + 1 + 1 + 1210 + 489 + 1282 + 577 + + + + + 红嘴鸥 + + 1 + 1 + 570 + 498 + 630 + 587 + + + + + 红嘴鸥 + + 1 + 1 + 3550 + 442 + 3608 + 525 + + + + + 红嘴鸥 + + 1 + 1 + 294 + 510 + 370 + 591 + + + + + 红嘴鸥 + + 1 + 1 + 1741 + 480 + 1794 + 565 + + + + + 红嘴鸥 + + 1 + 1 + 1974 + 479 + 2042 + 562 + + + + + 红嘴鸥 + + 1 + 1 + 78 + 514 + 149 + 590 + + + + + 红嘴鸥 + + 1 + 1 + 2485 + 476 + 2548 + 551 + + + + + 红嘴鸥 + + 1 + 1 + 2894 + 460 + 2954 + 532 + + + + + 红嘴鸥 + + 1 + 1 + 3162 + 461 + 3223 + 532 + + + + + 红嘴鸥 + + 1 + 1 + 703 + 1825 + 790 + 1909 + + + + + 红嘴鸥 + + 1 + 1 + 1157 + 1842 + 1235 + 1910 + + + + + 红嘴鸥 + + 1 + 1 + 3511 + 1862 + 3594 + 1939 + + + + + 鸟 + + 1 + 1 + 998 + 1833 + 1067 + 1912 + + + + + 红嘴鸥 + + 1 + 1 + 1375 + 1842 + 1432 + 1910 + + + + + 红嘴鸥 + + 1 + 1 + 1521 + 1827 + 1585 + 1911 + + + + + 红嘴鸥 + + 1 + 1 + 457 + 1822 + 536 + 1909 + + + + + 红嘴鸥 + + 1 + 1 + 3349 + 1865 + 3392 + 1936 + + + + + 鸟 + + 1 + 1 + 98 + 1595 + 336 + 1709 + + + + + 红嘴鸥 + + 1 + 1 + 3127 + 1863 + 3190 + 1927 + + + + + 红嘴鸥 + + 1 + 1 + 2050 + 1835 + 2125 + 1910 + + + + + 红嘴鸥 + + 1 + 1 + 2807 + 1858 + 2879 + 1925 + + + + + 红嘴鸥 + + 1 + 1 + 2571 + 1846 + 2649 + 1920 + + + + + 红嘴鸥 + + 1 + 1 + 2348 + 1836 + 2395 + 1916 + + + + + 红嘴鸥 + + 1 + 1 + 1819 + 1830 + 1905 + 1911 + + + + + 红嘴鸥 + + 1 + 1 + 225 + 1837 + 311 + 1908 + + + + + 鸟 + + 1 + 1 + 713 + 1496 + 769 + 1564 + + + + + 红嘴鸥 + + 1 + 1 + 2942 + 1134 + 2980 + 1160 + + + + + 红嘴鸥 + + 1 + 1 + 2370 + 1195 + 2413 + 1226 + + + + + 红嘴鸥 + + 1 + 1 + 1184 + 1161 + 1225 + 1190 + + + + + 红嘴鸥 + + 1 + 1 + 957 + 1527 + 1014 + 1569 + + + + + 鸟 + + 1 + 1 + 1087 + 1532 + 1131 + 1574 + + + + + 红嘴鸥 + + 1 + 1 + 1431 + 1537 + 1468 + 1583 + + + + + 红嘴鸥 + + 1 + 1 + 3617 + 1148 + 3646 + 1174 + + + + + 红嘴鸥 + + 1 + 1 + 18 + 1135 + 47 + 1159 + + + + + 红嘴鸥 + + 1 + 1 + 167 + 1137 + 190 + 1168 + + + + + 红嘴鸥 + + 1 + 1 + 222 + 1138 + 247 + 1167 + + + + + 红嘴鸥 + + 1 + 1 + 2608 + 1199 + 2630 + 1233 + + + + + 红嘴鸥 + + 1 + 1 + 3414 + 1145 + 3444 + 1171 + + + + + 鸟 + + 1 + 1 + 387 + 1499 + 448 + 1550 + + + + + 红嘴鸥 + + 1 + 1 + 2399 + 1121 + 2433 + 1145 + + + + + 红嘴鸥 + + 1 + 1 + 3466 + 1226 + 3494 + 1255 + + + + + 红嘴鸥 + + 1 + 1 + 1681 + 1526 + 1718 + 1594 + + + + + 红嘴鸥 + + 1 + 1 + 647 + 1147 + 685 + 1175 + + + + + 红嘴鸥 + + 1 + 1 + 3360 + 1227 + 3399 + 1261 + + + + + 红嘴鸥 + + 1 + 1 + 54 + 1063 + 82 + 1087 + + + + + 红嘴鸥 + + 1 + 1 + 1558 + 1532 + 1606 + 1595 + + + + + 红嘴鸥 + + 1 + 1 + 3244 + 1134 + 3274 + 1164 + + + + + 鸟 + + 1 + 1 + 3345 + 1140 + 3364 + 1168 + + + + + 红嘴鸥 + + 1 + 1 + 2724 + 1128 + 2750 + 1155 + + + + + 红嘴鸥 + + 1 + 1 + 2738 + 1206 + 2757 + 1232 + + + + + 红嘴鸥 + + 1 + 1 + 3086 + 1223 + 3118 + 1255 + + + + + 红嘴鸥 + + 1 + 1 + 452 + 1069 + 478 + 1098 + + + + + 红嘴鸥 + + 1 + 1 + 2288 + 1092 + 2325 + 1145 + + + + + 红嘴鸥 + + 1 + 1 + 37 + 1488 + 103 + 1544 + + + + + 红嘴鸥 + + 1 + 1 + 1390 + 1162 + 1418 + 1199 + + + + + 红嘴鸥 + + 1 + 1 + 2165 + 1168 + 2197 + 1221 + + + + + 鸟 + + 1 + 1 + 583 + 1493 + 634 + 1560 + + + + + 红嘴鸥 + + 1 + 1 + 589 + 1071 + 612 + 1107 + + + + + 红嘴鸥 + + 1 + 1 + 2531 + 1198 + 2555 + 1224 + + + + + 红嘴鸥 + + 1 + 1 + 344 + 1067 + 374 + 1093 + + + + + 红嘴鸥 + + 1 + 1 + 2018 + 1109 + 2055 + 1139 + + + + + 红嘴鸥 + + 1 + 1 + 97 + 1132 + 128 + 1162 + + + + + 红嘴鸥 + + 1 + 1 + 1280 + 1157 + 1306 + 1194 + + + + + 红嘴鸥 + + 1 + 1 + 1015 + 1090 + 1046 + 1112 + + + + + 红嘴鸥 + + 1 + 1 + 1239 + 1533 + 1283 + 1580 + + + + + 红嘴鸥 + + 1 + 1 + 2797 + 1130 + 2815 + 1160 + + + + + 红嘴鸥 + + 1 + 1 + 309 + 1143 + 337 + 1168 + + + + + 红嘴鸥 + + 1 + 1 + 856 + 1148 + 880 + 1182 + + + + + 红嘴鸥 + + 1 + 1 + 2672 + 1205 + 2697 + 1230 + + + + + 红嘴鸥 + + 1 + 1 + 2455 + 1191 + 2483 + 1227 + + + + + 红嘴鸥 + + 1 + 1 + 965 + 1147 + 990 + 1186 + + + + + 红嘴鸥 + + 1 + 1 + 3044 + 1135 + 3062 + 1163 + + + + + 红嘴鸥 + + 1 + 1 + 877 + 1085 + 904 + 1110 + + + + + 红嘴鸥 + + 1 + 1 + 1192 + 1085 + 1215 + 1121 + + + + + 红嘴鸥 + + 1 + 1 + 523 + 1073 + 547 + 1098 + + + + + 红嘴鸥 + + 1 + 1 + 771 + 1079 + 802 + 1106 + + + + + 红嘴鸥 + + 1 + 1 + 1576 + 1093 + 1615 + 1127 + + + + + 红嘴鸥 + + 1 + 1 + 723 + 1070 + 746 + 1104 + + + + + 红嘴鸥 + + 1 + 1 + 2853 + 1129 + 2868 + 1158 + + + + + 红嘴鸥 + + 1 + 1 + 411 + 1139 + 437 + 1170 + + + + + 红嘴鸥 + + 1 + 1 + 3182 + 1134 + 3203 + 1160 + + + + + 红嘴鸥 + + 1 + 1 + 3739 + 1239 + 3765 + 1267 + + + + + 红嘴鸥 + + 1 + 1 + 520 + 1145 + 549 + 1177 + + + + + 红嘴鸥 + + 1 + 1 + 1560 + 1168 + 1590 + 1204 + + + + + 红嘴鸥 + + 1 + 1 + 2106 + 1100 + 2136 + 1138 + + + + + 红嘴鸥 + + 1 + 1 + 3648 + 1227 + 3672 + 1262 + + + + + 红嘴鸥 + + 1 + 1 + 2216 + 1114 + 2245 + 1148 + + + + + 鸟 + + 1 + 1 + 1785 + 1164 + 1822 + 1211 + + + + + 红嘴鸥 + + 1 + 1 + 1408 + 1097 + 1433 + 1123 + + + + + 鸟 + + 1 + 1 + 1711 + 1088 + 1772 + 1129 + + + + + 红嘴鸥 + + 1 + 1 + 1077 + 1159 + 1100 + 1191 + + + + + 红嘴鸥 + + 1 + 1 + 3771 + 1153 + 3803 + 1180 + + + + + 红嘴鸥 + + 1 + 1 + 3546 + 1217 + 3573 + 1257 + + + + + 红嘴鸥 + + 1 + 1 + 656 + 1074 + 677 + 1101 + + + + + 红嘴鸥 + + 1 + 1 + 2805 + 1210 + 2824 + 1239 + + + + + 红嘴鸥 + + 1 + 1 + 2602 + 1121 + 2625 + 1149 + + + + + 鸟 + + 1 + 1 + 2070 + 1184 + 2105 + 1230 + + + + + 红嘴鸥 + + 1 + 1 + 1837 + 1100 + 1868 + 1131 + + + + + 红嘴鸥 + + 1 + 1 + 943 + 1087 + 964 + 1112 + + + + + 红嘴鸥 + + 1 + 1 + 1482 + 1166 + 1509 + 1202 + + + + + 红嘴鸥 + + 1 + 1 + 1958 + 1178 + 1988 + 1214 + + + + + 鸟 + + 1 + 1 + 1918 + 1099 + 1947 + 1139 + + + + + 红嘴鸥 + + 1 + 1 + 762 + 1149 + 786 + 1180 + + + + + 红嘴鸥 + + 1 + 1 + 1304 + 1092 + 1326 + 1121 + + + + + 红嘴鸥 + + 1 + 1 + 3016 + 1227 + 3041 + 1258 + + + + + 鸟 + + 1 + 1 + 2889 + 1209 + 2910 + 1240 + + + + + 红嘴鸥 + + 1 + 1 + 3522 + 1148 + 3548 + 1171 + + + + + 鸟 + + 1 + 1 + 3110 + 1143 + 3127 + 1165 + + + + + 红嘴鸥 + + 1 + 1 + 258 + 1064 + 282 + 1089 + + + + + 红嘴鸥 + + 1 + 1 + 3696 + 1146 + 3715 + 1176 + + + + + 红嘴鸥 + + 1 + 1 + 2913 + 2013 + 2996 + 2077 + + + + + 红嘴鸥 + + 1 + 1 + 2422 + 2002 + 2473 + 2064 + + + + + 苍鹭 + + 1 + 1 + 355 + 1917 + 486 + 2043 + + + + + 红嘴鸥 + + 1 + 1 + 2736 + 2004 + 2788 + 2069 + + + + + 红嘴鸥 + + 1 + 1 + 1872 + 1992 + 1922 + 2053 + + + + + 红嘴鸥 + + 1 + 1 + 3538 + 2021 + 3616 + 2091 + + + + + 红嘴鸥 + + 1 + 1 + 2571 + 2009 + 2632 + 2064 + + + + + 红嘴鸥 + + 1 + 1 + 562 + 1982 + 634 + 2038 + + + + + 红嘴鸥 + + 1 + 1 + 2355 + 1999 + 2406 + 2063 + + + + + 红嘴鸥 + + 1 + 1 + 76 + 1973 + 148 + 2036 + + + + + 红嘴鸥 + + 1 + 1 + 1111 + 1987 + 1183 + 2051 + + + + + 红嘴鸥 + + 1 + 1 + 642 + 1976 + 715 + 2040 + + + + + 红嘴鸥 + + 1 + 1 + 2829 + 2018 + 2899 + 2073 + + + + + 红嘴鸥 + + 1 + 1 + 183 + 1976 + 237 + 2037 + + + + + 红嘴鸥 + + 1 + 1 + 3641 + 2025 + 3679 + 2091 + + + + + 红嘴鸥 + + 1 + 1 + 1993 + 1997 + 2056 + 2055 + + + + + 红嘴鸥 + + 1 + 1 + 2054 + 2006 + 2132 + 2064 + + + + + 红嘴鸥 + + 1 + 1 + 229 + 1979 + 297 + 2037 + + + + + 红嘴鸥 + + 1 + 1 + 3164 + 2025 + 3199 + 2080 + + + + + 红嘴鸥 + + 1 + 1 + 3077 + 2030 + 3142 + 2078 + + + + + 红嘴鸥 + + 1 + 1 + 3423 + 2032 + 3484 + 2084 + + + + + 红嘴鸥 + + 1 + 1 + 1770 + 1983 + 1847 + 2051 + + + + + 红嘴鸥 + + 1 + 1 + 1600 + 1995 + 1663 + 2050 + + + + + 红嘴鸥 + + 1 + 1 + 876 + 1983 + 943 + 2045 + + + + + 红嘴鸥 + + 1 + 1 + 2648 + 2013 + 2714 + 2063 + + + + + 鸟 + + 1 + 1 + 1471 + 2004 + 1543 + 2055 + + + + + 红嘴鸥 + + 1 + 1 + 954 + 1987 + 1031 + 2047 + + + + + 红嘴鸥 + + 1 + 1 + 1211 + 1997 + 1283 + 2051 + + + + + 红嘴鸥 + + 1 + 1 + 1277 + 1992 + 1343 + 2049 + + + + + 红嘴鸥 + + 1 + 1 + 3362 + 2035 + 3432 + 2083 + + + + + 红嘴鸥 + + 1 + 1 + 815 + 1981 + 886 + 2046 + + + + + 红嘴鸥 + + 1 + 1 + 2282 + 2004 + 2356 + 2065 + + + + + 红嘴鸥 + + 1 + 1 + 3494 + 2021 + 3530 + 2084 + + + + + 红嘴鸥 + + 1 + 1 + 1394 + 2003 + 1454 + 2053 + + + + + 鸟 + + 1 + 1 + 2 + 1970 + 63 + 2036 + + + + + 红嘴鸥 + + 1 + 1 + 3263 + 2033 + 3312 + 2085 + + + + + 红嘴鸥 + + 1 + 1 + 3307 + 2021 + 3353 + 2088 + + + + + 红嘴鸥 + + 1 + 1 + 3714 + 2043 + 3789 + 2093 + + + + + 红嘴鸥 + + 1 + 1 + 3212 + 2037 + 3272 + 2082 + + + + + 红嘴鸥 + + 1 + 1 + 2523 + 2016 + 2562 + 2064 + + + + + 红嘴鸥 + + 1 + 1 + 730 + 2000 + 818 + 2044 + + + + + 红嘴鸥 + + 1 + 1 + 1660 + 2001 + 1728 + 2051 + + + + + 红嘴鸥 + + 1 + 1 + 3034 + 2034 + 3069 + 2074 + + + + + 红嘴鸥 + + 1 + 1 + 1024 + 1991 + 1074 + 2047 + + + + + 红嘴鸥 + + 1 + 1 + 2536 + 1698 + 2568 + 1722 + + + + + 红嘴鸥 + + 1 + 1 + 1338 + 2000 + 1404 + 2052 + + + + + 鸟 + + 1 + 1 + 1065 + 2000 + 1111 + 2048 + + + + + 红嘴鸥 + + 1 + 1 + 1094 + 1634 + 1135 + 1670 + + + + + 红嘴鸥 + + 1 + 1 + 3798 + 2045 + 3833 + 2095 + + + + + 红嘴鸥 + + 1 + 1 + 1723 + 1997 + 1787 + 2052 + + + + + 红嘴鸥 + + 1 + 1 + 2602 + 1695 + 2639 + 1728 + + + + + 红嘴鸥 + + 1 + 1 + 1404 + 1642 + 1430 + 1682 + + + + + 红嘴鸥 + + 1 + 1 + 3550 + 1738 + 3583 + 1770 + + + + + 红嘴鸥 + + 1 + 1 + 2082 + 1664 + 2107 + 1707 + + + + + 红嘴鸥 + + 1 + 1 + 97 + 1602 + 134 + 1635 + + + + + 红嘴鸥 + + 1 + 1 + 3200 + 1708 + 3230 + 1751 + + + + + 红嘴鸥 + + 1 + 1 + 3451 + 1728 + 3481 + 1760 + + + + + 红嘴鸥 + + 1 + 1 + 2292 + 1679 + 2318 + 1713 + + + + + 红嘴鸥 + + 1 + 1 + 1872 + 1665 + 1897 + 1698 + + + + + 红嘴鸥 + + 1 + 1 + 571 + 1615 + 597 + 1653 + + + + + 红嘴鸥 + + 1 + 1 + 1520 + 1654 + 1552 + 1688 + + + + + 红嘴鸥 + + 1 + 1 + 1790 + 1665 + 1819 + 1698 + + + + + 红嘴鸥 + + 1 + 1 + 2778 + 1699 + 2805 + 1736 + + + + + 红嘴鸥 + + 1 + 1 + 2892 + 1699 + 2921 + 1739 + + + + + 红嘴鸥 + + 1 + 1 + 3715 + 1736 + 3739 + 1769 + + + + + 红嘴鸥 + + 1 + 1 + 493 + 1618 + 525 + 1654 + + + + + 鸟 + + 1 + 1 + 2238 + 2004 + 2290 + 2062 + + + + + 红嘴鸥 + + 1 + 1 + 1196 + 1647 + 1241 + 1678 + + + + + 红嘴鸥 + + 1 + 1 + 1960 + 1669 + 1986 + 1702 + + + + + 红嘴鸥 + + 1 + 1 + 692 + 1622 + 724 + 1654 + + + + + 红嘴鸥 + + 1 + 1 + 1307 + 1640 + 1333 + 1681 + + + + + 红嘴鸥 + + 1 + 1 + 16 + 1593 + 48 + 1630 + + + + + 红嘴鸥 + + 1 + 1 + 3811 + 1629 + 3834 + 1661 + + + + + 红嘴鸥 + + 1 + 1 + 2713 + 1694 + 2736 + 1733 + + + + + 红嘴鸥 + + 1 + 1 + 3088 + 1713 + 3117 + 1749 + + + + + 红嘴鸥 + + 1 + 1 + 3625 + 1627 + 3646 + 1652 + + + + + 红嘴鸥 + + 1 + 1 + 619 + 1626 + 654 + 1649 + + + + + 红嘴鸥 + + 1 + 1 + 3568 + 1625 + 3593 + 1650 + + + + + 红嘴鸥 + + 1 + 1 + 218 + 1607 + 245 + 1640 + + + + + 红嘴鸥 + + 1 + 1 + 3515 + 1622 + 3537 + 1650 + + + + + 红嘴鸥 + + 1 + 1 + 3726 + 1631 + 3749 + 1655 + + + + + 红嘴鸥 + + 1 + 1 + 2205 + 1670 + 2228 + 1707 + + + + + 红嘴鸥 + + 1 + 1 + 3010 + 1705 + 3036 + 1740 + + + + + 红嘴鸥 + + 1 + 1 + 397 + 1607 + 423 + 1643 + + + + + 红嘴鸥 + + 1 + 1 + 988 + 1638 + 1015 + 1669 + + + + + 红嘴鸥 + + 1 + 1 + 2345 + 1565 + 2367 + 1594 + + + + + 红嘴鸥 + + 1 + 1 + 3825 + 1739 + 3840 + 1776 + + + + + 红嘴鸥 + + 1 + 1 + 1458 + 1660 + 1493 + 1686 + + + + + 红嘴鸥 + + 1 + 1 + 1627 + 1656 + 1651 + 1686 + + + + + 红嘴鸥 + + 1 + 1 + 2123 + 2014 + 2197 + 2062 + + + + + 红嘴鸥 + + 1 + 1 + 1 + 1483 + 34 + 1513 + + + + + 红嘴鸥 + + 1 + 1 + 2400 + 1684 + 2425 + 1714 + + + + + 红嘴鸥 + + 1 + 1 + 3347 + 1723 + 3373 + 1757 + + + + + 红嘴鸥 + + 1 + 1 + 281 + 1612 + 310 + 1639 + + + + + 红嘴鸥 + + 1 + 1 + 2183 + 1995 + 2240 + 2064 + + + + + 红嘴鸥 + + 1 + 1 + 906 + 1631 + 931 + 1662 + + + + + 鸟 + + 1 + 1 + 3664 + 1636 + 3684 + 1653 + + + + + 红嘴鸥 + + 1 + 1 + 280 + 1465 + 308 + 1499 + + + + + 红嘴鸥 + + 1 + 1 + 3449 + 1621 + 3473 + 1643 + + + + + 鸟 + + 1 + 1 + 1044 + 1842 + 1130 + 1924 + + + + + 红嘴鸥 + + 1 + 1 + 2293 + 1828 + 2344 + 1934 + + + + + 红嘴鸥 + + 1 + 1 + 3007 + 1850 + 3063 + 1940 + + + + + 鸟 + + 1 + 1 + 866 + 1847 + 955 + 1923 + + + + + 红嘴鸥 + + 1 + 1 + 2559 + 1848 + 2608 + 1936 + + + + + 红嘴鸥 + + 1 + 1 + 738 + 1841 + 804 + 1925 + + + + + 红嘴鸥 + + 1 + 1 + 3239 + 1866 + 3311 + 1945 + + + + + 鸟 + + 1 + 1 + 1835 + 1853 + 1903 + 1927 + + + + + 红嘴鸥 + + 1 + 1 + 501 + 1834 + 559 + 1922 + + + + + 红嘴鸥 + + 1 + 1 + 271 + 1832 + 330 + 1924 + + + + + 红嘴鸥 + + 1 + 1 + 1259 + 1850 + 1317 + 1926 + + + + + 红嘴鸥 + + 1 + 1 + 1640 + 1833 + 1703 + 1926 + + + + + 红嘴鸥 + + 1 + 1 + 2096 + 1843 + 2143 + 1930 + + + + + 鸟 + + 1 + 1 + 1438 + 1850 + 1525 + 1927 + + + + + 鸟 + + 1 + 1 + 67 + 1838 + 136 + 1921 + + + + + 鸟 + + 1 + 1 + 1462 + 940 + 1492 + 969 + + + + + 红嘴鸥 + + 1 + 1 + 1505 + 961 + 1533 + 997 + + + + + 红嘴鸥 + + 1 + 1 + 3418 + 1005 + 3443 + 1031 + + + + + 红嘴鸥 + + 1 + 1 + 2669 + 991 + 2706 + 1021 + + + + + 鸟 + + 1 + 1 + 497 + 915 + 531 + 969 + + + + + 红嘴鸥 + + 1 + 1 + 3518 + 973 + 3548 + 1000 + + + + + 红嘴鸥 + + 1 + 1 + 686 + 926 + 709 + 960 + + + + + 红嘴鸥 + + 1 + 1 + 2024 + 973 + 2049 + 1003 + + + + + 红嘴鸥 + + 1 + 1 + 2532 + 960 + 2557 + 988 + + + + + 红嘴鸥 + + 1 + 1 + 2574 + 987 + 2607 + 1014 + + + + + 红嘴鸥 + + 1 + 1 + 2363 + 983 + 2395 + 1012 + + + + + 红嘴鸥 + + 1 + 1 + 2107 + 979 + 2142 + 1005 + + + + + 红嘴鸥 + + 1 + 1 + 2931 + 990 + 2959 + 1018 + + + + + 红嘴鸥 + + 1 + 1 + 721 + 950 + 747 + 975 + + + + + 红嘴鸥 + + 1 + 1 + 3502 + 1005 + 3525 + 1031 + + + + + 红嘴鸥 + + 1 + 1 + 248 + 911 + 276 + 953 + + + + + 红嘴鸥 + + 1 + 1 + 3053 + 976 + 3084 + 1001 + + + + + 红嘴鸥 + + 1 + 1 + 3248 + 999 + 3267 + 1027 + + + + + 红嘴鸥 + + 1 + 1 + 1415 + 965 + 1444 + 997 + + + + + 红嘴鸥 + + 1 + 1 + 1020 + 932 + 1062 + 972 + + + + + 鸟 + + 1 + 1 + 1119 + 941 + 1153 + 981 + + + + + 鸟 + + 1 + 1 + 408 + 917 + 431 + 952 + + + + + 红嘴鸥 + + 1 + 1 + 3222 + 966 + 3241 + 996 + + + + + 红嘴鸥 + + 1 + 1 + 3163 + 971 + 3193 + 995 + + + + + 红嘴鸥 + + 1 + 1 + 931 + 957 + 954 + 981 + + + + + 红嘴鸥 + + 1 + 1 + 785 + 931 + 807 + 959 + + + + + 红嘴鸥 + + 1 + 1 + 810 + 948 + 838 + 977 + + + + + 红嘴鸥 + + 1 + 1 + 2495 + 979 + 2517 + 1015 + + + + + 红嘴鸥 + + 1 + 1 + 3400 + 977 + 3419 + 1000 + + + + + 红嘴鸥 + + 1 + 1 + 3015 + 999 + 3038 + 1024 + + + + + 红嘴鸥 + + 1 + 1 + 2271 + 986 + 2297 + 1011 + + + + + 红嘴鸥 + + 1 + 1 + 3092 + 985 + 3117 + 1023 + + + + + 红嘴鸥 + + 1 + 1 + 1870 + 942 + 1896 + 973 + + + + + 红嘴鸥 + + 1 + 1 + 2778 + 956 + 2802 + 989 + + + + + 红嘴鸥 + + 1 + 1 + 1218 + 957 + 1255 + 988 + + + + + 红嘴鸥 + + 1 + 1 + 2435 + 983 + 2464 + 1015 + + + + + 红嘴鸥 + + 1 + 1 + 907 + 932 + 932 + 958 + + + + + 红嘴鸥 + + 1 + 1 + 2847 + 990 + 2878 + 1018 + + + + + 红嘴鸥 + + 1 + 1 + 1302 + 959 + 1329 + 989 + + + + + 鸟 + + 1 + 1 + 2447 + 947 + 2476 + 981 + + + + + 红嘴鸥 + + 1 + 1 + 876 + 952 + 898 + 977 + + + + + 红嘴鸥 + + 1 + 1 + 3291 + 972 + 3316 + 994 + + + + + 红嘴鸥 + + 1 + 1 + 87 + 936 + 117 + 963 + + + + + 鸟 + + 1 + 1 + 1351 + 950 + 1381 + 988 + + + + + 红嘴鸥 + + 1 + 1 + 3613 + 1017 + 3636 + 1041 + + + + + 红嘴鸥 + + 1 + 1 + 3726 + 973 + 3756 + 1007 + + + + + 红嘴鸥 + + 1 + 1 + 3323 + 1007 + 3354 + 1029 + + + + + 鸟 + + 1 + 1 + 599 + 931 + 635 + 964 + + + + + 红嘴鸥 + + 1 + 1 + 1222 + 631 + 1281 + 654 + + + + + 红嘴鸥 + + 1 + 1 + 3186 + 1000 + 3209 + 1026 + + + + + 红嘴鸥 + + 1 + 1 + 1742 + 919 + 1801 + 957 + + + + + 红嘴鸥 + + 1 + 1 + 1604 + 966 + 1646 + 996 + + + + + 红嘴鸥 + + 1 + 1 + 1871 + 972 + 1909 + 1001 + + + + + 红嘴鸥 + + 1 + 1 + 2774 + 989 + 2799 + 1019 + + + + + 红嘴鸥 + + 1 + 1 + 2224 + 940 + 2255 + 964 + + + + + 红嘴鸥 + + 1 + 1 + 1788 + 954 + 1826 + 997 + + + + + 红嘴鸥 + + 1 + 1 + 2675 + 961 + 2711 + 984 + + + + + 红嘴鸥 + + 1 + 1 + 149 + 920 + 181 + 952 + + + + + 鸟 + + 1 + 1 + 3167 + 1343 + 3472 + 1438 + + + + + 鸟 + + 1 + 1 + 2034 + 1021 + 2103 + 1058 + + + + + 苍鹭 + + 1 + 1 + 2798 + 671 + 2919 + 838 + + + + + 骨顶鸡 + + 1 + 1 + 950 + 902 + 1033 + 940 + + + + + 红嘴鸥 + + 1 + 1 + 2259 + 733 + 2339 + 797 + + + + + 鸟 + + 1 + 1 + 253 + 893 + 341 + 928 + + + + + 红嘴鸥 + + 1 + 1 + 1015 + 667 + 1067 + 713 + + + + + 红嘴鸥 + + 1 + 1 + 1113 + 669 + 1165 + 718 + + + + + 红嘴鸥 + + 1 + 1 + 736 + 639 + 813 + 696 + + + + + 红嘴鸥 + + 1 + 1 + 115 + 605 + 186 + 653 + + + + + 鸟 + + 1 + 1 + 265 + 610 + 319 + 654 + + + + + 鸟 + + 1 + 1 + 582 + 636 + 619 + 679 + + + + + 鸟 + + 1 + 1 + 90 + 904 + 166 + 942 + + + + + 鸟 + + 1 + 1 + 2125 + 738 + 2163 + 784 + + + + + 鸟 + + 1 + 1 + 3375 + 671 + 3522 + 748 + + + + + 鸟 + + 1 + 1 + 362 + 1033 + 429 + 1081 + + + + + 红嘴鸥 + + 1 + 1 + 2320 + 678 + 2381 + 723 + + + + + 鸟 + + 1 + 1 + 902 + 1014 + 1004 + 1054 + + + + + 鸟 + + 1 + 1 + 639 + 912 + 686 + 953 + + + + + 鸟 + + 1 + 1 + 1331 + 869 + 1376 + 906 + + + + + 鸟 + + 1 + 1 + 2852 + 1108 + 2947 + 1144 + + + + + 鸟 + + 1 + 1 + 2759 + 1144 + 2846 + 1207 + + + + + 鸟 + + 1 + 1 + 772 + 1013 + 878 + 1059 + + + + + 鸟 + + 1 + 1 + 1020 + 1063 + 1098 + 1104 + + + + + 鸟 + + 1 + 1 + 1099 + 937 + 1191 + 985 + + + + + 鸟 + + 1 + 1 + 1782 + 703 + 1857 + 765 + + + + + 鸟 + + 1 + 1 + 2620 + 1015 + 2674 + 1053 + + + + + 鸟 + + 1 + 1 + 1 + 880 + 40 + 915 + + + + + 鸟 + + 1 + 1 + 3783 + 838 + 3840 + 890 + + + + + 鸟 + + 1 + 1 + 2525 + 1127 + 2632 + 1168 + + + + + 鸟 + + 1 + 1 + 2297 + 1037 + 2373 + 1070 + + + + + 鸟 + + 1 + 1 + 556 + 1002 + 635 + 1045 + + + + + 鸟 + + 1 + 1 + 919 + 646 + 975 + 706 + + + + + 鸟 + + 1 + 1 + 1143 + 756 + 1215 + 796 + + + + + 红嘴鸥 + + 1 + 1 + 2040 + 734 + 2075 + 780 + + + + + 红嘴鸥 + + 1 + 1 + 1711 + 709 + 1761 + 763 + + + + + 鸟 + + 1 + 1 + 1289 + 675 + 1349 + 733 + + + + + 鸟 + + 1 + 1 + 3653 + 826 + 3709 + 876 + + + + + 鸟 + + 1 + 1 + 611 + 1082 + 656 + 1117 + + + + + 鸟 + + 1 + 1 + 3553 + 1176 + 3633 + 1210 + + + + + 鸟 + + 1 + 1 + 35 + 601 + 101 + 648 + + + + + 鸟 + + 1 + 1 + 2243 + 1113 + 2324 + 1153 + + + + + 鸟 + + 1 + 1 + 2185 + 1013 + 2233 + 1066 + + + + + 鸟 + + 1 + 1 + 2719 + 953 + 2769 + 995 + + + + + 鸟 + + 1 + 1 + 848 + 641 + 908 + 699 + + + + + 鸟 + + 1 + 1 + 436 + 624 + 496 + 670 + + + + + 鸟 + + 1 + 1 + 3250 + 819 + 3346 + 859 + + + + + 鸟 + + 1 + 1 + 35 + 829 + 74 + 861 + + + + + 鸟 + + 1 + 1 + 1192 + 938 + 1287 + 970 + + + + + 鸟 + + 1 + 1 + 420 + 1005 + 479 + 1042 + + + + + 鸟 + + 1 + 1 + 2182 + 1226 + 2322 + 1277 + + + + + 鸟 + + 1 + 1 + 2189 + 960 + 2265 + 999 + + + + + 鸟 + + 1 + 1 + 1600 + 1017 + 1700 + 1065 + + + + + 鸟 + + 1 + 1 + 180 + 958 + 237 + 994 + + + + + 鸟 + + 1 + 1 + 2258 + 1064 + 2319 + 1110 + + + + + 鸟 + + 1 + 1 + 2582 + 1211 + 2712 + 1263 + + + + + 鸟 + + 1 + 1 + 3760 + 916 + 3835 + 957 + + + + + 鸟 + + 1 + 1 + 1704 + 794 + 1767 + 826 + + + + + 鸟 + + 1 + 1 + 127 + 1066 + 213 + 1111 + + + + + 鸟 + + 1 + 1 + 1956 + 734 + 2029 + 787 + + + + + 鸟 + + 1 + 1 + 2114 + 1073 + 2234 + 1119 + + + + + 鸟 + + 1 + 1 + 2887 + 927 + 2969 + 958 + + + + + 鸟 + + 1 + 1 + 1856 + 724 + 1906 + 766 + + + + + 鸟 + + 1 + 1 + 1276 + 1096 + 1364 + 1138 + + + + + 鸟 + + 1 + 1 + 1162 + 1113 + 1218 + 1149 + + + + + 鸟 + + 1 + 1 + 1135 + 1063 + 1215 + 1104 + + + + + 鸟 + + 1 + 1 + 1907 + 995 + 1986 + 1024 + + + + + 鸟 + + 1 + 1 + 1494 + 685 + 1552 + 742 + + + + + 鸟 + + 1 + 1 + 204 + 1015 + 312 + 1057 + + + + + 鸟 + + 1 + 1 + 1976 + 820 + 2044 + 848 + + + + + 红嘴鸥 + + 1 + 1 + 1925 + 731 + 1965 + 778 + + + + + 红嘴鸥 + + 1 + 1 + 1579 + 698 + 1631 + 749 + + + + + 鸟 + + 1 + 1 + 2493 + 639 + 2650 + 702 + + + + + 红嘴鸥 + + 1 + 1 + 1178 + 674 + 1213 + 720 + + + + + 鸟 + + 1 + 1 + 2571 + 1163 + 2632 + 1205 + + + + + 鸟 + + 1 + 1 + 1523 + 1058 + 1604 + 1102 + + + + + 红嘴鸥 + + 1 + 1 + 977 + 355 + 1004 + 382 + + + + + 鸟 + + 1 + 1 + 3590 + 1100 + 3681 + 1138 + + + + + 鸟 + + 1 + 1 + 174 + 1027 + 228 + 1066 + + + + + 鸟 + + 1 + 1 + 2131 + 963 + 2199 + 999 + + + + + 鸟 + + 1 + 1 + 354 + 943 + 444 + 986 + + + + + 红嘴鸥 + + 1 + 1 + 1140 + 357 + 1166 + 395 + + + + + 鸟 + + 1 + 1 + 3775 + 1046 + 3821 + 1085 + + + + + 鸟 + + 1 + 1 + 1923 + 1027 + 1984 + 1063 + + + + + 鸟 + + 1 + 1 + 3580 + 914 + 3676 + 960 + + + + + 红嘴鸥 + + 1 + 1 + 799 + 330 + 825 + 368 + + + + + 红嘴鸥 + + 1 + 1 + 2686 + 675 + 2753 + 737 + + + + + 红嘴鸥 + + 1 + 1 + 1937 + 1128 + 1981 + 1156 + + + + + 鸟 + + 1 + 1 + 3560 + 971 + 3601 + 1013 + + + + + 鸟 + + 1 + 1 + 2460 + 989 + 2590 + 1048 + + + + + 鸟 + + 1 + 1 + 3416 + 806 + 3456 + 860 + + + + + 鸟 + + 1 + 1 + 1484 + 1016 + 1574 + 1053 + + + + + 鸟 + + 1 + 1 + 2886 + 973 + 2973 + 1007 + + + + + 鸟 + + 1 + 1 + 2090 + 979 + 2128 + 1018 + + + + + 鸟 + + 1 + 1 + 3557 + 722 + 3601 + 766 + + + + + 红嘴鸥 + + 1 + 1 + 412 + 421 + 504 + 453 + + + + + 鸟 + + 1 + 1 + 1396 + 674 + 1471 + 739 + + + + + 红嘴鸥 + + 1 + 1 + 1048 + 351 + 1071 + 384 + + + + + 鸟 + + 1 + 1 + 2160 + 761 + 2280 + 861 + + + + + 鸟 + + 1 + 1 + 1828 + 719 + 1937 + 860 + + + + + 红嘴鸥 + + 1 + 1 + 2077 + 1251 + 2208 + 1372 + + + + + 鸟 + + 1 + 1 + 540 + 1306 + 668 + 1362 + + + + + 红嘴鸥 + + 1 + 1 + 3100 + 221 + 3155 + 317 + + + + + 红嘴鸥 + + 1 + 1 + 2475 + 246 + 2544 + 333 + + + + + 红嘴鸥 + + 1 + 1 + 408 + 297 + 523 + 372 + + + + + 红嘴鸥 + + 1 + 1 + 662 + 244 + 722 + 367 + + + + + 红嘴鸥 + + 1 + 1 + 1956 + 245 + 2011 + 343 + + + + + 红嘴鸥 + + 1 + 1 + 2259 + 264 + 2333 + 340 + + + + + 红嘴鸥 + + 1 + 1 + 3320 + 229 + 3376 + 312 + + + + + 红嘴鸥 + + 1 + 1 + 1330 + 256 + 1386 + 355 + + + + + 红嘴鸥 + + 1 + 1 + 873 + 270 + 935 + 364 + + + + + 红嘴鸥 + + 1 + 1 + 3697 + 219 + 3765 + 305 + + + + + 红嘴鸥 + + 1 + 1 + 197 + 295 + 256 + 373 + + + + + 红嘴鸥 + + 1 + 1 + 2653 + 248 + 2709 + 328 + + + + + 红嘴鸥 + + 1 + 1 + 2586 + 889 + 2677 + 978 + + + + + 红嘴鸥 + + 1 + 1 + 2968 + 872 + 3046 + 965 + + + + + 红嘴鸥 + + 1 + 1 + 2745 + 882 + 2814 + 970 + + + + + 红嘴鸥 + + 1 + 1 + 712 + 926 + 782 + 1030 + + + + + 红嘴鸥 + + 1 + 1 + 3664 + 867 + 3755 + 943 + + + + + 红嘴鸥 + + 1 + 1 + 1796 + 912 + 1868 + 998 + + + + + 红嘴鸥 + + 1 + 1 + 2098 + 911 + 2194 + 990 + + + + + 红嘴鸥 + + 1 + 1 + 22 + 978 + 109 + 1052 + + + + + 红嘴鸥 + + 1 + 1 + 1604 + 925 + 1712 + 1004 + + + + + 红嘴鸥 + + 1 + 1 + 1342 + 936 + 1420 + 1012 + + + + + 红嘴鸥 + + 1 + 1 + 194 + 970 + 285 + 1046 + + + + + 红嘴鸥 + + 1 + 1 + 1060 + 933 + 1116 + 1019 + + + + + 红嘴鸥 + + 1 + 1 + 3479 + 867 + 3541 + 947 + + + + + 红嘴鸥 + + 1 + 1 + 3215 + 878 + 3279 + 957 + + + + + 红嘴鸥 + + 1 + 1 + 2446 + 902 + 2558 + 983 + + + + + 红嘴鸥 + + 1 + 1 + 462 + 964 + 539 + 1037 + + + + + 红嘴鸥 + + 1 + 1 + 1917 + 926 + 1972 + 996 + + + + + 红嘴鸥 + + 1 + 1 + 891 + 951 + 963 + 1026 + + + + + 红嘴鸥 + + 1 + 1 + 2558 + 2029 + 2634 + 2111 + + + + + 红嘴鸥 + + 1 + 1 + 2709 + 2025 + 2772 + 2105 + + + + + 红嘴鸥 + + 1 + 1 + 1605 + 2077 + 1686 + 2144 + + + + + 红嘴鸥 + + 1 + 1 + 2420 + 2028 + 2489 + 2115 + + + + + 红嘴鸥 + + 1 + 1 + 1409 + 2088 + 1487 + 2155 + + + + + 红嘴鸥 + + 1 + 1 + 2832 + 2041 + 2900 + 2092 + + + + + 红嘴鸥 + + 1 + 1 + 2282 + 2043 + 2384 + 2118 + + + + + 红嘴鸥 + + 1 + 1 + 2117 + 2064 + 2193 + 2129 + + + + + 红嘴鸥 + + 1 + 1 + 1765 + 2072 + 1849 + 2139 + + + + + 红嘴鸥 + + 1 + 1 + 1912 + 2073 + 1998 + 2137 + + + + + 红嘴鸥 + + 1 + 1 + 2645 + 2054 + 2681 + 2093 + + + + + 红嘴鸥 + + 1 + 1 + 2950 + 2032 + 3022 + 2083 + + + + + 红嘴鸥 + + 1 + 1 + 1556 + 2078 + 1595 + 2112 + + + + + 红嘴鸥 + + 1 + 1 + 2773 + 2053 + 2814 + 2091 + + + + + 红嘴鸥 + + 1 + 1 + 3087 + 2015 + 3156 + 2104 + + + + + 红嘴鸥 + + 1 + 1 + 1250 + 2097 + 1336 + 2159 + + + + + 红嘴鸥 + + 1 + 1 + 2813 + 1031 + 2936 + 1150 + + + + + 红嘴鸥 + + 1 + 1 + 2496 + 1072 + 2611 + 1155 + + + + + 红嘴鸥 + + 1 + 1 + 3046 + 1046 + 3116 + 1135 + + + + + 红嘴鸥 + + 1 + 1 + 3496 + 1036 + 3588 + 1124 + + + + + 红嘴鸥 + + 1 + 1 + 3305 + 1053 + 3380 + 1132 + + + + + 红嘴鸥 + + 1 + 1 + 2090 + 1082 + 2149 + 1163 + + + + + 红嘴鸥 + + 1 + 1 + 3650 + 1038 + 3727 + 1118 + + + + + 红嘴鸥 + + 1 + 1 + 538 + 1132 + 629 + 1219 + + + + + 红嘴鸥 + + 1 + 1 + 2267 + 1092 + 2321 + 1163 + + + + + 红嘴鸥 + + 1 + 1 + 291 + 1145 + 369 + 1210 + + + + + 红嘴鸥 + + 1 + 1 + 1055 + 1112 + 1143 + 1189 + + + + + 红嘴鸥 + + 1 + 1 + 1806 + 1097 + 1864 + 1183 + + + + + 红嘴鸥 + + 1 + 1 + 682 + 1135 + 759 + 1208 + + + + + 红嘴鸥 + + 1 + 1 + 420 + 1149 + 528 + 1215 + + + + + 红嘴鸥 + + 1 + 1 + 1446 + 1109 + 1520 + 1185 + + + + + 红嘴鸥 + + 1 + 1 + 108 + 1140 + 168 + 1214 + + + + + 红嘴鸥 + + 1 + 1 + 1251 + 1118 + 1309 + 1191 + + + + + 红嘴鸥 + + 1 + 1 + 838 + 1134 + 899 + 1202 + + + + + 鸟 + + 1 + 1 + 952 + 1662 + 1281 + 1804 + + + + + 鸟 + + 1 + 1 + 70 + 1635 + 174 + 1700 + + + + + 苍鹭 + + 1 + 1 + 3594 + 1807 + 3677 + 1977 + + + + + 苍鹭 + + 1 + 1 + 2338 + 1735 + 2490 + 1961 + + + + + 鸟 + + 1 + 1 + 1482 + 1872 + 1551 + 1940 + + + + + 苍鹭 + + 1 + 1 + 3239 + 1818 + 3326 + 1976 + + + + + 红嘴鸥 + + 1 + 1 + 807 + 1865 + 900 + 1936 + + + + + 红嘴鸥 + + 1 + 1 + 3014 + 1896 + 3068 + 1965 + + + + + 红嘴鸥 + + 1 + 1 + 1109 + 1872 + 1164 + 1937 + + + + + 鸟 + + 1 + 1 + 1678 + 1882 + 1717 + 1944 + + + + + 红嘴鸥 + + 1 + 1 + 907 + 1869 + 979 + 1939 + + + + + 鸟 + + 1 + 1 + 1588 + 1879 + 1675 + 1944 + + + + + 鸟 + + 1 + 1 + 1014 + 1870 + 1056 + 1935 + + + + + 红嘴鸥 + + 1 + 1 + 605 + 1862 + 666 + 1936 + + + + + 红嘴鸥 + + 1 + 1 + 2848 + 1898 + 2919 + 1963 + + + + + 红嘴鸥 + + 1 + 1 + 2785 + 1882 + 2841 + 1961 + + + + + 鸟 + + 1 + 1 + 308 + 1876 + 357 + 1932 + + + + + 鸟 + + 1 + 1 + 1768 + 1884 + 1830 + 1945 + + + + + 红嘴鸥 + + 1 + 1 + 1690 + 1261 + 1735 + 1288 + + + + + 鸟 + + 1 + 1 + 1344 + 1878 + 1402 + 1934 + + + + + 鸟 + + 1 + 1 + 1 + 980 + 194 + 1102 + + + + + 红嘴鸥 + + 1 + 1 + 647 + 1224 + 684 + 1257 + + + + + 红嘴鸥 + + 1 + 1 + 1410 + 1878 + 1470 + 1941 + + + + + 鸟 + + 1 + 1 + 1870 + 1892 + 1931 + 1944 + + + + + 红嘴鸥 + + 1 + 1 + 52 + 1312 + 86 + 1349 + + + + + 红嘴鸥 + + 1 + 1 + 553 + 1321 + 585 + 1357 + + + + + 鸟 + + 1 + 1 + 979 + 1231 + 1006 + 1268 + + + + + 红嘴鸥 + + 1 + 1 + 37 + 1212 + 62 + 1241 + + + + + 红嘴鸥 + + 1 + 1 + 1114 + 1239 + 1138 + 1270 + + + + + 红嘴鸥 + + 1 + 1 + 370 + 1221 + 401 + 1253 + + + + + 鸟 + + 1 + 1 + 1227 + 1347 + 1253 + 1385 + + + + + 红嘴鸥 + + 1 + 1 + 2657 + 1385 + 2683 + 1435 + + + + + 红嘴鸥 + + 1 + 1 + 302 + 1209 + 328 + 1247 + + + + + 红嘴鸥 + + 1 + 1 + 2117 + 1274 + 2140 + 1296 + + + + + 红嘴鸥 + + 1 + 1 + 1761 + 1260 + 1784 + 1288 + + + + + 红嘴鸥 + + 1 + 1 + 2528 + 1280 + 2558 + 1311 + + + + + 红嘴鸥 + + 1 + 1 + 1959 + 1268 + 1987 + 1295 + + + + + 红嘴鸥 + + 1 + 1 + 200 + 1214 + 225 + 1246 + + + + + 红嘴鸥 + + 1 + 1 + 1180 + 1298 + 1229 + 1328 + + + + + 红嘴鸥 + + 1 + 1 + 1758 + 1363 + 1784 + 1404 + + + + + 红嘴鸥 + + 1 + 1 + 866 + 1339 + 894 + 1375 + + + + + 红嘴鸥 + + 1 + 1 + 119 + 1217 + 142 + 1246 + + + + + 红嘴鸥 + + 1 + 1 + 573 + 1221 + 597 + 1254 + + + + + 红嘴鸥 + + 1 + 1 + 206 + 1324 + 247 + 1355 + + + + + 红嘴鸥 + + 1 + 1 + 680 + 1286 + 714 + 1319 + + + + + 红嘴鸥 + + 1 + 1 + 747 + 1230 + 770 + 1258 + + + + + 红嘴鸥 + + 1 + 1 + 709 + 1334 + 739 + 1370 + + + + + 红嘴鸥 + + 1 + 1 + 3373 + 1300 + 3393 + 1329 + + + + + 红嘴鸥 + + 1 + 1 + 307 + 1330 + 337 + 1356 + + + + + 红嘴鸥 + + 1 + 1 + 408 + 1324 + 437 + 1362 + + + + + 红嘴鸥 + + 1 + 1 + 911 + 1235 + 935 + 1264 + + + + + 红嘴鸥 + + 1 + 1 + 1466 + 1248 + 1488 + 1286 + + + + + 红嘴鸥 + + 1 + 1 + 1329 + 1290 + 1362 + 1322 + + + + + 红嘴鸥 + + 1 + 1 + 3457 + 1301 + 3482 + 1332 + + + + + 红嘴鸥 + + 1 + 1 + 3245 + 1299 + 3270 + 1327 + + + + + 红嘴鸥 + + 1 + 1 + 1814 + 1258 + 1839 + 1290 + + + + + 红嘴鸥 + + 1 + 1 + 2873 + 1289 + 2898 + 1316 + + + + + 红嘴鸥 + + 1 + 1 + 2757 + 1329 + 2791 + 1357 + + + + + 红嘴鸥 + + 1 + 1 + 3297 + 1301 + 3317 + 1328 + + + + + 红嘴鸥 + + 1 + 1 + 2816 + 1289 + 2846 + 1316 + + + + + 红嘴鸥 + + 1 + 1 + 2997 + 1290 + 3028 + 1321 + + + + + 红嘴鸥 + + 1 + 1 + 1535 + 1251 + 1557 + 1287 + + + + + 红嘴鸥 + + 1 + 1 + 1645 + 1256 + 1666 + 1289 + + + + + 红嘴鸥 + + 1 + 1 + 1445 + 1300 + 1472 + 1332 + + + + + 红嘴鸥 + + 1 + 1 + 3733 + 1314 + 3757 + 1344 + + + + + 红嘴鸥 + + 1 + 1 + 1484 + 1290 + 1507 + 1328 + + + + + 红嘴鸥 + + 1 + 1 + 1186 + 1248 + 1213 + 1272 + + + + + 红嘴鸥 + + 1 + 1 + 2679 + 1281 + 2700 + 1310 + + + + + 鸟 + + 1 + 1 + 1071 + 1344 + 1099 + 1377 + + + + + 红嘴鸥 + + 1 + 1 + 2214 + 1271 + 2233 + 1298 + + + + + 鸟 + + 1 + 1 + 1505 + 1788 + 1561 + 1834 + + + + + 红嘴鸥 + + 1 + 1 + 1874 + 1256 + 1895 + 1292 + + + + + 红嘴鸥 + + 1 + 1 + 1855 + 1305 + 1900 + 1342 + + + + + 红嘴鸥 + + 1 + 1 + 844 + 1235 + 866 + 1267 + + + + + 红嘴鸥 + + 1 + 1 + 3102 + 1331 + 3142 + 1369 + + + + + 红嘴鸥 + + 1 + 1 + 2490 + 1275 + 2518 + 1305 + + + + + 红嘴鸥 + + 1 + 1 + 1399 + 1281 + 1429 + 1324 + + + + + 鸟 + + 1 + 1 + 1664 + 1304 + 1696 + 1340 + + + + + 红嘴鸥 + + 1 + 1 + 1047 + 1238 + 1069 + 1268 + + + + + 鸟 + + 1 + 1 + 1284 + 1757 + 1326 + 1815 + + + + + 红嘴鸥 + + 1 + 1 + 3293 + 1329 + 3317 + 1364 + + + + + 红嘴鸥 + + 1 + 1 + 405 + 1184 + 467 + 1212 + + + + + 红嘴鸥 + + 1 + 1 + 2521 + 1330 + 2568 + 1356 + + + + + 红嘴鸥 + + 1 + 1 + 3631 + 1308 + 3653 + 1339 + + + + + 红嘴鸥 + + 1 + 1 + 1244 + 1247 + 1267 + 1273 + + + + + 红嘴鸥 + + 1 + 1 + 3347 + 1339 + 3373 + 1368 + + + + + 红嘴鸥 + + 1 + 1 + 604 + 1290 + 649 + 1314 + + + + + 红嘴鸥 + + 1 + 1 + 3826 + 1313 + 3840 + 1345 + + + + + 红嘴鸥 + + 1 + 1 + 2035 + 1269 + 2055 + 1293 + + + + + 红嘴鸥 + + 1 + 1 + 2975 + 1323 + 3003 + 1359 + + + + + 红嘴鸥 + + 1 + 1 + 2731 + 1286 + 2792 + 1315 + + + + + 红嘴鸥 + + 1 + 1 + 2393 + 1274 + 2414 + 1303 + + + + + 红嘴鸥 + + 1 + 1 + 3027 + 1331 + 3065 + 1365 + + + + + 红嘴鸥 + + 1 + 1 + 3199 + 1295 + 3235 + 1327 + + + + + 红嘴鸥 + + 1 + 1 + 2303 + 1278 + 2321 + 1302 + + + + + 红嘴鸥 + + 1 + 1 + 2934 + 1291 + 2960 + 1324 + + + + + 红嘴鸥 + + 1 + 1 + 2740 + 1403 + 2762 + 1438 + + + + + 红嘴鸥 + + 1 + 1 + 3313 + 1627 + 3436 + 1698 + + + + + 红嘴鸥 + + 1 + 1 + 2404 + 1656 + 2488 + 1732 + + + + + 红嘴鸥 + + 1 + 1 + 1590 + 1688 + 1669 + 1760 + + + + + 红嘴鸥 + + 1 + 1 + 1714 + 1685 + 1803 + 1756 + + + + + 红嘴鸥 + + 1 + 1 + 2105 + 1661 + 2176 + 1742 + + + + + 红嘴鸥 + + 1 + 1 + 984 + 1655 + 1128 + 1779 + + + + + 红嘴鸥 + + 1 + 1 + 1956 + 1675 + 2050 + 1745 + + + + + 红嘴鸥 + + 1 + 1 + 1823 + 1678 + 1904 + 1752 + + + + + 红嘴鸥 + + 1 + 1 + 3139 + 1633 + 3210 + 1706 + + + + + 红嘴鸥 + + 1 + 1 + 1487 + 1683 + 1584 + 1765 + + + + + 红嘴鸥 + + 1 + 1 + 321 + 1692 + 512 + 1813 + + + + + 红嘴鸥 + + 1 + 1 + 2871 + 1648 + 2960 + 1720 + + + + + 红嘴鸥 + + 1 + 1 + 2600 + 1663 + 2690 + 1729 + + + + + 红嘴鸥 + + 1 + 1 + 2226 + 1659 + 2291 + 1737 + + + + + 红嘴鸥 + + 1 + 1 + 274 + 1739 + 338 + 1819 + + + + + 红嘴鸥 + + 1 + 1 + 90 + 1751 + 169 + 1832 + + + + + 红嘴鸥 + + 1 + 1 + 3516 + 1629 + 3627 + 1692 + + + + + 红嘴鸥 + + 1 + 1 + 583 + 1718 + 637 + 1801 + + + + + 红嘴鸥 + + 1 + 1 + 3624 + 1597 + 3717 + 1685 + + + + + 红嘴鸥 + + 1 + 1 + 1219 + 1684 + 1269 + 1778 + + + + + 鸟 + + 1 + 1 + 3232 + 985 + 3280 + 1033 + + + + + 鸟 + + 1 + 1 + 3437 + 896 + 3513 + 943 + + + + + 鸟 + + 1 + 1 + 1814 + 869 + 1896 + 917 + + + + + 鸟 + + 1 + 1 + 3769 + 956 + 3833 + 999 + + + + + 鸟 + + 1 + 1 + 878 + 745 + 947 + 783 + + + + + 鸟 + + 1 + 1 + 2783 + 892 + 2843 + 931 + + + + + 鸟 + + 1 + 1 + 1598 + 781 + 1676 + 819 + + + + + 鸟 + + 1 + 1 + 3660 + 992 + 3745 + 1030 + + + + + 鸟 + + 1 + 1 + 3639 + 885 + 3731 + 929 + + + + + 鸟 + + 1 + 1 + 2419 + 881 + 2508 + 924 + + + + + 鸟 + + 1 + 1 + 1708 + 760 + 1753 + 791 + + + + + 鸟 + + 1 + 1 + 1252 + 758 + 1359 + 806 + + + + + 鸟 + + 1 + 1 + 216 + 753 + 322 + 802 + + + + + 鸟 + + 1 + 1 + 1048 + 823 + 1101 + 873 + + + + + 鸟 + + 1 + 1 + 1284 + 911 + 1372 + 950 + + + + + 鸟 + + 1 + 1 + 2297 + 823 + 2348 + 853 + + + + + 鸟 + + 1 + 1 + 3317 + 1024 + 3367 + 1066 + + + + + 鸟 + + 1 + 1 + 784 + 865 + 832 + 908 + + + + + 鸟 + + 1 + 1 + 912 + 830 + 971 + 869 + + + + + 鸟 + + 1 + 1 + 965 + 803 + 1034 + 845 + + + + + 鸟 + + 1 + 1 + 381 + 797 + 486 + 840 + + + + + 鸟 + + 1 + 1 + 2224 + 969 + 2339 + 1015 + + + + + 鸟 + + 1 + 1 + 337 + 883 + 413 + 920 + + + + + 鸟 + + 1 + 1 + 1479 + 835 + 1524 + 872 + + + + + 鸟 + + 1 + 1 + 1509 + 758 + 1593 + 786 + + + + + 鸟 + + 1 + 1 + 1362 + 939 + 1448 + 981 + + + + + 鸟 + + 1 + 1 + 2378 + 920 + 2461 + 959 + + + + + 鸟 + + 1 + 1 + 2074 + 846 + 2129 + 887 + + + + + 鸟 + + 1 + 1 + 53 + 817 + 161 + 853 + + + + + 鸟 + + 1 + 1 + 2449 + 836 + 2503 + 871 + + + + + 鸟 + + 1 + 1 + 2420 + 806 + 2482 + 841 + + + + + 鸟 + + 1 + 1 + 1410 + 880 + 1475 + 920 + + + + + 鸟 + + 1 + 1 + 594 + 821 + 686 + 861 + + + + + 鸟 + + 1 + 1 + 2094 + 915 + 2187 + 964 + + + + + 鸟 + + 1 + 1 + 2815 + 937 + 2870 + 978 + + + + + 鸟 + + 1 + 1 + 3024 + 1035 + 3117 + 1072 + + + + + 红嘴鸥 + + 1 + 1 + 1864 + 777 + 1909 + 811 + + + + + 鸟 + + 1 + 1 + 3082 + 956 + 3133 + 995 + + + + + 鸟 + + 1 + 1 + 3119 + 901 + 3167 + 949 + + + + + 鸟 + + 1 + 1 + 1782 + 922 + 1829 + 961 + + + + + 红嘴鸥 + + 1 + 1 + 3654 + 609 + 3687 + 649 + + + + + 鸟 + + 1 + 1 + 2728 + 549 + 2768 + 590 + + + + + 鸟 + + 1 + 1 + 2563 + 536 + 2622 + 581 + + + + + 鸟 + + 1 + 1 + 3159 + 566 + 3211 + 621 + + + + + 鸟 + + 1 + 1 + 1963 + 891 + 2050 + 928 + + + + + 鸟 + + 1 + 1 + 2750 + 802 + 2855 + 846 + + + + + 红嘴鸥 + + 1 + 1 + 2945 + 834 + 2984 + 864 + + + + + 红嘴鸥 + + 1 + 1 + 3581 + 856 + 3633 + 889 + + + + + 鸟 + + 1 + 1 + 2947 + 557 + 3000 + 598 + + + + + 鸟 + + 1 + 1 + 1489 + 884 + 1571 + 937 + + + + + 鸟 + + 1 + 1 + 3248 + 873 + 3345 + 916 + + + + + 鸟 + + 1 + 1 + 232 + 897 + 310 + 938 + + + + + 鸟 + + 1 + 1 + 2728 + 898 + 2806 + 940 + + + + + 鸟 + + 1 + 1 + 1287 + 815 + 1360 + 856 + + + + + 鸟 + + 1 + 1 + 3503 + 600 + 3552 + 639 + + + + + 鸟 + + 1 + 1 + 3265 + 898 + 3363 + 936 + + + + + 红嘴鸥 + + 1 + 1 + 3226 + 590 + 3268 + 624 + + + + + 鸟 + + 1 + 1 + 2736 + 835 + 2823 + 874 + + + + + 红嘴鸥 + + 1 + 1 + 2915 + 1903 + 2997 + 1969 + + + + + 红嘴鸥 + + 1 + 1 + 2584 + 1898 + 2654 + 1963 + + + + + 苍鹭 + + 1 + 1 + 2353 + 1803 + 2461 + 1967 + + + + + 红嘴鸥 + + 1 + 1 + 571 + 1891 + 662 + 1952 + + + + + 红嘴鸥 + + 1 + 1 + 305 + 1872 + 357 + 1944 + + + + + 红嘴鸥 + + 1 + 1 + 3256 + 1910 + 3323 + 1976 + + + + + 红嘴鸥 + + 1 + 1 + 2686 + 1900 + 2759 + 1965 + + + + + 红嘴鸥 + + 1 + 1 + 50 + 1876 + 126 + 1947 + + + + + 红嘴鸥 + + 1 + 1 + 3162 + 1914 + 3216 + 1976 + + + + + 红嘴鸥 + + 1 + 1 + 2778 + 1916 + 2841 + 1967 + + + + + 红嘴鸥 + + 1 + 1 + 218 + 1864 + 282 + 1944 + + + + + 苍鹭 + + 1 + 1 + 3574 + 1840 + 3637 + 1986 + + + + + 红嘴鸥 + + 1 + 1 + 3056 + 1921 + 3145 + 1972 + + + + + 红嘴鸥 + + 1 + 1 + 2089 + 1888 + 2153 + 1955 + + + + + 红嘴鸥 + + 1 + 1 + 1269 + 1892 + 1343 + 1948 + + + + + 红嘴鸥 + + 1 + 1 + 459 + 1894 + 519 + 1943 + + + + + 鸟 + + 1 + 1 + 1734 + 1902 + 1785 + 1952 + + + + + 红嘴鸥 + + 1 + 1 + 2151 + 1906 + 2219 + 1959 + + + + + 红嘴鸥 + + 1 + 1 + 1804 + 1906 + 1871 + 1955 + + + + + 红嘴鸥 + + 1 + 1 + 2436 + 1032 + 2484 + 1078 + + + + + 鸟 + + 1 + 1 + 770 + 1887 + 820 + 1950 + + + + + 红嘴鸥 + + 1 + 1 + 1668 + 1471 + 1711 + 1500 + + + + + 红嘴鸥 + + 1 + 1 + 640 + 1432 + 670 + 1469 + + + + + 鸟 + + 1 + 1 + 1629 + 1894 + 1706 + 1956 + + + + + 红嘴鸥 + + 1 + 1 + 327 + 1415 + 361 + 1455 + + + + + 红嘴鸥 + + 1 + 1 + 1957 + 1472 + 1982 + 1514 + + + + + 红嘴鸥 + + 1 + 1 + 1849 + 1468 + 1875 + 1511 + + + + + 鸟 + + 1 + 1 + 1983 + 1908 + 2041 + 1953 + + + + + 红嘴鸥 + + 1 + 1 + 3250 + 1524 + 3283 + 1561 + + + + + 红嘴鸥 + + 1 + 1 + 3738 + 1930 + 3836 + 1992 + + + + + 红嘴鸥 + + 1 + 1 + 1517 + 1464 + 1548 + 1497 + + + + + 红嘴鸥 + + 1 + 1 + 3563 + 1532 + 3588 + 1570 + + + + + 红嘴鸥 + + 1 + 1 + 1450 + 1459 + 1480 + 1495 + + + + + 红嘴鸥 + + 1 + 1 + 1605 + 1472 + 1630 + 1503 + + + + + 红嘴鸥 + + 1 + 1 + 2248 + 1487 + 2277 + 1527 + + + + + 红嘴鸥 + + 1 + 1 + 1565 + 1892 + 1627 + 1948 + + + + + 红嘴鸥 + + 1 + 1 + 737 + 1440 + 764 + 1471 + + + + + 红嘴鸥 + + 1 + 1 + 3661 + 1534 + 3687 + 1576 + + + + + 红嘴鸥 + + 1 + 1 + 3030 + 1527 + 3062 + 1558 + + + + + 红嘴鸥 + + 1 + 1 + 3116 + 1513 + 3142 + 1554 + + + + + 红嘴鸥 + + 1 + 1 + 39 + 1403 + 113 + 1452 + + + + + 红嘴鸥 + + 1 + 1 + 2125 + 1484 + 2153 + 1520 + + + + + 红嘴鸥 + + 1 + 1 + 1308 + 1421 + 1394 + 1459 + + + + + 红嘴鸥 + + 1 + 1 + 1053 + 1444 + 1081 + 1482 + + + + + 鸟 + + 1 + 1 + 1453 + 1896 + 1531 + 1951 + + + + + 红嘴鸥 + + 1 + 1 + 1233 + 1448 + 1264 + 1484 + + + + + 鸟 + + 1 + 1 + 1017 + 1862 + 1171 + 1953 + + + + + 红嘴鸥 + + 1 + 1 + 1181 + 1446 + 1208 + 1487 + + + + + 红嘴鸥 + + 1 + 1 + 961 + 1440 + 993 + 1482 + + + + + 鸟 + + 1 + 1 + 1905 + 1908 + 1953 + 1953 + + + + + 红嘴鸥 + + 1 + 1 + 1358 + 1454 + 1392 + 1497 + + + + + 红嘴鸥 + + 1 + 1 + 2187 + 1487 + 2211 + 1520 + + + + + 红嘴鸥 + + 1 + 1 + 737 + 1317 + 767 + 1344 + + + + + 红嘴鸥 + + 1 + 1 + 3736 + 1551 + 3768 + 1576 + + + + + 红嘴鸥 + + 1 + 1 + 2542 + 1502 + 2576 + 1533 + + + + + 红嘴鸥 + + 1 + 1 + 2888 + 1510 + 2918 + 1546 + + + + + 红嘴鸥 + + 1 + 1 + 3796 + 1548 + 3820 + 1579 + + + + + 红嘴鸥 + + 1 + 1 + 3449 + 1536 + 3473 + 1566 + + + + + 红嘴鸥 + + 1 + 1 + 1942 + 1366 + 1990 + 1404 + + + + + 红嘴鸥 + + 1 + 1 + 3137 + 1384 + 3170 + 1415 + + + + + 红嘴鸥 + + 1 + 1 + 122 + 1420 + 168 + 1453 + + + + + 红嘴鸥 + + 1 + 1 + 1128 + 1442 + 1153 + 1484 + + + + + 红嘴鸥 + + 1 + 1 + 1022 + 1325 + 1055 + 1353 + + + + + 红嘴鸥 + + 1 + 1 + 192 + 1413 + 259 + 1457 + + + + + 红嘴鸥 + + 1 + 1 + 2820 + 1512 + 2848 + 1545 + + + + + 红嘴鸥 + + 1 + 1 + 617 + 1314 + 642 + 1341 + + + + + 红嘴鸥 + + 1 + 1 + 237 + 1355 + 311 + 1426 + + + + + 红嘴鸥 + + 1 + 1 + 2047 + 1479 + 2072 + 1514 + + + + + 红嘴鸥 + + 1 + 1 + 62 + 1296 + 92 + 1327 + + + + + 红嘴鸥 + + 1 + 1 + 2443 + 1495 + 2474 + 1529 + + + + + 红嘴鸥 + + 1 + 1 + 865 + 1403 + 933 + 1452 + + + + + 红嘴鸥 + + 1 + 1 + 159 + 1301 + 190 + 1332 + + + + + 红嘴鸥 + + 1 + 1 + 398 + 1302 + 428 + 1335 + + + + + 红嘴鸥 + + 1 + 1 + 2617 + 1499 + 2642 + 1536 + + + + + 红嘴鸥 + + 1 + 1 + 2351 + 1502 + 2382 + 1533 + + + + + 红嘴鸥 + + 1 + 1 + 2008 + 1352 + 2044 + 1383 + + + + + 鸟 + + 1 + 1 + 300 + 1612 + 380 + 1673 + + + + + 红嘴鸥 + + 1 + 1 + 2713 + 1513 + 2740 + 1540 + + + + + 红嘴鸥 + + 1 + 1 + 445 + 1426 + 474 + 1465 + + + + + 红嘴鸥 + + 1 + 1 + 1111 + 1310 + 1137 + 1358 + + + + + 红嘴鸥 + + 1 + 1 + 3347 + 1525 + 3369 + 1564 + + + + + 红嘴鸥 + + 1 + 1 + 333 + 1302 + 357 + 1331 + + + + + 红嘴鸥 + + 1 + 1 + 2950 + 1516 + 2987 + 1551 + + + + + 红嘴鸥 + + 1 + 1 + 688 + 1314 + 711 + 1343 + + + + + 鸟 + + 1 + 1 + 2616 + 1371 + 2643 + 1400 + + + + + 红嘴鸥 + + 1 + 1 + 1737 + 1471 + 1762 + 1505 + + + + + 鸟 + + 1 + 1 + 1941 + 1910 + 1984 + 1951 + + + + + 红嘴鸥 + + 1 + 1 + 1231 + 1332 + 1264 + 1364 + + + + + 红嘴鸥 + + 1 + 1 + 1559 + 1342 + 1589 + 1368 + + + + + 红嘴鸥 + + 1 + 1 + 538 + 1430 + 568 + 1464 + + + + + 红嘴鸥 + + 1 + 1 + 3621 + 1399 + 3649 + 1431 + + + + + 红嘴鸥 + + 1 + 1 + 1464 + 1340 + 1492 + 1367 + + + + + 红嘴鸥 + + 1 + 1 + 2530 + 1371 + 2556 + 1400 + + + + + 红嘴鸥 + + 1 + 1 + 525 + 1311 + 549 + 1339 + + + + + 红嘴鸥 + + 1 + 1 + 1175 + 1323 + 1205 + 1360 + + + + + 红嘴鸥 + + 1 + 1 + 2046 + 1912 + 2083 + 1950 + + + + + 红嘴鸥 + + 1 + 1 + 2683 + 1399 + 2710 + 1425 + + + + + 红嘴鸥 + + 1 + 1 + 110 + 1299 + 136 + 1331 + + + + + 红嘴鸥 + + 1 + 1 + 843 + 1440 + 868 + 1472 + + + + + 鸟 + + 1 + 1 + 1145 + 1887 + 1216 + 1953 + + + + + 红嘴鸥 + + 1 + 1 + 2450 + 1371 + 2474 + 1400 + + + + + 红嘴鸥 + + 1 + 1 + 2719 + 1371 + 2744 + 1403 + + + + + 红嘴鸥 + + 1 + 1 + 1843 + 1341 + 1866 + 1376 + + + + + 红嘴鸥 + + 1 + 1 + 268 + 1296 + 294 + 1333 + + + + + 红嘴鸥 + + 1 + 1 + 2268 + 1363 + 2303 + 1390 + + + + + 红嘴鸥 + + 1 + 1 + 1905 + 1348 + 1928 + 1377 + + + + + 红嘴鸥 + + 1 + 1 + 1320 + 1338 + 1352 + 1369 + + + + + 红嘴鸥 + + 1 + 1 + 886 + 1320 + 915 + 1348 + + + + + 红嘴鸥 + + 1 + 1 + 3073 + 1384 + 3096 + 1411 + + + + + 红嘴鸥 + + 1 + 1 + 1408 + 1338 + 1433 + 1365 + + + + + 红嘴鸥 + + 1 + 1 + 2062 + 1357 + 2088 + 1382 + + + + + 红嘴鸥 + + 1 + 1 + 470 + 1304 + 496 + 1336 + + + + + 红嘴鸥 + + 1 + 1 + 959 + 1323 + 981 + 1352 + + + + + 红嘴鸥 + + 1 + 1 + 1798 + 1346 + 1820 + 1375 + + + + + 红嘴鸥 + + 1 + 1 + 3269 + 1398 + 3296 + 1422 + + + + + 红嘴鸥 + + 1 + 1 + 3523 + 1401 + 3546 + 1426 + + + + + 红嘴鸥 + + 1 + 1 + 2168 + 1356 + 2198 + 1387 + + + + + 红嘴鸥 + + 1 + 1 + 2114 + 1381 + 2160 + 1411 + + + + + 红嘴鸥 + + 1 + 1 + 1638 + 1344 + 1666 + 1370 + + + + + 红嘴鸥 + + 1 + 1 + 2143 + 5 + 2202 + 106 + + + + + 红嘴鸥 + + 1 + 1 + 2703 + 5 + 2800 + 87 + + + + + 红嘴鸥 + + 1 + 1 + 3351 + 1 + 3437 + 73 + + + + + 红嘴鸥 + + 1 + 1 + 3141 + 1 + 3233 + 76 + + + + + 红嘴鸥 + + 1 + 1 + 2420 + 2 + 2476 + 97 + + + + + 红嘴鸥 + + 1 + 1 + 1762 + 8 + 1869 + 106 + + + + + 红嘴鸥 + + 1 + 1 + 1594 + 31 + 1655 + 106 + + + + + 红嘴鸥 + + 1 + 1 + 3626 + 2 + 3694 + 65 + + + + + 红嘴鸥 + + 1 + 1 + 898 + 25 + 971 + 120 + + + + + 鸟 + + 1 + 1 + 1158 + 13 + 1275 + 107 + + + + + 红嘴鸥 + + 1 + 1 + 2804 + 1904 + 2992 + 2049 + + + + + 红嘴鸥 + + 1 + 1 + 3540 + 1907 + 3646 + 1997 + + + + + 苍鹭 + + 1 + 1 + 1684 + 1799 + 1760 + 1988 + + + + + 红嘴鸥 + + 1 + 1 + 3144 + 1896 + 3209 + 1994 + + + + + 红嘴鸥 + + 1 + 1 + 3323 + 1919 + 3439 + 1995 + + + + + 苍鹭 + + 1 + 1 + 1100 + 1414 + 1160 + 1551 + + + + + 红嘴鸥 + + 1 + 1 + 2239 + 1917 + 2335 + 1983 + + + + + 红嘴鸥 + + 1 + 1 + 807 + 1911 + 896 + 1975 + + + + + 红嘴鸥 + + 1 + 1 + 302 + 1881 + 381 + 1976 + + + + + 红嘴鸥 + + 1 + 1 + 1528 + 1484 + 1611 + 1552 + + + + + 鸟 + + 1 + 1 + 3503 + 1513 + 3556 + 1565 + + + + + 红嘴鸥 + + 1 + 1 + 3781 + 1496 + 3836 + 1568 + + + + + 红嘴鸥 + + 1 + 1 + 3610 + 1508 + 3646 + 1562 + + + + + 鸟 + + 1 + 1 + 3670 + 1518 + 3735 + 1567 + + + + + 鸟 + + 1 + 1 + 2202 + 1425 + 2319 + 1494 + + + + + 红嘴鸥 + + 1 + 1 + 1873 + 1486 + 1936 + 1552 + + + + + 红嘴鸥 + + 1 + 1 + 2154 + 1045 + 2198 + 1073 + + + + + 红嘴鸥 + + 1 + 1 + 3121 + 1510 + 3179 + 1565 + + + + + 红嘴鸥 + + 1 + 1 + 2111 + 1425 + 2166 + 1494 + + + + + 红嘴鸥 + + 1 + 1 + 2927 + 1107 + 2956 + 1131 + + + + + 鸟 + + 1 + 1 + 71 + 1893 + 143 + 1968 + + + + + 红嘴鸥 + + 1 + 1 + 700 + 1013 + 745 + 1045 + + + + + 红嘴鸥 + + 1 + 1 + 2963 + 1510 + 3002 + 1561 + + + + + 鸟 + + 1 + 1 + 712 + 1503 + 792 + 1553 + + + + + 红嘴鸥 + + 1 + 1 + 3208 + 1103 + 3236 + 1138 + + + + + 红嘴鸥 + + 1 + 1 + 3230 + 1512 + 3271 + 1559 + + + + + 红嘴鸥 + + 1 + 1 + 2397 + 1045 + 2417 + 1072 + + + + + 红嘴鸥 + + 1 + 1 + 1529 + 1014 + 1613 + 1062 + + + + + 红嘴鸥 + + 1 + 1 + 2835 + 1099 + 2857 + 1132 + + + + + 红嘴鸥 + + 1 + 1 + 1310 + 1023 + 1337 + 1055 + + + + + 红嘴鸥 + + 1 + 1 + 3299 + 1121 + 3326 + 1141 + + + + + 红嘴鸥 + + 1 + 1 + 3097 + 1114 + 3143 + 1141 + + + + + 红嘴鸥 + + 1 + 1 + 2608 + 1492 + 2644 + 1558 + + + + + 红嘴鸥 + + 1 + 1 + 2239 + 1037 + 2264 + 1074 + + + + + 红嘴鸥 + + 1 + 1 + 2329 + 1050 + 2351 + 1074 + + + + + 红嘴鸥 + + 1 + 1 + 3144 + 1062 + 3174 + 1091 + + + + + 红嘴鸥 + + 1 + 1 + 631 + 1015 + 669 + 1046 + + + + + 红嘴鸥 + + 1 + 1 + 907 + 1052 + 937 + 1087 + + + + + 红嘴鸥 + + 1 + 1 + 2944 + 1052 + 2967 + 1087 + + + + + 红嘴鸥 + + 1 + 1 + 363 + 1045 + 396 + 1069 + + + + + 红嘴鸥 + + 1 + 1 + 969 + 1020 + 991 + 1051 + + + + + 红嘴鸥 + + 1 + 1 + 3384 + 1120 + 3410 + 1142 + + + + + 红嘴鸥 + + 1 + 1 + 3001 + 1106 + 3027 + 1135 + + + + + 红嘴鸥 + + 1 + 1 + 1060 + 1059 + 1093 + 1090 + + + + + 鸟 + + 1 + 1 + 1828 + 1077 + 1857 + 1108 + + + + + 红嘴鸥 + + 1 + 1 + 1161 + 1020 + 1190 + 1052 + + + + + 红嘴鸥 + + 1 + 1 + 1536 + 1076 + 1565 + 1102 + + + + + 鸟 + + 1 + 1 + 574 + 1509 + 649 + 1551 + + + + + 红嘴鸥 + + 1 + 1 + 2048 + 1086 + 2088 + 1116 + + + + + 红嘴鸥 + + 1 + 1 + 3425 + 1062 + 3451 + 1088 + + + + + 红嘴鸥 + + 1 + 1 + 3371 + 1511 + 3413 + 1553 + + + + + 红嘴鸥 + + 1 + 1 + 3050 + 1054 + 3077 + 1089 + + + + + 红嘴鸥 + + 1 + 1 + 3748 + 1070 + 3777 + 1097 + + + + + 红嘴鸥 + + 1 + 1 + 2461 + 1087 + 2490 + 1123 + + + + + 红嘴鸥 + + 1 + 1 + 3814 + 1128 + 3838 + 1152 + + + + + 红嘴鸥 + + 1 + 1 + 2751 + 1103 + 2779 + 1132 + + + + + 红嘴鸥 + + 1 + 1 + 1999 + 1080 + 2039 + 1115 + + + + + 鸟 + + 1 + 1 + 2036 + 1039 + 2062 + 1071 + + + + + 鸟 + + 1 + 1 + 2577 + 1089 + 2601 + 1128 + + + + + 红嘴鸥 + + 1 + 1 + 1123 + 1055 + 1148 + 1091 + + + + + 红嘴鸥 + + 1 + 1 + 3662 + 1119 + 3693 + 1147 + + + + + 红嘴鸥 + + 1 + 1 + 1894 + 1075 + 1921 + 1110 + + + + + 红嘴鸥 + + 1 + 1 + 2633 + 1035 + 2675 + 1065 + + + + + 红嘴鸥 + + 1 + 1 + 3259 + 1067 + 3285 + 1093 + + + + + 鸟 + + 1 + 1 + 2656 + 958 + 2705 + 990 + + + + + 红嘴鸥 + + 1 + 1 + 2353 + 1091 + 2377 + 1122 + + + + + 红嘴鸥 + + 1 + 1 + 438 + 1045 + 472 + 1073 + + + + + 红嘴鸥 + + 1 + 1 + 1641 + 1075 + 1673 + 1102 + + + + + 红嘴鸥 + + 1 + 1 + 3546 + 1117 + 3573 + 1145 + + + + + 红嘴鸥 + + 1 + 1 + 2466 + 1043 + 2486 + 1075 + + + + + 鸟 + + 1 + 1 + 804 + 1017 + 823 + 1044 + + + + + 红嘴鸥 + + 1 + 1 + 3320 + 1054 + 3344 + 1091 + + + + + 红嘴鸥 + + 1 + 1 + 296 + 1008 + 334 + 1035 + + + + + 红嘴鸥 + + 1 + 1 + 2587 + 1047 + 2615 + 1078 + + + + + 红嘴鸥 + + 1 + 1 + 1742 + 1075 + 1768 + 1110 + + + + + 红嘴鸥 + + 1 + 1 + 1798 + 1041 + 1830 + 1066 + + + + + 红嘴鸥 + + 1 + 1 + 2863 + 1054 + 2883 + 1085 + + + + + 红嘴鸥 + + 1 + 1 + 1970 + 1046 + 1994 + 1072 + + + + + 鸟 + + 1 + 1 + 599 + 1051 + 626 + 1084 + + + + + 红嘴鸥 + + 1 + 1 + 2139 + 1093 + 2170 + 1116 + + + + + 红嘴鸥 + + 1 + 1 + 1868 + 1039 + 1891 + 1068 + + + + + 鸟 + + 1 + 1 + 2226 + 1090 + 2246 + 1119 + + + + + 红嘴鸥 + + 1 + 1 + 2705 + 1049 + 2741 + 1079 + + + + + 红嘴鸥 + + 1 + 1 + 136 + 1044 + 165 + 1067 + + + + + 红嘴鸥 + + 1 + 1 + 875 + 1020 + 912 + 1049 + + + + + 红嘴鸥 + + 1 + 1 + 523 + 1051 + 556 + 1081 + + + + + 红嘴鸥 + + 1 + 1 + 208 + 1032 + 233 + 1075 + + + + + 鸟 + + 1 + 1 + 412 + 1008 + 442 + 1049 + + + + + 红嘴鸥 + + 1 + 1 + 1961 + 1080 + 1981 + 1112 + + + + + 鸟 + + 1 + 1 + 938 + 1756 + 1012 + 1788 + + + + + 红嘴鸥 + + 1 + 1 + 1339 + 1075 + 1368 + 1100 + + + + + 红嘴鸥 + + 1 + 1 + 116 + 1008 + 139 + 1032 + + + + + 红嘴鸥 + + 1 + 1 + 2288 + 1091 + 2311 + 1122 + + + + + 红嘴鸥 + + 1 + 1 + 1192 + 1060 + 1213 + 1093 + + + + + 鸟 + + 1 + 1 + 1448 + 1008 + 1472 + 1061 + + + + + 红嘴鸥 + + 1 + 1 + 297 + 1038 + 333 + 1072 + + + + + 红嘴鸥 + + 1 + 1 + 535 + 1009 + 560 + 1038 + + + + + 红嘴鸥 + + 1 + 1 + 1880 + 962 + 1949 + 1036 + + + + + 红嘴鸥 + + 1 + 1 + 2501 + 942 + 2567 + 999 + + + + + 红嘴鸥 + + 1 + 1 + 3334 + 905 + 3393 + 955 + + + + + 红嘴鸥 + + 1 + 1 + 396 + 1030 + 478 + 1091 + + + + + 红嘴鸥 + + 1 + 1 + 3438 + 899 + 3511 + 952 + + + + + 红嘴鸥 + + 1 + 1 + 795 + 1016 + 862 + 1080 + + + + + 红嘴鸥 + + 1 + 1 + 3076 + 922 + 3139 + 974 + + + + + 红嘴鸥 + + 1 + 1 + 2943 + 916 + 2994 + 978 + + + + + 红嘴鸥 + + 1 + 1 + 2219 + 958 + 2274 + 1015 + + + + + 红嘴鸥 + + 1 + 1 + 1773 + 977 + 1827 + 1039 + + + + + 红嘴鸥 + + 1 + 1 + 2787 + 929 + 2863 + 993 + + + + + 红嘴鸥 + + 1 + 1 + 1069 + 1019 + 1135 + 1071 + + + + + 红嘴鸥 + + 1 + 1 + 974 + 1020 + 1036 + 1069 + + + + + 红嘴鸥 + + 1 + 1 + 2114 + 968 + 2185 + 1012 + + + + + 红嘴鸥 + + 1 + 1 + 1190 + 1017 + 1249 + 1065 + + + + + 红嘴鸥 + + 1 + 1 + 2699 + 935 + 2750 + 989 + + + + + 红嘴鸥 + + 1 + 1 + 3527 + 878 + 3602 + 947 + + + + + 红嘴鸥 + + 1 + 1 + 508 + 1041 + 594 + 1094 + + + + + 红嘴鸥 + + 1 + 1 + 882 + 1026 + 958 + 1081 + + + + + 红嘴鸥 + + 1 + 1 + 2590 + 944 + 2659 + 997 + + + + + 红嘴鸥 + + 1 + 1 + 3220 + 908 + 3302 + 965 + + + + + 红嘴鸥 + + 1 + 1 + 1275 + 1004 + 1323 + 1057 + + + + + 红嘴鸥 + + 1 + 1 + 309 + 1045 + 380 + 1097 + + + + + 红嘴鸥 + + 1 + 1 + 1674 + 985 + 1732 + 1045 + + + + + 红嘴鸥 + + 1 + 1 + 594 + 1030 + 677 + 1091 + + + + + 红嘴鸥 + + 1 + 1 + 705 + 1030 + 769 + 1091 + + + + + 红嘴鸥 + + 1 + 1 + 1343 + 1000 + 1406 + 1055 + + + + + 红嘴鸥 + + 1 + 1 + 2407 + 957 + 2481 + 1006 + + + + + 红嘴鸥 + + 1 + 1 + 1428 + 1006 + 1496 + 1055 + + + + + 红嘴鸥 + + 1 + 1 + 2325 + 956 + 2390 + 1010 + + + + + 红嘴鸥 + + 1 + 1 + 1982 + 975 + 2105 + 1022 + + + + + 红嘴鸥 + + 1 + 1 + 3724 + 891 + 3801 + 939 + + + + + 红嘴鸥 + + 1 + 1 + 1540 + 997 + 1606 + 1047 + + + + + 红嘴鸥 + + 1 + 1 + 231 + 1047 + 309 + 1096 + + + + + 鸟 + + 1 + 1 + 1116 + 218 + 1394 + 304 + + + + + 红嘴鸥 + + 1 + 1 + 2568 + 524 + 2649 + 586 + + + + + 红嘴鸥 + + 1 + 1 + 2246 + 536 + 2311 + 603 + + + + + 红嘴鸥 + + 1 + 1 + 3333 + 356 + 3411 + 448 + + + + + 鸟 + + 1 + 1 + 1077 + 509 + 1154 + 657 + + + + + 鸟 + + 1 + 1 + 302 + 556 + 368 + 669 + + + + + 鸟 + + 1 + 1 + 2812 + 410 + 2884 + 539 + + + + + 鸟 + + 1 + 1 + 2398 + 514 + 2490 + 600 + + + + + 鸟 + + 1 + 1 + 536 + 628 + 686 + 695 + + + + + 红嘴鸥 + + 1 + 1 + 2162 + 552 + 2236 + 608 + + + + + 鸟 + + 1 + 1 + 3392 + 491 + 3477 + 550 + + + + + 鸟 + + 1 + 1 + 1935 + 563 + 2003 + 614 + + + + + 鸟 + + 1 + 1 + 3622 + 479 + 3691 + 536 + + + + + 红嘴鸥 + + 1 + 1 + 2075 + 560 + 2153 + 610 + + + + + 红嘴鸥 + + 1 + 1 + 1342 + 1 + 1448 + 64 + + + + + 红嘴鸥 + + 1 + 1 + 2106 + 2 + 2175 + 55 + + + + + 红嘴鸥 + + 1 + 1 + 1667 + 0 + 1730 + 57 + + + + + 红嘴鸥 + + 1 + 1 + 1811 + 0 + 1873 + 57 + + + + + 红嘴鸥 + + 1 + 1 + 2394 + 0 + 2494 + 49 + + + + + 红嘴鸥 + + 1 + 1 + 1121 + 0 + 1191 + 62 + + + + + 红嘴鸥 + + 1 + 1 + 125 + 1 + 186 + 62 + + + + + 红嘴鸥 + + 1 + 1 + 803 + 1 + 886 + 62 + + + + + 红嘴鸥 + + 1 + 1 + 2674 + 1 + 2736 + 43 + + + + + 红嘴鸥 + + 1 + 1 + 549 + 3 + 613 + 69 + + + + + 红嘴鸥 + + 1 + 1 + 3007 + 0 + 3070 + 37 + + + + + 红嘴鸥 + + 1 + 1 + 3198 + 0 + 3260 + 33 + + + + + 红嘴鸥 + + 1 + 1 + 2418 + 1902 + 2494 + 2001 + + + + + 苍鹭 + + 1 + 1 + 1422 + 1345 + 1479 + 1514 + + + + + 苍鹭 + + 1 + 1 + 3766 + 1362 + 3836 + 1515 + + + + + 苍鹭 + + 1 + 1 + 2758 + 1365 + 2819 + 1526 + + + + + 红嘴鸥 + + 1 + 1 + 431 + 1903 + 506 + 2008 + + + + + 红嘴鸥 + + 1 + 1 + 3144 + 1921 + 3244 + 2004 + + + + + 红嘴鸥 + + 1 + 1 + 1176 + 1902 + 1231 + 1995 + + + + + 红嘴鸥 + + 1 + 1 + 3519 + 1917 + 3579 + 2004 + + + + + 红嘴鸥 + + 1 + 1 + 2833 + 1912 + 2899 + 1999 + + + + + 红嘴鸥 + + 1 + 1 + 2014 + 1442 + 2062 + 1505 + + + + + 红嘴鸥 + + 1 + 1 + 885 + 1926 + 938 + 2002 + + + + + 红嘴鸥 + + 1 + 1 + 3243 + 1444 + 3290 + 1517 + + + + + 红嘴鸥 + + 1 + 1 + 149 + 1917 + 206 + 2007 + + + + + 鸟 + + 1 + 1 + 2250 + 1921 + 2306 + 1993 + + + + + 红嘴鸥 + + 1 + 1 + 3530 + 1448 + 3624 + 1509 + + + + + 鸟 + + 1 + 1 + 3310 + 1454 + 3361 + 1511 + + + + + 红嘴鸥 + + 1 + 1 + 397 + 1441 + 445 + 1513 + + + + + 红嘴鸥 + + 1 + 1 + 3151 + 1469 + 3195 + 1517 + + + + + 红嘴鸥 + + 1 + 1 + 2351 + 1452 + 2431 + 1509 + + + + + 鸟 + + 1 + 1 + 224 + 1437 + 278 + 1511 + + + + + 红嘴鸥 + + 1 + 1 + 906 + 1453 + 943 + 1508 + + + + + 红嘴鸥 + + 1 + 1 + 1839 + 1451 + 1885 + 1506 + + + + + 红嘴鸥 + + 1 + 1 + 1098 + 1457 + 1152 + 1508 + + + + + 红嘴鸥 + + 1 + 1 + 543 + 1444 + 586 + 1510 + + + + + 红嘴鸥 + + 1 + 1 + 1 + 1449 + 32 + 1516 + + + + + 苍鹭 + + 1 + 1 + 2150 + 1450 + 2194 + 1508 + + + + + 红嘴鸥 + + 1 + 1 + 713 + 1448 + 762 + 1510 + + + + + 红嘴鸥 + + 1 + 1 + 1735 + 1452 + 1771 + 1506 + + + + + 苍鹭 + + 1 + 1 + 952 + 1323 + 1044 + 1412 + + + + + 红嘴鸥 + + 1 + 1 + 2876 + 550 + 2997 + 620 + + + + + 红嘴鸥 + + 1 + 1 + 155 + 1682 + 196 + 1738 + + + + + 红嘴鸥 + + 1 + 1 + 229 + 1696 + 270 + 1731 + + + + + 红嘴鸥 + + 1 + 1 + 482 + 1674 + 551 + 1714 + + + + + 红嘴鸥 + + 1 + 1 + 661 + 1670 + 695 + 1715 + + + + + 红嘴鸥 + + 1 + 1 + 315 + 1689 + 359 + 1727 + + + + + 红嘴鸥 + + 1 + 1 + 944 + 1365 + 1027 + 1405 + + + + + 红嘴鸥 + + 1 + 1 + 1504 + 1845 + 1579 + 1913 + + + + + 鸟 + + 1 + 1 + 204 + 1851 + 288 + 1915 + + + + + 鸟 + + 1 + 1 + 750 + 1841 + 835 + 1911 + + + + + 鸟 + + 1 + 1 + 1320 + 1825 + 1404 + 1916 + + + + + 苍鹭 + + 1 + 1 + 2400 + 1740 + 2503 + 1934 + + + + + 鸟 + + 1 + 1 + 935 + 1847 + 1010 + 1912 + + + + + 红嘴鸥 + + 1 + 1 + 3499 + 1873 + 3546 + 1943 + + + + + 鸟 + + 1 + 1 + 3096 + 1864 + 3137 + 1930 + + + + + 鸟 + + 1 + 1 + 489 + 1853 + 577 + 1913 + + + + + 鸟 + + 1 + 1 + 361 + 1851 + 447 + 1911 + + + + + 鸟 + + 1 + 1 + 3656 + 1871 + 3748 + 1944 + + + + + 红嘴鸥 + + 1 + 1 + 3299 + 1863 + 3340 + 1935 + + + + + 鸟 + + 1 + 1 + 1831 + 1850 + 1893 + 1916 + + + + + 鸟 + + 1 + 1 + 594 + 1841 + 670 + 1908 + + + + + 鸟 + + 1 + 1 + 1698 + 1846 + 1745 + 1916 + + + + + 红嘴鸥 + + 1 + 1 + 193 + 1132 + 219 + 1158 + + + + + 鸟 + + 1 + 1 + 1076 + 1853 + 1153 + 1906 + + + + + 红嘴鸥 + + 1 + 1 + 339 + 1136 + 378 + 1161 + + + + + 红嘴鸥 + + 1 + 1 + 2582 + 1267 + 2610 + 1309 + + + + + 红嘴鸥 + + 1 + 1 + 264 + 1133 + 288 + 1161 + + + + + 红嘴鸥 + + 1 + 1 + 2206 + 1172 + 2231 + 1200 + + + + + 红嘴鸥 + + 1 + 1 + 2081 + 1171 + 2105 + 1197 + + + + + 红嘴鸥 + + 1 + 1 + 3573 + 1312 + 3602 + 1339 + + + + + 鸟 + + 1 + 1 + 1 + 1850 + 37 + 1912 + + + + + 鸟 + + 1 + 1 + 3299 + 1287 + 3322 + 1332 + + + + + 鸟 + + 1 + 1 + 2286 + 1252 + 2323 + 1304 + + + + + 红嘴鸥 + + 1 + 1 + 483 + 1210 + 514 + 1247 + + + + + 苍鹭 + + 1 + 1 + 1704 + 1112 + 1757 + 1193 + + + + + 红嘴鸥 + + 1 + 1 + 3735 + 1313 + 3761 + 1344 + + + + + 红嘴鸥 + + 1 + 1 + 2143 + 1176 + 2166 + 1199 + + + + + 红嘴鸥 + + 1 + 1 + 2004 + 1171 + 2033 + 1197 + + + + + 红嘴鸥 + + 1 + 1 + 3519 + 1202 + 3543 + 1230 + + + + + 红嘴鸥 + + 1 + 1 + 1438 + 1237 + 1470 + 1272 + + + + + 红嘴鸥 + + 1 + 1 + 1347 + 1238 + 1377 + 1275 + + + + + 红嘴鸥 + + 1 + 1 + 3163 + 1195 + 3183 + 1226 + + + + + 红嘴鸥 + + 1 + 1 + 517 + 1133 + 544 + 1161 + + + + + 红嘴鸥 + + 1 + 1 + 2390 + 1263 + 2417 + 1303 + + + + + 红嘴鸥 + + 1 + 1 + 1499 + 1159 + 1522 + 1184 + + + + + 红嘴鸥 + + 1 + 1 + 1963 + 1168 + 1983 + 1197 + + + + + 红嘴鸥 + + 1 + 1 + 2703 + 1192 + 2743 + 1218 + + + + + 红嘴鸥 + + 1 + 1 + 2996 + 1195 + 3025 + 1223 + + + + + 红嘴鸥 + + 1 + 1 + 326 + 1212 + 349 + 1241 + + + + + 鸟 + + 1 + 1 + 2949 + 1279 + 2974 + 1318 + + + + + 红嘴鸥 + + 1 + 1 + 2281 + 1178 + 2304 + 1204 + + + + + 红嘴鸥 + + 1 + 1 + 41 + 1198 + 69 + 1237 + + + + + 红嘴鸥 + + 1 + 1 + 3784 + 1215 + 3805 + 1241 + + + + + 红嘴鸥 + + 1 + 1 + 3107 + 1196 + 3130 + 1225 + + + + + 红嘴鸥 + + 1 + 1 + 143 + 1201 + 168 + 1245 + + + + + 红嘴鸥 + + 1 + 1 + 425 + 1217 + 458 + 1250 + + + + + 红嘴鸥 + + 1 + 1 + 2042 + 1251 + 2073 + 1290 + + + + + 红嘴鸥 + + 1 + 1 + 1419 + 1153 + 1454 + 1180 + + + + + 红嘴鸥 + + 1 + 1 + 2809 + 1188 + 2842 + 1219 + + + + + 红嘴鸥 + + 1 + 1 + 382 + 1219 + 416 + 1245 + + + + + 红嘴鸥 + + 1 + 1 + 2886 + 1294 + 2916 + 1328 + + + + + 红嘴鸥 + + 1 + 1 + 3430 + 1212 + 3467 + 1234 + + + + + 红嘴鸥 + + 1 + 1 + 580 + 1134 + 609 + 1164 + + + + + 鸟 + + 1 + 1 + 2525 + 1239 + 2547 + 1274 + + + + + 红嘴鸥 + + 1 + 1 + 397 + 1149 + 420 + 1177 + + + + + 红嘴鸥 + + 1 + 1 + 2548 + 1176 + 2569 + 1210 + + + + + 红嘴鸥 + + 1 + 1 + 2801 + 1284 + 2828 + 1317 + + + + + 红嘴鸥 + + 1 + 1 + 3577 + 1206 + 3630 + 1237 + + + + + 红嘴鸥 + + 1 + 1 + 2465 + 1178 + 2487 + 1207 + + + + + 红嘴鸥 + + 1 + 1 + 2625 + 1238 + 2651 + 1271 + + + + + 红嘴鸥 + + 1 + 1 + 1844 + 1255 + 1876 + 1283 + + + + + 红嘴鸥 + + 1 + 1 + 2358 + 1176 + 2382 + 1202 + + + + + 红嘴鸥 + + 1 + 1 + 1202 + 1242 + 1234 + 1271 + + + + + 鸟 + + 1 + 1 + 778 + 1181 + 809 + 1219 + + + + + 红嘴鸥 + + 1 + 1 + 3193 + 1286 + 3220 + 1326 + + + + + 红嘴鸥 + + 1 + 1 + 251 + 1214 + 273 + 1246 + + + + + 红嘴鸥 + + 1 + 1 + 3436 + 1301 + 3457 + 1332 + + + + + 红嘴鸥 + + 1 + 1 + 1061 + 1187 + 1095 + 1223 + + + + + 红嘴鸥 + + 1 + 1 + 3221 + 1195 + 3241 + 1226 + + + + + 红嘴鸥 + + 1 + 1 + 3065 + 1194 + 3083 + 1227 + + + + + 鸟 + + 1 + 1 + 539 + 1173 + 574 + 1210 + + + + + 红嘴鸥 + + 1 + 1 + 1277 + 1231 + 1305 + 1275 + + + + + 鸟 + + 1 + 1 + 2608 + 1114 + 2665 + 1188 + + + + + 红嘴鸥 + + 1 + 1 + 2124 + 1262 + 2154 + 1289 + + + + + 红嘴鸥 + + 1 + 1 + 625 + 1152 + 646 + 1184 + + + + + 红嘴鸥 + + 1 + 1 + 3282 + 1205 + 3301 + 1227 + + + + + 红嘴鸥 + + 1 + 1 + 1626 + 1238 + 1650 + 1275 + + + + + 红嘴鸥 + + 1 + 1 + 2689 + 1277 + 2718 + 1310 + + + + + 红嘴鸥 + + 1 + 1 + 2223 + 1257 + 2249 + 1291 + + + + + 红嘴鸥 + + 1 + 1 + 2468 + 1273 + 2498 + 1303 + + + + + 红嘴鸥 + + 1 + 1 + 91 + 1130 + 112 + 1154 + + + + + 红嘴鸥 + + 1 + 1 + 1089 + 1230 + 1114 + 1269 + + + + + 红嘴鸥 + + 1 + 1 + 3000 + 1258 + 3025 + 1294 + + + + + 红嘴鸥 + + 1 + 1 + 1956 + 1246 + 1990 + 1288 + + + + + 红嘴鸥 + + 1 + 1 + 3354 + 1207 + 3374 + 1228 + + + + + 红嘴鸥 + + 1 + 1 + 775 + 1142 + 800 + 1170 + + + + + 红嘴鸥 + + 1 + 1 + 1250 + 1150 + 1273 + 1180 + + + + + 鸟 + + 1 + 1 + 1853 + 145 + 2026 + 249 + + + + + 苍鹭 + + 1 + 1 + 1484 + 29 + 1588 + 287 + + + + + 红嘴鸥 + + 1 + 1 + 2271 + 6 + 2423 + 66 + + + + + 红嘴鸥 + + 1 + 1 + 1587 + 123 + 1711 + 212 + + + + + 鸟 + + 1 + 1 + 2050 + 144 + 2189 + 251 + + + + + 红嘴鸥 + + 1 + 1 + 3258 + 2059 + 3321 + 2120 + + + + + 红嘴鸥 + + 1 + 1 + 2225 + 2036 + 2254 + 2090 + + + + + 红嘴鸥 + + 1 + 1 + 2070 + 2030 + 2098 + 2082 + + + + + 红嘴鸥 + + 1 + 1 + 1327 + 2025 + 1374 + 2076 + + + + + 红嘴鸥 + + 1 + 1 + 2927 + 2064 + 2984 + 2104 + + + + + 红嘴鸥 + + 1 + 1 + 1677 + 1771 + 1713 + 1808 + + + + + 红嘴鸥 + + 1 + 1 + 3619 + 2064 + 3680 + 2122 + + + + + 红嘴鸥 + + 1 + 1 + 691 + 2024 + 742 + 2067 + + + + + 红嘴鸥 + + 1 + 1 + 3016 + 2052 + 3047 + 2109 + + + + + 红嘴鸥 + + 1 + 1 + 1586 + 2030 + 1649 + 2075 + + + + + 红嘴鸥 + + 1 + 1 + 3108 + 2057 + 3181 + 2111 + + + + + 红嘴鸥 + + 1 + 1 + 2418 + 1796 + 2445 + 1836 + + + + + 红嘴鸥 + + 1 + 1 + 2801 + 2043 + 2853 + 2104 + + + + + 红嘴鸥 + + 1 + 1 + 2157 + 2041 + 2195 + 2089 + + + + + 红嘴鸥 + + 1 + 1 + 329 + 2027 + 393 + 2064 + + + + + 红嘴鸥 + + 1 + 1 + 1220 + 2028 + 1272 + 2070 + + + + + 红嘴鸥 + + 1 + 1 + 3531 + 2070 + 3560 + 2116 + + + + + 红嘴鸥 + + 1 + 1 + 3695 + 2078 + 3724 + 2130 + + + + + 红嘴鸥 + + 1 + 1 + 1956 + 2031 + 1983 + 2081 + + + + + 红嘴鸥 + + 1 + 1 + 2694 + 2054 + 2738 + 2093 + + + + + 红嘴鸥 + + 1 + 1 + 3465 + 2082 + 3499 + 2118 + + + + + 红嘴鸥 + + 1 + 1 + 1820 + 2028 + 1871 + 2084 + + + + + 红嘴鸥 + + 1 + 1 + 1769 + 1777 + 1801 + 1813 + + + + + 红嘴鸥 + + 1 + 1 + 132 + 2015 + 175 + 2058 + + + + + 红嘴鸥 + + 1 + 1 + 570 + 2019 + 642 + 2068 + + + + + 红嘴鸥 + + 1 + 1 + 2041 + 1787 + 2070 + 1824 + + + + + 红嘴鸥 + + 1 + 1 + 1415 + 2028 + 1451 + 2073 + + + + + 红嘴鸥 + + 1 + 1 + 6 + 2020 + 63 + 2060 + + + + + 红嘴鸥 + + 1 + 1 + 1207 + 1762 + 1256 + 1792 + + + + + 红嘴鸥 + + 1 + 1 + 872 + 1745 + 899 + 1778 + + + + + 红嘴鸥 + + 1 + 1 + 1954 + 1786 + 1981 + 1821 + + + + + 红嘴鸥 + + 1 + 1 + 771 + 1744 + 800 + 1775 + + + + + 红嘴鸥 + + 1 + 1 + 2349 + 2045 + 2387 + 2092 + + + + + 红嘴鸥 + + 1 + 1 + 2406 + 2053 + 2471 + 2090 + + + + + 红嘴鸥 + + 1 + 1 + 1281 + 1759 + 1311 + 1799 + + + + + 红嘴鸥 + + 1 + 1 + 2324 + 1795 + 2349 + 1837 + + + + + 红嘴鸥 + + 1 + 1 + 849 + 2012 + 912 + 2072 + + + + + 红嘴鸥 + + 1 + 1 + 1159 + 2021 + 1204 + 2074 + + + + + 红嘴鸥 + + 1 + 1 + 1833 + 1782 + 1859 + 1818 + + + + + 红嘴鸥 + + 1 + 1 + 3221 + 2061 + 3248 + 2111 + + + + + 红嘴鸥 + + 1 + 1 + 3347 + 1850 + 3376 + 1880 + + + + + 红嘴鸥 + + 1 + 1 + 3202 + 1840 + 3229 + 1876 + + + + + 红嘴鸥 + + 1 + 1 + 1718 + 2047 + 1747 + 2085 + + + + + 红嘴鸥 + + 1 + 1 + 1458 + 2019 + 1510 + 2075 + + + + + 红嘴鸥 + + 1 + 1 + 291 + 1720 + 316 + 1760 + + + + + 红嘴鸥 + + 1 + 1 + 3031 + 1834 + 3058 + 1868 + + + + + 红嘴鸥 + + 1 + 1 + 2500 + 2057 + 2526 + 2097 + + + + + 红嘴鸥 + + 1 + 1 + 753 + 2008 + 827 + 2068 + + + + + 红嘴鸥 + + 1 + 1 + 3677 + 1776 + 3707 + 1810 + + + + + 红嘴鸥 + + 1 + 1 + 2168 + 1687 + 2195 + 1729 + + + + + 红嘴鸥 + + 1 + 1 + 384 + 1735 + 413 + 1762 + + + + + 红嘴鸥 + + 1 + 1 + 1120 + 2023 + 1162 + 2075 + + + + + 红嘴鸥 + + 1 + 1 + 2502 + 1803 + 2524 + 1843 + + + + + 红嘴鸥 + + 1 + 1 + 2579 + 1712 + 2605 + 1744 + + + + + 红嘴鸥 + + 1 + 1 + 2792 + 1822 + 2819 + 1862 + + + + + 红嘴鸥 + + 1 + 1 + 3368 + 1750 + 3394 + 1783 + + + + + 红嘴鸥 + + 1 + 1 + 196 + 1721 + 237 + 1756 + + + + + 红嘴鸥 + + 1 + 1 + 2315 + 2046 + 2348 + 2087 + + + + + 红嘴鸥 + + 1 + 1 + 464 + 1731 + 488 + 1763 + + + + + 红嘴鸥 + + 1 + 1 + 461 + 2011 + 515 + 2069 + + + + + 红嘴鸥 + + 1 + 1 + 521 + 2006 + 564 + 2063 + + + + + 红嘴鸥 + + 1 + 1 + 1280 + 2031 + 1314 + 2074 + + + + + 红嘴鸥 + + 1 + 1 + 2283 + 1800 + 2313 + 1831 + + + + + 红嘴鸥 + + 1 + 1 + 923 + 2015 + 962 + 2073 + + + + + 红嘴鸥 + + 1 + 1 + 1539 + 1761 + 1568 + 1803 + + + + + 红嘴鸥 + + 1 + 1 + 552 + 1735 + 576 + 1766 + + + + + 红嘴鸥 + + 1 + 1 + 3548 + 1851 + 3575 + 1887 + + + + + 红嘴鸥 + + 1 + 1 + 991 + 1751 + 1017 + 1785 + + + + + 红嘴鸥 + + 1 + 1 + 3436 + 1761 + 3464 + 1786 + + + + + 红嘴鸥 + + 1 + 1 + 2145 + 1792 + 2168 + 1826 + + + + + 红嘴鸥 + + 1 + 1 + 2652 + 1712 + 2677 + 1751 + + + + + 鸟 + + 1 + 1 + 2427 + 1704 + 2451 + 1737 + + + + + 红嘴鸥 + + 1 + 1 + 1355 + 1764 + 1384 + 1798 + + + + + 红嘴鸥 + + 1 + 1 + 2959 + 1826 + 2984 + 1862 + + + + + 红嘴鸥 + + 1 + 1 + 1429 + 1768 + 1456 + 1800 + + + + + 红嘴鸥 + + 1 + 1 + 3497 + 1760 + 3520 + 1787 + + + + + 红嘴鸥 + + 1 + 1 + 2228 + 1691 + 2251 + 1729 + + + + + 红嘴鸥 + + 1 + 1 + 680 + 1733 + 703 + 1768 + + + + + 红嘴鸥 + + 1 + 1 + 1885 + 1684 + 1920 + 1715 + + + + + 红嘴鸥 + + 1 + 1 + 221 + 2017 + 312 + 2066 + + + + + 红嘴鸥 + + 1 + 1 + 1411 + 1662 + 1446 + 1695 + + + + + 红嘴鸥 + + 1 + 1 + 1704 + 1673 + 1729 + 1705 + + + + + 红嘴鸥 + + 1 + 1 + 1593 + 1666 + 1619 + 1697 + + + + + 红嘴鸥 + + 1 + 1 + 843 + 1634 + 867 + 1670 + + + + + 红嘴鸥 + + 1 + 1 + 1642 + 1670 + 1669 + 1700 + + + + + 红嘴鸥 + + 1 + 1 + 899 + 1639 + 926 + 1671 + + + + + 红嘴鸥 + + 1 + 1 + 2894 + 1828 + 2926 + 1864 + + + + + 红嘴鸥 + + 1 + 1 + 3754 + 1769 + 3778 + 1799 + + + + + 鸟 + + 1 + 1 + 1533 + 1660 + 1557 + 1696 + + + + + 红嘴鸥 + + 1 + 1 + 2097 + 1695 + 2120 + 1728 + + + + + 红嘴鸥 + + 1 + 1 + 3619 + 1763 + 3644 + 1795 + + + + + 红嘴鸥 + + 1 + 1 + 702 + 1631 + 726 + 1662 + + + + + 红嘴鸥 + + 1 + 1 + 1485 + 1666 + 1511 + 1694 + + + + + 红嘴鸥 + + 1 + 1 + 3557 + 1760 + 3583 + 1794 + + + + + 红嘴鸥 + + 1 + 1 + 1135 + 1762 + 1161 + 1789 + + + + + 红嘴鸥 + + 1 + 1 + 3124 + 1845 + 3151 + 1875 + + + + + 红嘴鸥 + + 1 + 1 + 991 + 2008 + 1026 + 2075 + + + + + 红嘴鸥 + + 1 + 1 + 2690 + 1806 + 2717 + 1854 + + + + + 红嘴鸥 + + 1 + 1 + 1221 + 1645 + 1250 + 1683 + + + + + 红嘴鸥 + + 1 + 1 + 1839 + 1688 + 1867 + 1714 + + + + + 红嘴鸥 + + 1 + 1 + 1784 + 2044 + 1823 + 2078 + + + + + 红嘴鸥 + + 1 + 1 + 2753 + 1719 + 2781 + 1754 + + + + + 红嘴鸥 + + 1 + 1 + 740 + 1639 + 788 + 1675 + + + + + 红嘴鸥 + + 1 + 1 + 2573 + 2048 + 2612 + 2092 + + + + + 红嘴鸥 + + 1 + 1 + 2299 + 1696 + 2321 + 1731 + + + + + 红嘴鸥 + + 1 + 1 + 2704 + 1718 + 2741 + 1751 + + + + + 红嘴鸥 + + 1 + 1 + 3077 + 1732 + 3106 + 1772 + + + + + 红嘴鸥 + + 1 + 1 + 2041 + 1694 + 2071 + 1723 + + + + + 红嘴鸥 + + 1 + 1 + 1073 + 1751 + 1098 + 1786 + + + + + 红嘴鸥 + + 1 + 1 + 655 + 1634 + 678 + 1659 + + + + + 红嘴鸥 + + 1 + 1 + 998 + 1994 + 1122 + 2062 + + + + + 红嘴鸥 + + 1 + 1 + 2960 + 1734 + 2987 + 1767 + + + + + 红嘴鸥 + + 1 + 1 + 1947 + 1687 + 1978 + 1722 + + + + + 红嘴鸥 + + 1 + 1 + 1096 + 1648 + 1122 + 1680 + + + + + 红嘴鸥 + + 1 + 1 + 1780 + 1679 + 1802 + 1709 + + + + + 红嘴鸥 + + 1 + 1 + 492 + 1619 + 516 + 1649 + + + + + 红嘴鸥 + + 1 + 1 + 2502 + 1712 + 2523 + 1740 + + + + + 红嘴鸥 + + 1 + 1 + 2610 + 1810 + 2691 + 1854 + + + + + 红嘴鸥 + + 1 + 1 + 2895 + 1723 + 2921 + 1761 + + + + + 红嘴鸥 + + 1 + 1 + 1052 + 2025 + 1122 + 2073 + + + + + 红嘴鸥 + + 1 + 1 + 3017 + 1740 + 3050 + 1769 + + + + + 红嘴鸥 + + 1 + 1 + 3145 + 1744 + 3173 + 1775 + + + + + 红嘴鸥 + + 1 + 1 + 430 + 2020 + 466 + 2063 + + + + + 红嘴鸥 + + 1 + 1 + 1156 + 1644 + 1183 + 1681 + + + + + 红嘴鸥 + + 1 + 1 + 972 + 1643 + 999 + 1671 + + + + + 苍鹭 + + 1 + 1 + 111 + 1277 + 185 + 1462 + + + + + 苍鹭 + + 1 + 1 + 3086 + 1359 + 3158 + 1496 + + + + + 红嘴鸥 + + 1 + 1 + 3239 + 1825 + 3318 + 1916 + + + + + 苍鹭 + + 1 + 1 + 561 + 1307 + 618 + 1464 + + + + + 红嘴鸥 + + 1 + 1 + 877 + 1832 + 1013 + 1902 + + + + + 苍鹭 + + 1 + 1 + 1200 + 1329 + 1269 + 1467 + + + + + 红嘴鸥 + + 1 + 1 + 3492 + 1826 + 3571 + 1915 + + + + + 红嘴鸥 + + 1 + 1 + 1552 + 1830 + 1643 + 1901 + + + + + 红嘴鸥 + + 1 + 1 + 3696 + 1821 + 3751 + 1916 + + + + + 红嘴鸥 + + 1 + 1 + 277 + 1802 + 334 + 1901 + + + + + 红嘴鸥 + + 1 + 1 + 2335 + 1415 + 2373 + 1472 + + + + + 红嘴鸥 + + 1 + 1 + 1321 + 1837 + 1400 + 1897 + + + + + 红嘴鸥 + + 1 + 1 + 2828 + 1851 + 2897 + 1926 + + + + + 红嘴鸥 + + 1 + 1 + 1086 + 1825 + 1147 + 1899 + + + + + 鸟 + + 1 + 1 + 12 + 1812 + 86 + 1893 + + + + + 红嘴鸥 + + 1 + 1 + 2474 + 1838 + 2531 + 1921 + + + + + 红嘴鸥 + + 1 + 1 + 2657 + 1848 + 2736 + 1925 + + + + + 鸟 + + 1 + 1 + 2056 + 1417 + 2098 + 1470 + + + + + 鸟 + + 1 + 1 + 536 + 1810 + 601 + 1892 + + + + + 红嘴鸥 + + 1 + 1 + 709 + 884 + 752 + 923 + + + + + 红嘴鸥 + + 1 + 1 + 1607 + 896 + 1656 + 936 + + + + + 红嘴鸥 + + 1 + 1 + 1936 + 1111 + 1978 + 1141 + + + + + 红嘴鸥 + + 1 + 1 + 2569 + 1401 + 2612 + 1472 + + + + + 鸟 + + 1 + 1 + 973 + 1410 + 1012 + 1456 + + + + + 鸟 + + 1 + 1 + 2802 + 912 + 2834 + 957 + + + + + 红嘴鸥 + + 1 + 1 + 1248 + 905 + 1293 + 935 + + + + + 红嘴鸥 + + 1 + 1 + 2142 + 915 + 2164 + 942 + + + + + 红嘴鸥 + + 1 + 1 + 860 + 1403 + 899 + 1459 + + + + + 红嘴鸥 + + 1 + 1 + 2678 + 912 + 2701 + 946 + + + + + 红嘴鸥 + + 1 + 1 + 289 + 884 + 316 + 914 + + + + + 红嘴鸥 + + 1 + 1 + 3473 + 924 + 3508 + 966 + + + + + 红嘴鸥 + + 1 + 1 + 844 + 883 + 867 + 919 + + + + + 鸟 + + 1 + 1 + 3396 + 918 + 3427 + 963 + + + + + 鸟 + + 1 + 1 + 3771 + 917 + 3810 + 973 + + + + + 鸟 + + 1 + 1 + 1936 + 1417 + 1975 + 1463 + + + + + 鸟 + + 1 + 1 + 3069 + 919 + 3108 + 957 + + + + + 红嘴鸥 + + 1 + 1 + 2066 + 908 + 2098 + 940 + + + + + 红嘴鸥 + + 1 + 1 + 3587 + 932 + 3613 + 956 + + + + + 鸟 + + 1 + 1 + 3297 + 918 + 3328 + 961 + + + + + 鸟 + + 1 + 1 + 3164 + 921 + 3200 + 957 + + + + + 红嘴鸥 + + 1 + 1 + 2621 + 932 + 2642 + 955 + + + + + 红嘴鸥 + + 1 + 1 + 1204 + 899 + 1234 + 933 + + + + + 鸟 + + 1 + 1 + 1693 + 892 + 1736 + 938 + + + + + 红嘴鸥 + + 1 + 1 + 225 + 886 + 257 + 912 + + + + + 红嘴鸥 + + 1 + 1 + 2467 + 914 + 2499 + 952 + + + + + 红嘴鸥 + + 1 + 1 + 2561 + 918 + 2596 + 948 + + + + + 鸟 + + 1 + 1 + 2964 + 920 + 3001 + 961 + + + + + 鸟 + + 1 + 1 + 1677 + 1374 + 1771 + 1468 + + + + + 红嘴鸥 + + 1 + 1 + 1401 + 849 + 1465 + 885 + + + + + 红嘴鸥 + + 1 + 1 + 1055 + 905 + 1084 + 929 + + + + + 红嘴鸥 + + 1 + 1 + 1329 + 900 + 1379 + 935 + + + + + 红嘴鸥 + + 1 + 1 + 152 + 889 + 182 + 911 + + + + + 红嘴鸥 + + 1 + 1 + 3207 + 917 + 3251 + 950 + + + + + 红嘴鸥 + + 1 + 1 + 364 + 885 + 391 + 915 + + + + + 红嘴鸥 + + 1 + 1 + 1424 + 891 + 1460 + 937 + + + + + 红嘴鸥 + + 1 + 1 + 876 + 906 + 903 + 926 + + + + + 红嘴鸥 + + 1 + 1 + 3730 + 943 + 3753 + 970 + + + + + 红嘴鸥 + + 1 + 1 + 1762 + 833 + 1852 + 895 + + + + + 红嘴鸥 + + 1 + 1 + 1961 + 913 + 1995 + 943 + + + + + 红嘴鸥 + + 1 + 1 + 638 + 884 + 664 + 923 + + + + + 红嘴鸥 + + 1 + 1 + 3619 + 938 + 3652 + 964 + + + + + 鸟 + + 1 + 1 + 567 + 892 + 598 + 927 + + + + + 红嘴鸥 + + 1 + 1 + 1124 + 895 + 1157 + 928 + + + + + 红嘴鸥 + + 1 + 1 + 2883 + 935 + 2905 + 959 + + + + + 红嘴鸥 + + 1 + 1 + 3345 + 906 + 3375 + 927 + + + + + 鸟 + + 1 + 1 + 803 + 904 + 820 + 926 + + + + + 红嘴鸥 + + 1 + 1 + 1093 + 1912 + 1154 + 2024 + + + + + 苍鹭 + + 1 + 1 + 995 + 1341 + 1052 + 1514 + + + + + 红嘴鸥 + + 1 + 1 + 3627 + 1905 + 3686 + 2012 + + + + + 红嘴鸥 + + 1 + 1 + 3333 + 1919 + 3394 + 2009 + + + + + 鸟 + + 1 + 1 + 3145 + 1930 + 3233 + 2012 + + + + + 红嘴鸥 + + 1 + 1 + 1970 + 1925 + 2054 + 2014 + + + + + 红嘴鸥 + + 1 + 1 + 864 + 1917 + 924 + 2022 + + + + + 红嘴鸥 + + 1 + 1 + 2720 + 1906 + 2775 + 2011 + + + + + 鸟 + + 1 + 1 + 3033 + 1930 + 3102 + 2009 + + + + + 红嘴鸥 + + 1 + 1 + 1473 + 1918 + 1529 + 2021 + + + + + 苍鹭 + + 1 + 1 + 3284 + 1363 + 3347 + 1506 + + + + + 苍鹭 + + 1 + 1 + 2198 + 1362 + 2270 + 1507 + + + + + 苍鹭 + + 1 + 1 + 537 + 1358 + 597 + 1522 + + + + + 红嘴鸥 + + 1 + 1 + 296 + 1940 + 353 + 2023 + + + + + 红嘴鸥 + + 1 + 1 + 2533 + 1906 + 2588 + 2011 + + + + + 红嘴鸥 + + 1 + 1 + 1329 + 1939 + 1389 + 2021 + + + + + 苍鹭 + + 1 + 1 + 2660 + 1373 + 2715 + 1507 + + + + + 苍鹭 + + 1 + 1 + 1764 + 1353 + 1828 + 1513 + + + + + 红嘴鸥 + + 1 + 1 + 3636 + 1439 + 3691 + 1505 + + + + + 红嘴鸥 + + 1 + 1 + 1659 + 1927 + 1724 + 2015 + + + + + 鸟 + + 1 + 1 + 87 + 1380 + 144 + 1521 + + + + + 红嘴鸥 + + 1 + 1 + 78 + 1927 + 143 + 2033 + + + + + 苍鹭 + + 1 + 1 + 1381 + 1361 + 1439 + 1512 + + + + + 红嘴鸥 + + 1 + 1 + 2992 + 1431 + 3032 + 1505 + + + + + 红嘴鸥 + + 1 + 1 + 620 + 203 + 742 + 260 + + + + + 苍鹭 + + 1 + 1 + 491 + 1037 + 542 + 1151 + + + + + 苍鹭 + + 1 + 1 + 2281 + 1135 + 2416 + 1293 + + + + + 苍鹭 + + 1 + 1 + 2979 + 1195 + 3071 + 1354 + + + + + 苍鹭 + + 1 + 1 + 2512 + 1132 + 2616 + 1311 + + + + + 苍鹭 + + 1 + 1 + 604 + 1000 + 786 + 1153 + + + + + 鸟 + + 1 + 1 + 1139 + 1031 + 1214 + 1186 + + + + + 苍鹭 + + 1 + 1 + 3318 + 1232 + 3392 + 1373 + + + + + 苍鹭 + + 1 + 1 + 1369 + 1072 + 1468 + 1204 + + + + + 苍鹭 + + 1 + 1 + 3575 + 1241 + 3675 + 1399 + + + + + 苍鹭 + + 1 + 1 + 1824 + 1096 + 1903 + 1251 + + + + + 苍鹭 + + 1 + 1 + 1632 + 1084 + 1726 + 1221 + + + + + 苍鹭 + + 1 + 1 + 1735 + 1091 + 1845 + 1235 + + + + + 苍鹭 + + 1 + 1 + 2034 + 1120 + 2131 + 1266 + + + + + 红嘴鸥 + + 1 + 1 + 3478 + 175 + 3538 + 215 + + + + + 鸟 + + 1 + 1 + 2738 + 422 + 2899 + 502 + + + + + 鸟 + + 1 + 1 + 1373 + 2 + 1435 + 82 + + + + + 红嘴鸥 + + 1 + 1 + 3332 + 159 + 3388 + 205 + + + + + 鸟 + + 1 + 1 + 3669 + 170 + 3721 + 218 + + + + + 红嘴鸥 + + 1 + 1 + 3392 + 163 + 3444 + 206 + + + + + 鸟 + + 1 + 1 + 3783 + 177 + 3840 + 225 + + + + + 红嘴鸥 + + 1 + 1 + 3549 + 160 + 3595 + 214 + + + + + 红嘴鸥 + + 1 + 1 + 2842 + 1 + 2872 + 32 + + + + + 红嘴鸥 + + 1 + 1 + 3606 + 179 + 3657 + 218 + + + + + 鸟 + + 1 + 1 + 13 + 200 + 95 + 238 + + + + + 鸟 + + 1 + 1 + 3683 + 92 + 3743 + 139 + + + + + 红嘴鸥 + + 1 + 1 + 2947 + 7 + 2975 + 38 + + + + + 鸟 + + 1 + 1 + 1693 + 57 + 1768 + 92 + + + + + 红嘴鸥 + + 1 + 1 + 154 + 192 + 193 + 237 + + + + + 红嘴鸥 + + 1 + 1 + 3258 + 156 + 3300 + 202 + + + + + 红嘴鸥 + + 1 + 1 + 3613 + 98 + 3657 + 135 + + + + + 红嘴鸥 + + 1 + 1 + 142 + 4 + 200 + 38 + + + + + 红嘴鸥 + + 1 + 1 + 2405 + 77 + 2451 + 112 + + + + + 红嘴鸥 + + 1 + 1 + 2713 + 77 + 2754 + 116 + + + + + 鸟 + + 1 + 1 + 792 + 454 + 881 + 501 + + + + + 红嘴鸥 + + 1 + 1 + 3184 + 9 + 3205 + 39 + + + + + 鸟 + + 1 + 1 + 339 + 5 + 409 + 48 + + + + + 红嘴鸥 + + 1 + 1 + 141 + 1791 + 231 + 1841 + + + + + 鸟 + + 1 + 1 + 3730 + 1861 + 3794 + 1934 + + + + + 鸟 + + 1 + 1 + 2801 + 1653 + 2881 + 1707 + + + + + 红嘴鸥 + + 1 + 1 + 3405 + 2009 + 3463 + 2121 + + + + + 红嘴鸥 + + 1 + 1 + 3053 + 2010 + 3106 + 2116 + + + + + 苍鹭 + + 1 + 1 + 821 + 1465 + 874 + 1627 + + + + + 苍鹭 + + 1 + 1 + 3212 + 1445 + 3282 + 1598 + + + + + 鸟 + + 1 + 1 + 69 + 1473 + 128 + 1633 + + + + + 红嘴鸥 + + 1 + 1 + 2144 + 2026 + 2204 + 2124 + + + + + 红嘴鸥 + + 1 + 1 + 930 + 2037 + 1013 + 2142 + + + + + 苍鹭 + + 1 + 1 + 2672 + 1410 + 2732 + 1601 + + + + + 红嘴鸥 + + 1 + 1 + 1343 + 2034 + 1411 + 2134 + + + + + 红嘴鸥 + + 1 + 1 + 3675 + 2032 + 3751 + 2115 + + + + + 红嘴鸥 + + 1 + 1 + 2394 + 2038 + 2456 + 2119 + + + + + 苍鹭 + + 1 + 1 + 2030 + 1464 + 2096 + 1607 + + + + + 苍鹭 + + 1 + 1 + 1513 + 1448 + 1580 + 1612 + + + + + 红嘴鸥 + + 1 + 1 + 1626 + 2048 + 1687 + 2135 + + + + + 红嘴鸥 + + 1 + 1 + 2658 + 2041 + 2731 + 2113 + + + + + 红嘴鸥 + + 1 + 1 + 1138 + 2052 + 1216 + 2137 + + + + + 红嘴鸥 + + 1 + 1 + 757 + 2059 + 820 + 2141 + + + + + 红嘴鸥 + + 1 + 1 + 439 + 1554 + 491 + 1626 + + + + + 鸟 + + 1 + 1 + 121 + 2071 + 187 + 2143 + + + + + 红嘴鸥 + + 1 + 1 + 1805 + 1549 + 1848 + 1606 + + + + + 红嘴鸥 + + 1 + 1 + 1645 + 783 + 1731 + 880 + + + + + 红嘴鸥 + + 1 + 1 + 2218 + 782 + 2331 + 870 + + + + + 红嘴鸥 + + 1 + 1 + 2571 + 755 + 2649 + 863 + + + + + 红嘴鸥 + + 1 + 1 + 2397 + 758 + 2460 + 866 + + + + + 红嘴鸥 + + 1 + 1 + 2995 + 760 + 3072 + 849 + + + + + 红嘴鸥 + + 1 + 1 + 1840 + 807 + 1950 + 878 + + + + + 红嘴鸥 + + 1 + 1 + 2849 + 781 + 2943 + 855 + + + + + 红嘴鸥 + + 1 + 1 + 3381 + 762 + 3470 + 838 + + + + + 红嘴鸥 + + 1 + 1 + 1325 + 796 + 1428 + 889 + + + + + 红嘴鸥 + + 1 + 1 + 3150 + 767 + 3217 + 846 + + + + + 红嘴鸥 + + 1 + 1 + 1507 + 803 + 1557 + 880 + + + + + 红嘴鸥 + + 1 + 1 + 2060 + 794 + 2136 + 874 + + + + + 红嘴鸥 + + 1 + 1 + 2706 + 779 + 2775 + 857 + + + + + 红嘴鸥 + + 1 + 1 + 385 + 841 + 460 + 917 + + + + + 红嘴鸥 + + 1 + 1 + 40 + 856 + 123 + 932 + + + + + 红嘴鸥 + + 1 + 1 + 642 + 835 + 706 + 906 + + + + + 红嘴鸥 + + 1 + 1 + 1113 + 836 + 1188 + 897 + + + + + 红嘴鸥 + + 1 + 1 + 901 + 834 + 958 + 909 + + + + + 红嘴鸥 + + 1 + 1 + 3644 + 744 + 3740 + 831 + + + + + 红嘴鸥 + + 1 + 1 + 2694 + 4 + 2847 + 88 + + + + + 苍鹭 + + 1 + 1 + 340 + 1558 + 412 + 1714 + + + + + 苍鹭 + + 1 + 1 + 3314 + 1489 + 3370 + 1656 + + + + + 苍鹭 + + 1 + 1 + 2766 + 1474 + 2842 + 1660 + + + + + 苍鹭 + + 1 + 1 + 1767 + 1533 + 1835 + 1672 + + + + + 红嘴鸥 + + 1 + 1 + 2732 + 2076 + 2802 + 2160 + + + + + 红嘴鸥 + + 1 + 1 + 3790 + 2071 + 3840 + 2157 + + + + + 红嘴鸥 + + 1 + 1 + 1609 + 2110 + 1677 + 2160 + + + + + 红嘴鸥 + + 1 + 1 + 1212 + 2102 + 1281 + 2160 + + + + + 鸟 + + 1 + 1 + 2437 + 2103 + 2511 + 2160 + + + + + 红嘴鸥 + + 1 + 1 + 3178 + 2087 + 3249 + 2159 + + + + + 红嘴鸥 + + 1 + 1 + 3605 + 1598 + 3645 + 1650 + + + + + 红嘴鸥 + + 1 + 1 + 3377 + 2096 + 3435 + 2160 + + + + + 红嘴鸥 + + 1 + 1 + 3641 + 2095 + 3700 + 2160 + + + + + 红嘴鸥 + + 1 + 1 + 914 + 2114 + 989 + 2160 + + + + + 红嘴鸥 + + 1 + 1 + 1817 + 2113 + 1893 + 2160 + + + + + 鸟 + + 1 + 1 + 1519 + 1866 + 1663 + 2020 + + + + + 红嘴鸥 + + 1 + 1 + 2360 + 550 + 2422 + 636 + + + + + 红嘴鸥 + + 1 + 1 + 3108 + 525 + 3171 + 611 + + + + + 红嘴鸥 + + 1 + 1 + 1934 + 546 + 1994 + 645 + + + + + 红嘴鸥 + + 1 + 1 + 3307 + 522 + 3384 + 604 + + + + + 红嘴鸥 + + 1 + 1 + 1677 + 564 + 1770 + 649 + + + + + 红嘴鸥 + + 1 + 1 + 2792 + 548 + 2890 + 624 + + + + + 苍鹭 + + 1 + 1 + 3552 + 508 + 3620 + 593 + + + + + 红嘴鸥 + + 1 + 1 + 398 + 615 + 504 + 689 + + + + + 红嘴鸥 + + 1 + 1 + 1 + 610 + 64 + 698 + + + + + 红嘴鸥 + + 1 + 1 + 1469 + 583 + 1549 + 657 + + + + + 红嘴鸥 + + 1 + 1 + 2612 + 553 + 2671 + 630 + + + + + 红嘴鸥 + + 1 + 1 + 3736 + 508 + 3796 + 586 + + + + + 红嘴鸥 + + 1 + 1 + 2135 + 562 + 2200 + 643 + + + + + 鸟 + + 1 + 1 + 3292 + 1383 + 3597 + 1504 + + + + + 红嘴鸥 + + 1 + 1 + 848 + 1892 + 996 + 1959 + + + + + 红嘴鸥 + + 1 + 1 + 1253 + 779 + 1325 + 855 + + + + + 红嘴鸥 + + 1 + 1 + 1132 + 788 + 1201 + 849 + + + + + 红嘴鸥 + + 1 + 1 + 1478 + 764 + 1540 + 826 + + + + + 红嘴鸥 + + 1 + 1 + 1574 + 766 + 1657 + 824 + + + + + 红嘴鸥 + + 1 + 1 + 1330 + 777 + 1409 + 840 + + + + + 红嘴鸥 + + 1 + 1 + 2787 + 710 + 2874 + 769 + + + + + 红嘴鸥 + + 1 + 1 + 1406 + 781 + 1481 + 830 + + + + + 红嘴鸥 + + 1 + 1 + 711 + 815 + 809 + 870 + + + + + 红嘴鸥 + + 1 + 1 + 3178 + 676 + 3253 + 741 + + + + + 红嘴鸥 + + 1 + 1 + 375 + 823 + 444 + 888 + + + + + 红嘴鸥 + + 1 + 1 + 503 + 833 + 580 + 878 + + + + + 红嘴鸥 + + 1 + 1 + 1935 + 762 + 2008 + 816 + + + + + 红嘴鸥 + + 1 + 1 + 2557 + 708 + 2621 + 778 + + + + + 红嘴鸥 + + 1 + 1 + 1826 + 757 + 1887 + 819 + + + + + 红嘴鸥 + + 1 + 1 + 1684 + 770 + 1763 + 825 + + + + + 红嘴鸥 + + 1 + 1 + 2676 + 708 + 2741 + 766 + + + + + 红嘴鸥 + + 1 + 1 + 233 + 846 + 303 + 891 + + + + + 红嘴鸥 + + 1 + 1 + 2920 + 703 + 2984 + 762 + + + + + 红嘴鸥 + + 1 + 1 + 3029 + 696 + 3084 + 753 + + + + + 红嘴鸥 + + 1 + 1 + 2413 + 677 + 2511 + 783 + + + + + 红嘴鸥 + + 1 + 1 + 3164 + 1390 + 3274 + 1465 + + + + + 鸟 + + 1 + 1 + 1675 + 1762 + 1777 + 1880 + + + + + 红嘴鸥 + + 1 + 1 + 154 + 1307 + 268 + 1375 + + + + + 红嘴鸥 + + 1 + 1 + 1857 + 1230 + 1955 + 1311 + + + + + 红嘴鸥 + + 1 + 1 + 0 + 1305 + 86 + 1381 + + + + + 红嘴鸥 + + 1 + 1 + 1018 + 1266 + 1094 + 1346 + + + + + 红嘴鸥 + + 1 + 1 + 3026 + 1198 + 3104 + 1272 + + + + + 红嘴鸥 + + 1 + 1 + 2083 + 1222 + 2146 + 1309 + + + + + 红嘴鸥 + + 1 + 1 + 1195 + 1260 + 1278 + 1341 + + + + + 红嘴鸥 + + 1 + 1 + 463 + 1299 + 550 + 1366 + + + + + 红嘴鸥 + + 1 + 1 + 814 + 1282 + 898 + 1348 + + + + + 红嘴鸥 + + 1 + 1 + 343 + 1304 + 426 + 1368 + + + + + 红嘴鸥 + + 1 + 1 + 2274 + 1213 + 2409 + 1307 + + + + + 红嘴鸥 + + 1 + 1 + 619 + 1285 + 693 + 1362 + + + + + 红嘴鸥 + + 1 + 1 + 3185 + 1177 + 3256 + 1262 + + + + + 红嘴鸥 + + 1 + 1 + 2890 + 1193 + 2947 + 1281 + + + + + 红嘴鸥 + + 1 + 1 + 3717 + 1158 + 3815 + 1246 + + + + + 红嘴鸥 + + 1 + 1 + 1383 + 1251 + 1446 + 1329 + + + + + 红嘴鸥 + + 1 + 1 + 2475 + 1208 + 2544 + 1283 + + + + + 红嘴鸥 + + 1 + 1 + 2693 + 1206 + 2749 + 1279 + + + + + 鸟 + + 1 + 1 + 1475 + 1171 + 1707 + 1328 + + + + + 红嘴鸥 + + 1 + 1 + 3439 + 1193 + 3507 + 1256 + + + + + 红嘴鸥 + + 1 + 1 + 756 + 175 + 834 + 268 + + + + + 红嘴鸥 + + 1 + 1 + 3009 + 132 + 3065 + 228 + + + + + 红嘴鸥 + + 1 + 1 + 3660 + 119 + 3724 + 211 + + + + + 红嘴鸥 + + 1 + 1 + 382 + 177 + 479 + 272 + + + + + 红嘴鸥 + + 1 + 1 + 1045 + 167 + 1101 + 263 + + + + + 红嘴鸥 + + 1 + 1 + 1959 + 169 + 2015 + 252 + + + + + 鸟 + + 1 + 1 + 129 + 111 + 446 + 219 + + + + + 红嘴鸥 + + 1 + 1 + 3226 + 1951 + 3286 + 2062 + + + + + 红嘴鸥 + + 1 + 1 + 3544 + 1946 + 3603 + 2057 + + + + + 苍鹭 + + 1 + 1 + 1060 + 1380 + 1123 + 1556 + + + + + 苍鹭 + + 1 + 1 + 2946 + 1347 + 3012 + 1544 + + + + + 红嘴鸥 + + 1 + 1 + 2347 + 1959 + 2404 + 2057 + + + + + 红嘴鸥 + + 1 + 1 + 2016 + 1965 + 2092 + 2055 + + + + + 红嘴鸥 + + 1 + 1 + 1318 + 1973 + 1378 + 2068 + + + + + 苍鹭 + + 1 + 1 + 1421 + 1394 + 1482 + 1549 + + + + + 苍鹭 + + 1 + 1 + 1932 + 1401 + 1993 + 1546 + + + + + 苍鹭 + + 1 + 1 + 3527 + 1395 + 3592 + 1541 + + + + + 苍鹭 + + 1 + 1 + 663 + 1395 + 720 + 1559 + + + + + 红嘴鸥 + + 1 + 1 + 576 + 2001 + 629 + 2079 + + + + + 苍鹭 + + 1 + 1 + 76 + 1407 + 147 + 1568 + + + + + 红嘴鸥 + + 1 + 1 + 1007 + 1996 + 1063 + 2070 + + + + + 红嘴鸥 + + 1 + 1 + 2543 + 1987 + 2595 + 2061 + + + + + 苍鹭 + + 1 + 1 + 2313 + 1395 + 2374 + 1545 + + + + + 红嘴鸥 + + 1 + 1 + 131 + 2005 + 221 + 2082 + + + + + 红嘴鸥 + + 1 + 1 + 3293 + 1488 + 3346 + 1540 + + + + + 红嘴鸥 + + 1 + 1 + 1750 + 1962 + 1806 + 2058 + + + + + 红嘴鸥 + + 1 + 1 + 2619 + 1476 + 2675 + 1548 + + + + + 红嘴鸥 + + 1 + 1 + 414 + 1504 + 456 + 1559 + + + + + 苍鹭 + + 1 + 1 + 467 + 1913 + 536 + 2069 + + + + + 红嘴鸥 + + 1 + 1 + 1607 + 2043 + 1647 + 2090 + + + + + 红嘴鸥 + + 1 + 1 + 701 + 2015 + 758 + 2072 + + + + + 红嘴鸥 + + 1 + 1 + 1478 + 2021 + 1505 + 2077 + + + + + 红嘴鸥 + + 1 + 1 + 1785 + 2033 + 1814 + 2086 + + + + + 红嘴鸥 + + 1 + 1 + 3284 + 2073 + 3348 + 2124 + + + + + 红嘴鸥 + + 1 + 1 + 2161 + 2049 + 2194 + 2105 + + + + + 红嘴鸥 + + 1 + 1 + 2520 + 2048 + 2555 + 2106 + + + + + 红嘴鸥 + + 1 + 1 + 888 + 2015 + 921 + 2072 + + + + + 红嘴鸥 + + 1 + 1 + 827 + 2020 + 864 + 2071 + + + + + 红嘴鸥 + + 1 + 1 + 3152 + 2069 + 3184 + 2113 + + + + + 红嘴鸥 + + 1 + 1 + 960 + 2016 + 990 + 2074 + + + + + 红嘴鸥 + + 1 + 1 + 1358 + 2023 + 1384 + 2078 + + + + + 红嘴鸥 + + 1 + 1 + 2024 + 2048 + 2052 + 2099 + + + + + 红嘴鸥 + + 1 + 1 + 3698 + 2094 + 3742 + 2131 + + + + + 红嘴鸥 + + 1 + 1 + 3423 + 2082 + 3459 + 2121 + + + + + 红嘴鸥 + + 1 + 1 + 1257 + 2025 + 1297 + 2084 + + + + + 红嘴鸥 + + 1 + 1 + 1953 + 2050 + 2007 + 2094 + + + + + 红嘴鸥 + + 1 + 1 + 1414 + 2023 + 1439 + 2082 + + + + + 红嘴鸥 + + 1 + 1 + 3076 + 2065 + 3104 + 2111 + + + + + 红嘴鸥 + + 1 + 1 + 3299 + 1944 + 3344 + 1973 + + + + + 红嘴鸥 + + 1 + 1 + 2744 + 2060 + 2772 + 2105 + + + + + 红嘴鸥 + + 1 + 1 + 2285 + 2058 + 2317 + 2107 + + + + + 红嘴鸥 + + 1 + 1 + 2417 + 2073 + 2450 + 2116 + + + + + 红嘴鸥 + + 1 + 1 + 2673 + 2056 + 2702 + 2108 + + + + + 红嘴鸥 + + 1 + 1 + 1553 + 2024 + 1580 + 2080 + + + + + 红嘴鸥 + + 1 + 1 + 2598 + 2067 + 2644 + 2108 + + + + + 红嘴鸥 + + 1 + 1 + 846 + 1837 + 888 + 1869 + + + + + 红嘴鸥 + + 1 + 1 + 3656 + 1959 + 3685 + 1990 + + + + + 红嘴鸥 + + 1 + 1 + 2081 + 2060 + 2116 + 2101 + + + + + 红嘴鸥 + + 1 + 1 + 1273 + 1843 + 1302 + 1880 + + + + + 红嘴鸥 + + 1 + 1 + 1848 + 2052 + 1879 + 2091 + + + + + 红嘴鸥 + + 1 + 1 + 2795 + 2066 + 2827 + 2105 + + + + + 红嘴鸥 + + 1 + 1 + 323 + 1817 + 350 + 1846 + + + + + 红嘴鸥 + + 1 + 1 + 33 + 1802 + 61 + 1834 + + + + + 红嘴鸥 + + 1 + 1 + 1464 + 1856 + 1513 + 1889 + + + + + 红嘴鸥 + + 1 + 1 + 1013 + 2034 + 1083 + 2074 + + + + + 红嘴鸥 + + 1 + 1 + 3704 + 1953 + 3728 + 1989 + + + + + 红嘴鸥 + + 1 + 1 + 329 + 1720 + 361 + 1750 + + + + + 红嘴鸥 + + 1 + 1 + 2783 + 1915 + 2822 + 1950 + + + + + 红嘴鸥 + + 1 + 1 + 244 + 1811 + 270 + 1838 + + + + + 红嘴鸥 + + 1 + 1 + 2457 + 1900 + 2495 + 1936 + + + + + 红嘴鸥 + + 1 + 1 + 3157 + 1935 + 3188 + 1961 + + + + + 红嘴鸥 + + 1 + 1 + 2909 + 1913 + 2939 + 1955 + + + + + 红嘴鸥 + + 1 + 1 + 1645 + 1867 + 1679 + 1896 + + + + + 红嘴鸥 + + 1 + 1 + 2558 + 1901 + 2592 + 1936 + + + + + 红嘴鸥 + + 1 + 1 + 2841 + 2061 + 2870 + 2108 + + + + + 红嘴鸥 + + 1 + 1 + 2926 + 1852 + 2951 + 1879 + + + + + 红嘴鸥 + + 1 + 1 + 3186 + 1865 + 3213 + 1890 + + + + + 红嘴鸥 + + 1 + 1 + 2806 + 1830 + 2834 + 1873 + + + + + 红嘴鸥 + + 1 + 1 + 453 + 1809 + 479 + 1851 + + + + + 红嘴鸥 + + 1 + 1 + 3361 + 2080 + 3383 + 2120 + + + + + 鸟 + + 1 + 1 + 737 + 1925 + 849 + 1965 + + + + + 红嘴鸥 + + 1 + 1 + 2266 + 1896 + 2332 + 1930 + + + + + 红嘴鸥 + + 1 + 1 + 1346 + 1860 + 1373 + 1888 + + + + + 红嘴鸥 + + 1 + 1 + 1554 + 1869 + 1588 + 1894 + + + + + 红嘴鸥 + + 1 + 1 + 3564 + 2092 + 3632 + 2125 + + + + + 红嘴鸥 + + 1 + 1 + 2990 + 1845 + 3017 + 1882 + + + + + 红嘴鸥 + + 1 + 1 + 1300 + 1756 + 1338 + 1795 + + + + + 红嘴鸥 + + 1 + 1 + 604 + 1823 + 631 + 1862 + + + + + 红嘴鸥 + + 1 + 1 + 3038 + 1843 + 3061 + 1884 + + + + + 红嘴鸥 + + 1 + 1 + 1177 + 1984 + 1265 + 2078 + + + + + 红嘴鸥 + + 1 + 1 + 3445 + 1870 + 3473 + 1906 + + + + + 红嘴鸥 + + 1 + 1 + 1177 + 1848 + 1206 + 1879 + + + + + 红嘴鸥 + + 1 + 1 + 1910 + 1878 + 1937 + 1906 + + + + + 红嘴鸥 + + 1 + 1 + 175 + 1706 + 203 + 1746 + + + + + 红嘴鸥 + + 1 + 1 + 2895 + 2068 + 2971 + 2111 + + + + + 红嘴鸥 + + 1 + 1 + 1 + 1939 + 69 + 1993 + + + + + 红嘴鸥 + + 1 + 1 + 3407 + 1944 + 3429 + 1974 + + + + + 红嘴鸥 + + 1 + 1 + 1464 + 1765 + 1496 + 1803 + + + + + 红嘴鸥 + + 1 + 1 + 66 + 1720 + 92 + 1746 + + + + + 红嘴鸥 + + 1 + 1 + 2061 + 1886 + 2096 + 1915 + + + + + 红嘴鸥 + + 1 + 1 + 1064 + 2037 + 1103 + 2078 + + + + + 红嘴鸥 + + 1 + 1 + 932 + 1834 + 960 + 1865 + + + + + 红嘴鸥 + + 1 + 1 + 2882 + 2080 + 2916 + 2156 + + + + + 鸟 + + 1 + 1 + 695 + 1381 + 777 + 1474 + + + + + 红嘴鸥 + + 1 + 1 + 439 + 1728 + 466 + 1763 + + + + + 红嘴鸥 + + 1 + 1 + 643 + 1730 + 670 + 1768 + + + + + 鸟 + + 1 + 1 + 995 + 1729 + 1028 + 1783 + + + + + 红嘴鸥 + + 1 + 1 + 1031 + 1841 + 1062 + 1879 + + + + + 红嘴鸥 + + 1 + 1 + 2151 + 1879 + 2186 + 1919 + + + + + 红嘴鸥 + + 1 + 1 + 1111 + 2032 + 1174 + 2072 + + + + + 红嘴鸥 + + 1 + 1 + 3521 + 1878 + 3548 + 1909 + + + + + 红嘴鸥 + + 1 + 1 + 589 + 1738 + 616 + 1764 + + + + + 红嘴鸥 + + 1 + 1 + 831 + 2138 + 868 + 2160 + + + + + 红嘴鸥 + + 1 + 1 + 715 + 1739 + 743 + 1770 + + + + + 红嘴鸥 + + 1 + 1 + 3124 + 1855 + 3148 + 1886 + + + + + 红嘴鸥 + + 1 + 1 + 1125 + 1760 + 1155 + 1791 + + + + + 红嘴鸥 + + 1 + 1 + 1972 + 1796 + 1999 + 1826 + + + + + 红嘴鸥 + + 1 + 1 + 2385 + 1809 + 2412 + 1851 + + + + + 红嘴鸥 + + 1 + 1 + 2158 + 1804 + 2190 + 1842 + + + + + 红嘴鸥 + + 1 + 1 + 2697 + 1913 + 2728 + 1944 + + + + + 红嘴鸥 + + 1 + 1 + 1767 + 1875 + 1792 + 1901 + + + + + 红嘴鸥 + + 1 + 1 + 3800 + 1972 + 3830 + 2002 + + + + + 苍鹭 + + 1 + 1 + 411 + 1294 + 496 + 1452 + + + + + 苍鹭 + + 1 + 1 + 149 + 1247 + 238 + 1435 + + + + + 苍鹭 + + 1 + 1 + 2066 + 1412 + 2176 + 1581 + + + + + 苍鹭 + + 1 + 1 + 1611 + 1360 + 1712 + 1548 + + + + + 鸟 + + 1 + 1 + 1660 + 923 + 1716 + 992 + + + + + 苍鹭 + + 1 + 1 + 2216 + 815 + 2302 + 931 + + + + + 鸟 + + 1 + 1 + 1223 + 1022 + 1299 + 1057 + + + + + 鸟 + + 1 + 1 + 216 + 825 + 262 + 887 + + + + + 苍鹭 + + 1 + 1 + 3535 + 960 + 3602 + 1108 + + + + + 鸟 + + 1 + 1 + 40 + 823 + 132 + 878 + + + + + 红嘴鸥 + + 1 + 1 + 551 + 849 + 594 + 907 + + + + + 鸟 + + 1 + 1 + 2389 + 1134 + 2478 + 1174 + + + + + 鸟 + + 1 + 1 + 246 + 1159 + 321 + 1202 + + + + + 红嘴鸥 + + 1 + 1 + 1782 + 941 + 1846 + 996 + + + + + 苍鹭 + + 1 + 1 + 2848 + 913 + 2926 + 1063 + + + + + 红嘴鸥 + + 1 + 1 + 343 + 836 + 389 + 896 + + + + + 鸟 + + 1 + 1 + 2015 + 1108 + 2104 + 1155 + + + + + 鸟 + + 1 + 1 + 1059 + 1242 + 1149 + 1282 + + + + + 鸟 + + 1 + 1 + 1151 + 878 + 1203 + 948 + + + + + 鸟 + + 1 + 1 + 1192 + 1231 + 1264 + 1271 + + + + + 鸟 + + 1 + 1 + 720 + 1257 + 815 + 1302 + + + + + 鸟 + + 1 + 1 + 664 + 991 + 704 + 1024 + + + + + 鸟 + + 1 + 1 + 1062 + 1282 + 1183 + 1344 + + + + + 鸟 + + 1 + 1 + 1825 + 1326 + 1873 + 1374 + + + + + 鸟 + + 1 + 1 + 1220 + 1077 + 1260 + 1114 + + + + + 鸟 + + 1 + 1 + 1548 + 928 + 1597 + 975 + + + + + 鸟 + + 1 + 1 + 72 + 1195 + 202 + 1247 + + + + + 鸟 + + 1 + 1 + 439 + 839 + 517 + 896 + + + + + 鸟 + + 1 + 1 + 45 + 1104 + 119 + 1137 + + + + + 鸟 + + 1 + 1 + 1478 + 1125 + 1529 + 1158 + + + + + 红嘴鸥 + + 1 + 1 + 1325 + 903 + 1360 + 957 + + + + + 鸟 + + 1 + 1 + 1086 + 1106 + 1183 + 1146 + + + + + 鸟 + + 1 + 1 + 973 + 973 + 1054 + 1021 + + + + + 鸟 + + 1 + 1 + 1547 + 1274 + 1638 + 1320 + + + + + 鸟 + + 1 + 1 + 1013 + 881 + 1070 + 938 + + + + + 鸟 + + 1 + 1 + 1219 + 1295 + 1319 + 1349 + + + + + 鸟 + + 1 + 1 + 1658 + 1313 + 1723 + 1363 + + + + + 鸟 + + 1 + 1 + 8 + 1189 + 61 + 1243 + + + + + 鸟 + + 1 + 1 + 422 + 627 + 569 + 683 + + + + + 鸟 + + 1 + 1 + 172 + 1280 + 237 + 1325 + + + + + 鸟 + + 1 + 1 + 1359 + 1111 + 1458 + 1147 + + + + + 红嘴鸥 + + 1 + 1 + 678 + 874 + 755 + 921 + + + + + 鸟 + + 1 + 1 + 2304 + 893 + 2383 + 1029 + + + + + 鸟 + + 1 + 1 + 328 + 1269 + 399 + 1304 + + + + + 鸟 + + 1 + 1 + 412 + 1035 + 487 + 1069 + + + + + 鸟 + + 1 + 1 + 1230 + 1119 + 1301 + 1154 + + + + + 鸟 + + 1 + 1 + 1731 + 1378 + 1789 + 1421 + + + + + 鸟 + + 1 + 1 + 770 + 1149 + 829 + 1194 + + + + + 鸟 + + 1 + 1 + 1936 + 1177 + 2003 + 1216 + + + + + 鸟 + + 1 + 1 + 1573 + 1371 + 1694 + 1432 + + + + + 鸟 + + 1 + 1 + 926 + 990 + 991 + 1029 + + + + + 鸟 + + 1 + 1 + 2269 + 1146 + 2358 + 1187 + + + + + 鸟 + + 1 + 1 + 405 + 1161 + 446 + 1200 + + + + + 红嘴鸥 + + 1 + 1 + 3204 + 1019 + 3252 + 1074 + + + + + 红嘴鸥 + + 1 + 1 + 555 + 1051 + 653 + 1081 + + + + + 鸟 + + 1 + 1 + 1481 + 915 + 1540 + 968 + + + + + 鸟 + + 1 + 1 + 915 + 875 + 967 + 934 + + + + + 鸟 + + 1 + 1 + 1427 + 1304 + 1524 + 1361 + + + + + 鸟 + + 1 + 1 + 2508 + 1313 + 2578 + 1359 + + + + + 鸟 + + 1 + 1 + 2602 + 982 + 2650 + 1040 + + + + + 红嘴鸥 + + 1 + 1 + 0 + 826 + 48 + 874 + + + + + 红嘴鸥 + + 1 + 1 + 1239 + 898 + 1315 + 948 + + + + + 红嘴鸥 + + 1 + 1 + 546 + 797 + 600 + 830 + + + + + 鸟 + + 1 + 1 + 1872 + 1012 + 1947 + 1053 + + + + + 红嘴鸥 + + 1 + 1 + 68 + 759 + 120 + 797 + + + + + 鸟 + + 1 + 1 + 543 + 1000 + 575 + 1029 + + + + + 鸟 + + 1 + 1 + 1587 + 1016 + 1663 + 1045 + + + + + 鸟 + + 1 + 1 + 754 + 1051 + 806 + 1084 + + + + + 鸟 + + 1 + 1 + 831 + 981 + 915 + 1013 + + + + + 红嘴鸥 + + 1 + 1 + 1030 + 1119 + 1100 + 1147 + + + + + 鸟 + + 1 + 1 + 218 + 1037 + 284 + 1088 + + + + + 鸟 + + 1 + 1 + 695 + 1087 + 741 + 1122 + + + + + 鸟 + + 1 + 1 + 2362 + 1367 + 2455 + 1414 + + + + + 鸟 + + 1 + 1 + 474 + 1249 + 547 + 1289 + + + + + 鸟 + + 1 + 1 + 188 + 958 + 258 + 1012 + + + + + 鸟 + + 1 + 1 + 2680 + 1185 + 2734 + 1226 + + + + diff --git a/updated_excel_file.xlsx b/updated_excel_file.xlsx new file mode 100755 index 0000000..499aab9 Binary files /dev/null and b/updated_excel_file.xlsx differ diff --git a/vediotoima.py b/vediotoima.py index e184dbf..fd9d227 100755 --- a/vediotoima.py +++ b/vediotoima.py @@ -50,6 +50,9 @@ def vedio_img(input,output,fps): print('image of %s is saved' % (savedname)) if __name__ == '__main__': - filename = '../data_MPKFNet/rawdata/1_3.mp4' - savedpath = '../data_MPKFNet/result_raw/' + "2021.2.23" - vedio_img(filename,savedpath,1000) + filename = '/data3/DEMO/video/PYH/PYH_SHL001.mp4' + savedpath = '/data3/DEMO/images/PYH_SHL001' + os.system("sudo chmod 777 -R /data3/DEMO/") + if not os.path.exists(savedpath): + os.makedirs(savedpath) + vedio_img(filename,savedpath,1) diff --git a/vgg_baye.py b/vgg_baye.py new file mode 100755 index 0000000..753dc6e --- /dev/null +++ b/vgg_baye.py @@ -0,0 +1,95 @@ +import torch.nn as nn +import torch.utils.model_zoo as model_zoo +import torch +import os +from torch.nn import functional as F + +__all__ = ['vgg19'] +model_urls = { + 'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth', +} + +class VGG(nn.Module): + def __init__(self, features): + super(VGG, self).__init__() + self.features = features + self.reg_layer = nn.Sequential( + nn.Conv2d(512, 256, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(256, 128, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(128, 1, 1) + ) + # left_header + # self.left_header = nn.Sequential( + # nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1), + # nn.MaxPool2d(kernel_size=2, stride=2), + # nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1), + # nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1), + # nn.AvgPool2d(kernel_size=2, stride=2), + # nn.Flatten(), + # nn.Linear(18432, 1000), + # nn.Linear(1000, 5) + # ) + # # right_header + # self.right_header = nn.Sequential( + # nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1), + # nn.MaxPool2d(kernel_size=2, stride=2), + # nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1), + # nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1), + # nn.AvgPool2d(kernel_size=2, stride=2), + # nn.Flatten(), + # nn.Linear(18432, 1000), #512 - 32768 + # nn.Linear(1000, 13) + # ) + + def forward(self, x): + outputs = [] + # VGG19 outputs 0 + x = self.features(x) + outputs.append(x) + #with torch.no_grad(): + # left_header 1 posture + # x_left = self.left_header(x) + # outputs.append(x_left) + # # right_header 2 + # x_right = self.right_header(x) + # outputs.append(x_right) + # density outputs 3 + x = F.upsample_bilinear(x, scale_factor=2) + x = self.reg_layer(x) + outputs.append(torch.abs(x)) + return torch.abs(x) + +def make_layers(cfg, batch_norm=False): + layers = [] + in_channels = 3 + for v in cfg: + if v == 'M': + layers += [nn.MaxPool2d(kernel_size=2, stride=2)] + else: + conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) + if batch_norm: + layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] + else: + layers += [conv2d, nn.ReLU(inplace=True)] + in_channels = v + return nn.Sequential(*layers) + +cfg = { + 'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512] +} + +def vgg19(): + """VGG 19-layer model (configuration "E") + model pre-trained on ImageNet + """ + #make_layers(cfg['E']) + model = VGG(make_layers(cfg['E'])) + model.load_state_dict(model_zoo.load_url(model_urls['vgg19']), strict=False) + # checkpoint = torch.load('./Net_model_bird/0121-110701/115_ckpt.tar') + # model.load_state_dict(checkpoint['model_state_dict']) + # model.load_state_dict(torch.load(os.path.join('./Net_model_bird', '84_best_model.pth'))) + + return model + diff --git a/video2image.py b/video2image.py new file mode 100644 index 0000000..e69de29 diff --git a/videoCrop.py b/videoCrop.py new file mode 100755 index 0000000..93fd94c --- /dev/null +++ b/videoCrop.py @@ -0,0 +1,63 @@ +# -- coding: utf-8 -- +# @Time : 2023/2/08 14:58 +# @Author : Calvin +# @Email : 934055521@qq.com +# @File : videoCrop.py +# @use : +# @Software: VS Code + + +from tqdm import tqdm +import numpy as np +import cv2 +import os + + + +def longVideo_to_shortVideo(): + + for video in tqdm(os.listdir(video_folder_path), ncols=80, ascii=True, desc="Reading video"): + video_name = video.split('.')[0] + "_" + cap = cv2.VideoCapture(os.path.join(video_folder_path, video)) #获取视频(用绝对路径) + cap.isOpened() #判断视频是否能顺利打开读取,True为能打开,False为不能打开 + #获取视频信息 + width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) + height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) #获得视频帧宽和帧高 + if cap.isOpened(): # 当成功打开视频时cap.isOpened()返回True, 否则返回False + rate = cap.get(5) # cap.get()括号中的参数为5代表获取帧速率 + FrameNumber = int(cap.get(7)) # 获取视频文件的总帧数 + duration = FrameNumber/rate # 视频总帧数除以帧速率等于视频时间,除以60之后的单位就是分钟 + fps = int(25) # 每一段小视频帧数(我这个视频1秒钟的视频17帧),也用于后面的写入视频的帧速率 + success, frame = cap.read() + # cap.read() 返回一个布尔值给sucess(True/False)。如果帧读取的是正确的,就是True。所以最后你可以通过检查他的返回值来查看视频文件是否已经到了结尾。返回视频帧给frame + i = 0 + j = 0 + while (True): + success, frame = cap.read() + # cap.read()表示按帧读取视频,success,frame获得cap.read()的两个返回值 + # 其中success是布尔值,取帧是正确的则返回TRUE,如果文件读到结尾它的返回值就是False + # frame就是每一帧图像,是一个三维矩阵 + if success: + i += 1 + if (i % (15 * fps) == 1): # 每15秒保存一段小视频,每一秒的视频有17帧,这里一共保存了5秒(如果你想保存其他时长的视频,你只需要更改5这个数字) + # cap.read()按帧读取视频,每读取一帧,i就+1, + # 当读取到的帧数能整除每段小视频的帧数了,那就把视频保存下来 + j += 1 + videoWriter = cv2.VideoWriter(os.path.join(video_save_path, video_name + str(j) + '.mp4'), cv2.VideoWriter_fourcc('D', 'I', 'V', 'X'), fps, (int(width), int(height))) + # 分别是:保存文件名、编码器、帧率、视频宽高 + # 视频全部保存在了本代码所在的文件夹中,若你保存的小视频长度都为1秒,因为保存的是帧速率大小的帧图像,也就是每秒17帧的速率,就刚好保存了每秒17帧的小视频 + videoWriter.write(frame) # 写入帧图像 + else: + videoWriter.write(frame) + else: + print('end') + break + cap.release() #释放摄像头 + + +if __name__ == '__main__': + video_folder_path = "./" + video_save_path = video_folder_path.replace("Raw_LongVideo", "Res_ShortVideo") + if not os.path.isdir(video_save_path): + os.makedirs(video_save_path) + longVideo_to_shortVideo() # 长视频裁剪为15秒一段的短视频 \ No newline at end of file diff --git a/videoCrop.spec b/videoCrop.spec new file mode 100755 index 0000000..9601f64 --- /dev/null +++ b/videoCrop.spec @@ -0,0 +1,33 @@ +# -*- mode: python ; coding: utf-8 -*- + +block_cipher = None + + +a = Analysis(['videoCrop.py'], + pathex=['/data1/Hatcher/model/project/MPKFNet'], + binaries=[], + datas=[], + hiddenimports=[], + hookspath=[], + runtime_hooks=[], + excludes=[], + win_no_prefer_redirects=False, + win_private_assemblies=False, + cipher=block_cipher, + noarchive=False) +pyz = PYZ(a.pure, a.zipped_data, + cipher=block_cipher) +exe = EXE(pyz, + a.scripts, + a.binaries, + a.zipfiles, + a.datas, + [], + name='videoCrop', + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=True, + upx_exclude=[], + runtime_tmpdir=None, + console=True ) diff --git a/voc2coco.py b/voc2coco.py new file mode 100755 index 0000000..dbababc --- /dev/null +++ b/voc2coco.py @@ -0,0 +1,226 @@ +#!/usr/bin/python + +# pip install lxml +""" +需要先使用creat_coco_annotation.py生成 anno_train and anno_test 文件夹 +""" +import sys +import os +import json +import xml.etree.ElementTree as ET +import glob +import shutil +import cv2 +from tqdm import tqdm +from coco_visualization import checkCOCO +START_BOUNDING_BOX_ID = 1 +PRE_DEFINE_CATEGORIES = None +# If necessary, pre-define category and its id +# PRE_DEFINE_CATEGORIES = {"aeroplane": 1, "bicycle": 2, "bird": 3, "boat": 4, +# "bottle":5, "bus": 6, "car": 7, "cat": 8, "chair": 9, +# "cow": 10, "diningtable": 11, "dog": 12, "horse": 13, +# "motorbike": 14, "person": 15, "pottedplant": 16, +# "sheep": 17, "sofa": 18, "train": 19, "tvmonitor": 20} + + +def get(root, name): + vars = root.findall(name) + return vars + + +def get_and_check(root, name, length): + vars = root.findall(name) + if len(vars) == 0: + raise ValueError("Can not find %s in %s." % (name, root.tag)) + if length > 0 and len(vars) != length: + raise ValueError( + "The size of %s is supposed to be %d, but is %d." + % (name, length, len(vars)) + ) + if length == 1: + vars = vars[0] + return vars + + +def get_filename_as_int(filename): + try: + filename = filename.replace("\\", "/") + filename = os.path.splitext(os.path.basename(filename))[0] + return str(filename) + except: + raise ValueError("Filename %s is supposed to be an integer." % (filename)) + + +def get_categories(xml_files): + """Generate category name to id mapping from a list of xml files. + + Arguments: + xml_files {list} -- A list of xml file paths. + + Returns: + dict -- category name to id mapping. + """ + classes_names = [] + for xml_file in xml_files: + tree = ET.parse(xml_file) + root = tree.getroot() + for member in root.findall("object"): + classes_names.append(member[0].text) + classes_names = list(set(classes_names)) + classes_names.sort() + #return {name: i for i, name in enumerate(classes_names)} + return {"bird": 1} + + +def convert(rootpath,xml_files, json_file): + json_dict = {"images": [], "type": "instances", "annotations": [], "categories": []} + if PRE_DEFINE_CATEGORIES is not None: + categories = PRE_DEFINE_CATEGORIES + else: + categories = get_categories(xml_files) + bnd_id = START_BOUNDING_BOX_ID + for xml_file in xml_files: + tree = ET.parse(xml_file) + root = tree.getroot() + path = get(root, "path") + if len(path) == 1: + filename = os.path.basename(xml_file).replace(".xml","") + elif len(path) == 0: + filename = os.path.basename(xml_file).replace(".xml", "") + else: + raise ValueError("%d paths found in %s" % (len(path), xml_file)) + ## The filename must be a number + image_id = get_filename_as_int(filename) + try: + size = get_and_check(root, "size", 1) + width = int(get_and_check(size, "width", 1).text) + height = int(get_and_check(size, "height", 1).text) + except: + imgPath = os.path.join(rootpath,"JPEGImages","{}.jpg".format(str(filename))) + try: + img = cv2.imread(imgPath) + + except: + imgPath = os.path.join(rootpath,"JPEGImages","{}.png".format(str(filename))) + img = cv2.imread(imgPath) + + width =int(img.shape[1]) + height = int(img.shape[0]) + if not os.path.exists(os.path.join(rootpath,"JPEGImages","{}.jpg".format(str(filename)))): #图片里面既有jpg又有png + image = { + "file_name": "{}.png".format(filename), + "height": height, + "width": width, + "id": image_id, + } + else: + image = { + "file_name": "{}.jpg".format(filename), + "height": height, + "width": width, + "id": image_id, + } + json_dict["images"].append(image) + ## Currently we do not support segmentation. + # segmented = get_and_check(root, 'segmented', 1).text + # assert segmented == '0' + #print(filename) + for obj in get(root, "object"): + category = "bird"#get_and_check(obj, "name", 1).text + # if category not in categories: + # new_id = len(categories) + # categories[category] = new_id + category_id = categories[category] + bndbox = get_and_check(obj, "bndbox", 1) + xmin = int(get_and_check(bndbox, "xmin", 1).text) + ymin = int(get_and_check(bndbox, "ymin", 1).text) + xmax = int(get_and_check(bndbox, "xmax", 1).text) + ymax = int(get_and_check(bndbox, "ymax", 1).text) + assert xmax > xmin + assert ymax > ymin + o_width = abs(xmax - xmin) + o_height = abs(ymax - ymin) + ann = { + "area": o_width * o_height, + "iscrowd": 0, + "image_id": image_id, + "bbox": [xmin, ymin, o_width, o_height], + "category_id": category_id, + "id": bnd_id, + "ignore": 0, + "segmentation": [], + } + json_dict["annotations"].append(ann) + bnd_id = bnd_id + 1 + + for cate, cid in categories.items(): + cat = {"supercategory": "none", "id": cid, "name": cate} + json_dict["categories"].append(cat) + + os.makedirs(os.path.dirname(json_file), exist_ok=True) + json_fp = open(json_file, "w") + json_str = json.dumps(json_dict) + json_fp.write(json_str) + json_fp.close() +def data_pre(root): + xml_root = os.path.join(root,"ImageSets/Main/train.txt") + result_root = os.path.join(root,"COCO/Anno_train") + if not os.path.exists(result_root): + os.makedirs(result_root) + with open(xml_root) as f: + lines = f.readlines() + for line in tqdm(lines): + sourcePath = os.path.join(root,"Annotations","{}.xml".format(str(line).replace("\n",""))) + desPath = os.path.join(result_root,"{}.xml".format(str(line)).replace("\n","")) + shutil.copy(sourcePath,desPath) + print("train set is ok") + xml_root = os.path.join(root,"ImageSets/Main/test.txt") + result_root = os.path.join(root,"COCO/Anno_val") + if not os.path.exists(result_root): + os.makedirs(result_root) + with open(xml_root) as f: + lines = f.readlines() + for line in tqdm(lines): + sourcePath = os.path.join(root,"Annotations","{}.xml".format(str(line).replace("\n",""))) + desPath = os.path.join(result_root,"{}.xml".format(str(line)).replace("\n","")) + shutil.copy(sourcePath,desPath) + print("val set is ok") +if __name__ == "__main__": + #os.system("sudo chmod 777 -R /data/DataManagement/Project/CAS_ProjectBird/CDB_ProjectBird/") + #root = "/data/DataManagement/Project/CAS_ProjectBird/CDB_ProjectBird/" + #data_pre(root) + import argparse + + parser = argparse.ArgumentParser( + description="Convert Pascal VOC annotation to COCO format." + ) + parser.add_argument("root", default="/data4/Hatcher/smallobject/voc_class/CDB_airplane/",help="root", type=str) + + args = parser.parse_args() + root = args.root + jsonPath = os.path.join(root,"COCO/annotations") + if not os.path.exists(jsonPath): + os.makedirs(jsonPath) + jsonTrain = os.path.join(jsonPath,"train.json") + jsonval = os.path.join(jsonPath, "val.json") + result_root = os.path.join(root, "COCO/Anno_train") + + xml_files = glob.glob(os.path.join(result_root, "*.xml")) + # If you want to do train/val split, you can pass a subset of xml files to convert function. + print("Number of train xml files: {}".format(len(xml_files))) + convert(root,xml_files, jsonTrain) + print("train COCO is ok") + + result_root = os.path.join(root, "COCO/Anno_test") + xml_files = glob.glob(os.path.join(result_root, "*.xml")) + # If you want to do train/val split, you can pass a subset of xml files to convert function. + print("Number of val xml files: {}".format(len(xml_files))) + convert(root,xml_files, jsonval) + print("val COCO is ok") + if not os.path.join(root,"COCO/train"): + os.makedirs(os.path.join(root,"COCO/train")) + if not os.path.join(root,"COCO/val"): + os.makedirs(os.path.join(root,"COCO/val")) + os.system("ln -s {}/images/train {}/COCO/train".format(root,root)) + os.system("ln -s {}/images/test {}/COCO/val".format(root, root)) + checkCOCO(jsonTrain,"{}/COCO/train".format(root)) \ No newline at end of file