first
This commit is contained in:
1 parent
54ccfb11fe
commit
a0818377bb
194 files changed
+41635
-216
No files matched your search
+78
-20
@@ -9,20 +9,73 @@ import os
|
||||
import cv2
|
||||
import xml.dom.minidom
|
||||
from tqdm import tqdm
|
||||
|
||||
from lxml import etree
|
||||
image_path="./JPEGImages/"
|
||||
annotation_path="./Annatations/"
|
||||
annotation_path="/data/Hatcher/Fine_HC/anno_xml/"
|
||||
save_path ="./check/"
|
||||
num = 0
|
||||
files_name = os.listdir(image_path)
|
||||
files_name = os.listdir(annotation_path)
|
||||
class GEN_Annotations:
|
||||
def __init__(self, filename):
|
||||
self.root = etree.Element("annotation")
|
||||
|
||||
child1 = etree.SubElement(self.root, "folder")
|
||||
child1.text = "Hatcher"
|
||||
|
||||
child2 = etree.SubElement(self.root, "filename")
|
||||
child2.text = filename
|
||||
|
||||
child3 = etree.SubElement(self.root, "source")
|
||||
|
||||
child4 = etree.SubElement(child3, "annotation")
|
||||
child4.text = "MultiModel"
|
||||
child5 = etree.SubElement(child3, "database")
|
||||
child5.text = "Unknown"
|
||||
|
||||
child6 = etree.SubElement(child3, "image")
|
||||
child6.text = "flickr"
|
||||
child7 = etree.SubElement(child3, "flickrid")
|
||||
child7.text = "35435"
|
||||
|
||||
def set_size(self, witdh, height, channel):
|
||||
size = etree.SubElement(self.root, "size")
|
||||
widthn = etree.SubElement(size, "width")
|
||||
widthn.text = str(witdh)
|
||||
heightn = etree.SubElement(size, "height")
|
||||
heightn.text = str(height)
|
||||
channeln = etree.SubElement(size, "depth")
|
||||
channeln.text = str(channel)
|
||||
|
||||
def savefile(self, filename):
|
||||
tree = etree.ElementTree(self.root)
|
||||
tree.write(filename, pretty_print=True, xml_declaration=False, encoding='utf-8')
|
||||
|
||||
def add_pic_attr(self, label, xmin, ymin, xmax, ymax):
|
||||
object = etree.SubElement(self.root, "object")
|
||||
namen = etree.SubElement(object, "name")
|
||||
namen.text = label
|
||||
bndbox = etree.SubElement(object, "bndbox")
|
||||
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)
|
||||
|
||||
|
||||
def make_xml(image_path,shape0,shape1,x_left, y_left, x_right, y_right):
|
||||
|
||||
|
||||
print(image_path)
|
||||
print("\n")
|
||||
anno = GEN_Annotations(image_path)
|
||||
anno.set_size(shape0, shape1, 3)
|
||||
anno.add_pic_attr("bird", x_left, y_left, x_right, y_right)
|
||||
anno.savefile(image_path)
|
||||
for filename_ in tqdm(files_name):
|
||||
filename, extension= os.path.splitext(filename_)
|
||||
#filename=filename.split('__')[0]
|
||||
img_path =image_path+filename+'.jpg'
|
||||
xml_path =annotation_path+filename+'.xml'
|
||||
img = cv2.imread(img_path)
|
||||
if img is None:
|
||||
pass
|
||||
xml_path = os.path.join(annotation_path,filename_)
|
||||
try:
|
||||
dom = xml.dom.minidom.parse(xml_path)
|
||||
except:
|
||||
@@ -30,6 +83,10 @@ for filename_ in tqdm(files_name):
|
||||
continue
|
||||
root = dom.documentElement
|
||||
objects=dom.getElementsByTagName("object")
|
||||
shapes = dom.getElementsByTagName("size")
|
||||
for shape in shapes:
|
||||
width = shape.getElementsByTagName('width')[0].childNodes[0].data
|
||||
height = shape.getElementsByTagName('height')[0].childNodes[0].data
|
||||
for object in objects:
|
||||
bndbox = object.getElementsByTagName('bndbox')[0]
|
||||
xmin = bndbox.getElementsByTagName('xmin')[0]
|
||||
@@ -38,18 +95,19 @@ for filename_ in tqdm(files_name):
|
||||
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)
|
||||
xmin_data=int(float(xmin.childNodes[0].data.replace("tensor(","").replace(", device='cuda:0')","")))
|
||||
ymin_data=int(float(ymin.childNodes[0].data.replace("tensor(","").replace(", device='cuda:0')","")))
|
||||
xmax_data=int(float(xmax.childNodes[0].data.replace("tensor(","").replace(", device='cuda:0')","")))
|
||||
ymax_data=int(float(ymax.childNodes[0].data.replace("tensor(","").replace(", device='cuda:0')","")))
|
||||
label_name=object.getElementsByTagName('name')[0].childNodes[0].data
|
||||
cv2.rectangle(img,(xmin_data,ymin_data),(xmax_data,ymax_data),(55,255,155),1)
|
||||
num +=1
|
||||
cv2.putText(img,label_name,(xmin_data,ymin_data-3),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),2)
|
||||
# cv2.rectangle(img,(xmin_data,ymin_data),(xmax_data,ymax_data),(55,255,155),1)
|
||||
# num +=1
|
||||
# cv2.putText(img,label_name,(xmin_data,ymin_data-3),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,255,0),2)
|
||||
make_xml(xml_path, width, height, xmin_data, ymin_data, xmax_data, ymax_data)
|
||||
flag=0
|
||||
flag=cv2.imwrite(save_path+"{}.jpg".format(filename),img)
|
||||
if not (flag):
|
||||
print(filename,"error")
|
||||
# flag=cv2.imwrite(save_path+"{}.jpg".format(filename),img)
|
||||
# if not (flag):
|
||||
# print(filename,"error")
|
||||
print("all done ====================================")
|
||||
print("number = ",num)
|
||||
|
||||
|
||||
Executable
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -129,11 +129,11 @@ def inf(DensityEstimationResultPath,devices):
|
||||
with open (json_outputpath,'w',encoding='utf-8') as f:
|
||||
f.write(str(json_data))
|
||||
|
||||
# plt.figure(num_display)
|
||||
# plt.title("predict:{}".format(int(num_display)))
|
||||
# plt.imshow(targets_pred1[0, 0, :, :])
|
||||
# plt.savefig(DensityEstimationResultPath + "/" + str(img_pathtemp))
|
||||
# plt.close()
|
||||
plt.figure(num_display)
|
||||
plt.title("predict:{}".format(int(num_display)))
|
||||
plt.imshow(targets_pred1[0, 0, :, :])
|
||||
plt.savefig(DensityEstimationResultPath + "/" + str(img_pathtemp))
|
||||
plt.close()
|
||||
|
||||
i += 1
|
||||
|
||||
@@ -170,7 +170,7 @@ if __name__ == '__main__':
|
||||
help='Video name.')
|
||||
parser.add_argument("skip_getimg", default=False, type=str,
|
||||
help='skip_getimg.')
|
||||
parser.add_argument("GPU", default='0', type=str,
|
||||
parser.add_argument("GPU", default='6', type=str,
|
||||
help='GPU.')
|
||||
|
||||
parser.add_argument(
|
||||
@@ -195,7 +195,7 @@ if __name__ == '__main__':
|
||||
CombineVideoResultPath = '../data_MPKFNet/result_vedio/'+video_name_path+"desity.avi"
|
||||
print(args.skip_getimg)
|
||||
print(args.GPU)
|
||||
if not args.skip_getimg:
|
||||
if args.skip_getimg == "False":
|
||||
|
||||
vedio_img(RawVideoFilename, RawVideoExtrationSavedpath, 1)
|
||||
get_name = []
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
# -*- 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 = None # Density(gp.devices, root)
|
||||
self.DetectionClass = Detection_Y5(gp.devices, self.root)
|
||||
self.Fine_grianedClass = Fine_grained_T(gp.devices, self.root)
|
||||
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)
|
||||
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 = 2
|
||||
else:
|
||||
gp.fontScale = 1
|
||||
|
||||
|
||||
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/"
|
||||
DFS = DetFineVid(gp.VideoPath,SavePath)
|
||||
DFS.StartRec()
|
||||
DFS.conVideo()
|
||||
def filedeal(rootPath): #deal all file in a folder
|
||||
SavePath = "/data1/Hatcher/model/project/data_MPKFNet/result/"
|
||||
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 = "/data/DataManagement/Project/005_kunmingdianchi/0002_20220412_800_200/研究院-鱼视频/"
|
||||
filedeal(rootPath)
|
||||
#commanddeal()
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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'] = '2'
|
||||
os.environ['CUDA_VISIBLE_DEVICES'] = '3'
|
||||
|
||||
def parse_args():
|
||||
|
||||
@@ -39,10 +39,11 @@ def parse_args():
|
||||
help="path to config file",
|
||||
type=str,
|
||||
)
|
||||
parser.add_argument("--ckpt", type=str, default="../data_MPKFNet/weigth/detection/detection.pth",
|
||||
help="Trained weights.")
|
||||
#.../data_MPKFNet/weigth/detection/detection.pth
|
||||
# parser.add_argument("--ckpt", type=str, default="../data_MPKFNet/weigth/detection/weigth_all/detectionboyanghu.pth",
|
||||
#help="Trained weights.")
|
||||
parser.add_argument("--score_threshold", type=float, default=0.3)
|
||||
parser.add_argument("--video_name", default='000120210501080936.mp4', type=str, help='Video name.')
|
||||
parser.add_argument("video_name", default='YNhiv00016.mp4', type=str, help='Video name.')
|
||||
parser.add_argument("--images_dir", default='../data_MPKFNet/result_raw/yang/', type=str,
|
||||
help='Specify a image dir to do prediction.')
|
||||
parser.add_argument("--output_dir", default='../data_MPKFNet/result/yangd/', type=str,
|
||||
@@ -111,7 +112,7 @@ if __name__ == '__main__':
|
||||
args = parse_args()
|
||||
video_name_path = args.video_name
|
||||
video_name_path = video_name_path.replace(".MP4", "").replace(".mp4", "").replace(".MOV", "").replace(".mov", "")
|
||||
RawVideoFilename = '../data_MPKFNet/rawdata/1/'+args.video_name
|
||||
RawVideoFilename = '../data_MPKFNet/rawdata/'+args.video_name
|
||||
RawVideoExtrationSavedpath = '../data_MPKFNet/result_raw/' + video_name_path
|
||||
args.images_dir = '../data_MPKFNet/result_raw/' + video_name_path
|
||||
args.output_dir = "../data_MPKFNet/result/" + video_name_path + "Detection"
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,97 @@
|
||||
'''
|
||||
author £º Hatcher W
|
||||
Email£º hcwang@semi.ac.cn
|
||||
use: ÀûÓÃÄ¿±ê¼ì²â±ê×¢Êý¾Ý¼¯Éú³ÉϸÁ£¶Èʶ±ðÔ¤Êý¾Ý¼¯£¨Î´±ê×¢£©£¬½«Ä¿±ê¼ì²â±ê×¢µÄͼÏñ²Ã¼ôΪϸÁ£¶Èʶ±ðµÄ½á¹û
|
||||
input:Ä¿±ê¼ì²â±êÇ©Îļþ¸ù·¾¶ xml£¬Í¬Ä¿Â¼ÏÂÃæÓаüº¬ËùÓÐͼƬµÄJPEGImages·¾¶
|
||||
output£ºÊä³öËùÓеĽá¹ûͼƬµ½FineOrimages
|
||||
'''
|
||||
import xml.dom.minidom
|
||||
from tqdm import tqdm
|
||||
from glob import glob
|
||||
import cv2
|
||||
import os
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
from jpg import jpg
|
||||
|
||||
root_path = "/data/DataManagement/Project/005_kunmingdianchi/0002_20220412_800_200/Dataset/VOC00502/Annotations"
|
||||
class_name = ["Anser albifrons" ,"Fulica atra" ,"Leucogeranus leucogeranus" ,"Egretta garzetta","Platalea leucorodia" ,"Mergellus albellus" ,"Grus monacha" ,"Tringa ochropus" ,"Numenius arquata" ,"Anser indicus","Anas zonorhyncha","Ardea cinerea","Mareca strepera" ,"Mareca penelope" ,"Tadorna ferruginea","Ardea alba","Numenius madagascariensis" ,"Botaurus stellaris" ,"Ciconia boyciana" ,"Anser fabalis" ,"Recurvirostra avosetta" ,"Podiceps cristatus","Vanellus vanellus" ,"Aythya fuligula" ,"Tringa erythropus","Calidris alpina" ,"Ciconia nigra" ,"Gallinula chloropus","Porphyrio poliocephalus","Larus ridibundus" ,"Anser cygnoides" ,"Charadrius alexandrinusw" ,"Pluvialis squatarola" ,"Grus grus" ,"Anser anser" ,"Pluvialis fulva" ,"Charadrius dubius" ,"Anas crecca","Anas platyrhynchos","Spatula clypeata","Phalacrocorax carbo","Mergus merganser" ,"Tadorna tadorna" ,"Tringa nebulariaw","Bucephala clangula" ,"Gallinago gallinago" ,"Anser erythropus","Cygnus columbianus" ,"Ichthyaetus ichthyaetus","Anas acuta" ,"Ardea intermedia"]
|
||||
image_T = 100
|
||||
def cv2_crop(im, box):
|
||||
'''cv2ʵÏÖÀàËÆPILµÄ²Ã¼ô
|
||||
|
||||
:param im: ¼ÓÔØºÃµÄͼÏñ
|
||||
:param box: ²Ã¼ôµÄ¾ØÐΣ¬Ôª×é(left, upper, right, lower).
|
||||
'''
|
||||
return im.copy()[box[1]:box[3], box[0]:box[2], :]
|
||||
|
||||
def convert(size, box):
|
||||
dw = 1./size[0]
|
||||
dh = 1./size[1]
|
||||
x = (box[0] + box[1])/2.0
|
||||
y = (box[2] + box[3])/2.0
|
||||
w = box[1] - box[0]
|
||||
h = box[3] - box[2]
|
||||
x = x*dw
|
||||
w = w*dw
|
||||
y = y*dh
|
||||
h = h*dh
|
||||
return (x,y,w,h)
|
||||
num_count = 0
|
||||
#for xml_path in os.listdir(root_path):
|
||||
xml_files = glob(os.path.join(root_path,"*.xml"))
|
||||
print(os.path.join(root_path.replace("Annotations","JPEGImages")))
|
||||
#jpg(os.path.join(root_path.replace("anno","images"),xml_path.replace("xml","jpg")))
|
||||
f = open("./Hatcher_ALL.txt", "a")
|
||||
txt_lists = []
|
||||
if not os.path.exists(os.path.join(root_path.replace("Annotations","FineDataset_{}".format(str(image_T))))):
|
||||
os.makedirs(os.path.join(root_path.replace("Annotations","FineDataset_{}".format(str(image_T)))))
|
||||
for xml_file in tqdm(xml_files):
|
||||
|
||||
print(xml_file+" is doing")
|
||||
DOMTree = xml.dom.minidom.parse(xml_file)
|
||||
collection = DOMTree.documentElement
|
||||
#img_name = collection.getElementsByTagName("filename")[0].childNodes[0].data
|
||||
img_name = xml_file.replace("Annotations","JPEGImages").replace(".xml",".jpg")
|
||||
objects = collection.getElementsByTagName("object")
|
||||
#img = cv2.imread(img_name)
|
||||
img = cv2.imdecode(np.fromfile(img_name,dtype=np.uint8),-1)
|
||||
#cv2.imwrite(img_name,img)
|
||||
#img = cv2.imdecode(np.fromfile(img_name,dtype=np.uint8),-1)
|
||||
# im = Image.open(img_name)
|
||||
# im.save(img_name, quality=100)
|
||||
# im = Image.open(img_name)
|
||||
for object_id in objects:
|
||||
xmin = object_id.getElementsByTagName('bndbox')[0].getElementsByTagName('xmin')[0].childNodes[0].data
|
||||
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
|
||||
xmin = int(xmin)
|
||||
xmax = int(xmax)
|
||||
ymin = int(ymin)
|
||||
ymax = int(ymax)
|
||||
if ((xmax - xmin)<image_T) | ((ymax - ymin)<image_T):
|
||||
continue
|
||||
#class_index = class_name.index(str(name).replace("\t","").strip())
|
||||
img1 = cv2_crop(img,(xmin, ymin,xmax, ymax))
|
||||
cv2.imwrite(os.path.join(root_path.replace("Annotations","FineDataset_{}".format(str(image_T))),"{}.jpg".format(str(num_count).zfill(6))), img1)
|
||||
txt_lists.append("{}.jpg".format(str(num_count).zfill(6))+'\n')
|
||||
#f.write(str(name).replace("\t","").strip().replace(" ","_" )+"_{}.jpg".format(num_count)+" "+str(class_index)+'\n')
|
||||
num_count += 1
|
||||
for txt_list in txt_lists:
|
||||
f.write(txt_list)
|
||||
f.close()
|
||||
print(num_count)
|
||||
|
||||
|
||||
|
||||
|
||||
#######################
|
||||
|
||||
###Õë¶ÔÄ¿±ê¼ì²âÊý¾Ý¼¯Ö±½ÓÉú³ÉϸÁ£¶ÈÊý¾Ý¼¯
|
||||
|
||||
|
||||
##########################
|
||||
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ cap = cv2.VideoCapture(args.video_path)
|
||||
while (cap.isOpened()):
|
||||
ret,frame = cap.read()
|
||||
cv2.imshow('image',frame)
|
||||
k = cv2.waitKey(10)
|
||||
k = cv2.waitKey(0)
|
||||
if(k&0xff == ord('q')):
|
||||
break
|
||||
cap.release()
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import cv2
|
||||
from PIL import Image
|
||||
import os
|
||||
import matplotlib as plt
|
||||
def SemiLogoPaste(orimage,Logoimage,radio,image_path):#orimage:cv2 image:cv2
|
||||
or_W = orimage.size[0]
|
||||
or_H = orimage.size[1]
|
||||
#Logoimage = cv2.resize(Logoimage, (int(Logoimage.shape[1] * radio), int(Logoimage.shape[0] * radio)))
|
||||
#Logoimage = Image.fromarray(cv2.cvtColor(Logoimage, cv2.COLOR_BGR2RGB))
|
||||
Logo_W = Logoimage.shape[1]
|
||||
Logo_H = Logoimage.shape[0]
|
||||
for j in range(Logo_W):
|
||||
for i in range(Logo_H):
|
||||
if Logoimage[i][j][0]==Logoimage[i][j][1]==Logoimage[i][j][2]==255:
|
||||
Logoimage[i][j][0] = 0
|
||||
Logoimage[i][j][1] = 0
|
||||
Logoimage[i][j][2] = 0
|
||||
cv2.imshow("Logo",Logoimage)
|
||||
cv2.waitKey()
|
||||
x_right = int(or_W/20.0*19.0)
|
||||
y_right = int(or_H/10.0*9.5)
|
||||
x_left = x_right - Logo_W
|
||||
y_left = y_right - Logo_H
|
||||
orimage.paste(Logoimage, (x_left, y_left, x_right, y_right))
|
||||
orimage.save(image_path)
|
||||
if __name__ == '__main__':
|
||||
Logoimage = cv2.imread("/data1/Hatcher/model/MPKFNet/logo.png")
|
||||
orimage = Image.open("/data1/Hatcher/model/data_MPKFNet/data/VOC/VOCdevkit/VOC00401/check/0004_20220304_0001.jpg")
|
||||
SemiLogoPaste(orimage,Logoimage,1.5,"./LOGOresult.jpg")
|
||||
+902
-71
File diff suppressed because it is too large.
Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+27
-4
@@ -1,6 +1,5 @@
|
||||
# Plotting utils
|
||||
# !usr/bin/env python
|
||||
# -*- coding:utf-8 _*-
|
||||
|
||||
import glob
|
||||
import math
|
||||
import os
|
||||
@@ -16,12 +15,13 @@ 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
|
||||
@@ -55,7 +55,7 @@ def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
|
||||
return filtfilt(b, a, data) # forward-backward filter
|
||||
|
||||
|
||||
def plot_one_box(x, img, color=None, label=None, line_thickness=3):
|
||||
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)]
|
||||
@@ -67,8 +67,31 @@ def plot_one_box(x, img, color=None, label=None, line_thickness=3):
|
||||
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)
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
BIN
Binary file not shown.
@@ -0,0 +1,10 @@
|
||||
import os
|
||||
path = "/data1/GHM/data/VoiceRecognition/PaperUseData/VOT_CCPE_2/FinalDatasetVoice_3/test"
|
||||
file_list = os.listdir(path)
|
||||
num = 0
|
||||
for file_path in file_list:
|
||||
image_list = os.listdir(os.path.join(path,file_path))
|
||||
print("{} is {}".format(file_path,str(len(image_list))))
|
||||
if len(image_list) ==3:
|
||||
num+=1
|
||||
print(num)
|
||||
+4
-4
@@ -13,9 +13,9 @@ 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/"
|
||||
|
||||
files_name = os.listdir(image_path)
|
||||
for filename_ in tqdm(files_name):
|
||||
def _check_voc(image_path,annotation_path,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'
|
||||
@@ -49,6 +49,6 @@ for filename_ in tqdm(files_name):
|
||||
flag=cv2.imwrite(save_path+"{}.jpg".format(filename),img)
|
||||
if not (flag):
|
||||
print(filename,"error")
|
||||
print("all done ====================================")
|
||||
print("all done ====================================")
|
||||
|
||||
#(int((xmin_data+xmax_data/2)),int((ymin_data+ymax_data)/2))
|
||||
@@ -1,4 +1,4 @@
|
||||
#进入线程先把标志位置为True
|
||||
#½øÈëÏß³ÌÏȰѱê־λÖÃΪTrue
|
||||
# from System_I import Detection
|
||||
# import os,torch
|
||||
# os.environ['CUDA_VISIBLE_DEVICES'] = '1'
|
||||
@@ -6,39 +6,114 @@
|
||||
# root = "/home/wanghc/output"
|
||||
import os,torch, threading,argparse
|
||||
class global_para():
|
||||
parser1 = argparse.ArgumentParser(description="GYD")
|
||||
parser1.add_argument("video_num", default='0001', type=str,
|
||||
#check()
|
||||
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='5', type=str,
|
||||
parser1.add_argument("--GPU", default='6', type=str,
|
||||
help='GPU.')
|
||||
parser1.add_argument("thresh", default=0.6, type=float,
|
||||
parser1.add_argument("--thresh", default=0.4, type=float,
|
||||
help='GPU.')
|
||||
parser1.add_argument("red", default=0, type=int,
|
||||
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)
|
||||
red_flag = args.red
|
||||
detect_thresh = args.thresh
|
||||
is_ex_bird = False # 目标检测标志位,每个一秒检测一次目标检测,如果有鸟,则置为True,为True的时候说明, 处理30s的线程还在继续,直到标志位变为了False再开启新的线程
|
||||
Density_thread_flag = False # 密度估计线程标志位,为True说明开启了密度估计线程,处理完750帧为止,标志位标为False,
|
||||
Detection_thread_flag = False # 目标检测和细粒度识别线程标志位,为True说明开启了密度估计线程,处理完750帧为止,标志位标为False,
|
||||
Vedio_thread_flag = False # 存储视频线程标志位,存储30s
|
||||
SaveImage_thread_flag = False # 保存原图线程标志位,存储30张原图
|
||||
ALL_thread_flag = False # 所有线程的标志位,单独开设一个线程,监控所有线程是否都结束,如果都结束,则置为False,后续添加线程管理,可以放在这里面
|
||||
|
||||
DebugPrint_flag = True # 打印标志位
|
||||
|
||||
destory_image = False
|
||||
Camera_device = args.video_num # 摄像头编号,0001
|
||||
image_time = None # 当前处理的30视频的编号
|
||||
ImgDealQueue = [] # 750帧视频,缓存空间
|
||||
root = "/data/Hatcher/output2"
|
||||
#os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
||||
#print(args)
|
||||
root = "/home/gyd/output1"
|
||||
# os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
||||
os.environ['CUDA_VISIBLE_DEVICES'] = args.GPU
|
||||
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()
|
||||
is_ex_bird = False # Ä¿±ê¼ì²â±ê־λ£¬Ã¿¸öÒ»Ãë¼ì²âÒ»´ÎÄ¿±ê¼ì²â£¬Èç¹ûÓÐÄñ£¬ÔòÖÃΪTrue£¬ÎªTrueµÄʱºò˵Ã÷£¬ ´¦Àí30sµÄÏ̻߳¹ÔÚ¼ÌÐø£¬Ö±µ½±ê־λ±äΪÁËFalseÔÙ¿ªÆôеÄÏß³Ì
|
||||
Density_thread_flag = False # ÃܶȹÀ¼ÆÏ̱߳ê־λ£¬ÎªTrue˵Ã÷¿ªÆôÁËÃܶȹÀ¼ÆỊ̈߳¬´¦ÀíÍê750֡Ϊֹ£¬±ê־λ±êΪFalse£¬
|
||||
Detection_thread_flag = False # Ä¿±ê¼ì²âºÍϸÁ£¶Èʶ±ðÏ̱߳ê־λ£¬ÎªTrue˵Ã÷¿ªÆôÁËÃܶȹÀ¼ÆỊ̈߳¬´¦ÀíÍê750֡Ϊֹ£¬±ê־λ±êΪFalse£¬
|
||||
Vedio_thread_flag = False # ´æ´¢ÊÓÆµÏ̱߳ê־룬´æ´¢30s
|
||||
SaveImage_thread_flag = False # ±£´æÔͼÏ̱߳ê־룬´æ´¢30ÕÅÔͼ
|
||||
ALL_thread_flag = False # ËùÓÐÏ̵߳ıê־룬µ¥¶À¿ªÉèÒ»¸öỊ̈߳¬¼à¿ØËùÓÐÏß³ÌÊÇ·ñ¶¼½áÊø£¬Èç¹û¶¼½áÊø£¬ÔòÖÃΪFalse£¬ºóÐøÌí¼ÓÏ̹߳ÜÀí£¬¿ÉÒÔ·ÅÔÚÕâÀïÃæ
|
||||
|
||||
ShowAllNumFlag = False
|
||||
|
||||
|
||||
DebugPrint_flag = False # ´òÓ¡±ê־λ
|
||||
Species = torch.zeros(8).cuda()
|
||||
num_count_old =0
|
||||
boxes_fine = None
|
||||
labels_fine = None
|
||||
|
||||
showThresh = 25
|
||||
destory_image = False
|
||||
Camera_device = args.video_num # ÉãÏñÍ·±àºÅ£¬0001
|
||||
image_time = None # µ±Ç°´¦ÀíµÄ30ÊÓÆµµÄ±àºÅ
|
||||
ImgDealQueue = [] # 750Ö¡ÊÓÆµ£¬»º´æ¿Õ¼ä
|
||||
img_show = None
|
||||
|
||||
|
||||
#event = threading.Event()
|
||||
eventDensity = threading.Event()
|
||||
eventDetection = threading.Event()
|
||||
eventSaveimage = threading.Event()
|
||||
max_age = 2
|
||||
min_hits = 3
|
||||
sortiou_threshold = 0.3
|
||||
Finerestartboxes = []
|
||||
IndexMax = 0
|
||||
radioShowX = 2560.0
|
||||
radioShowY = 1440.0
|
||||
radioShowtext = radioShowX
|
||||
SortLabel_Index = None #±êÇ©ºÍË÷Òý¶ÔÓ¦¹ØÏµ[[4,1],[3,2]]
|
||||
SortLabel_Indexpre = [] #±êÇ©ºÍË÷ÒýµÄ¶ÔÓ¦¹ØÏµ£¬ÓÃÔÚ×·×Ù¹ý³ÌÖÐгöÏÖµÄÄ¿±ê£¬[[label,Index,Count]]
|
||||
# Detection2 = Detection(devices,root)
|
||||
FineCountThresh = 5
|
||||
|
||||
img_show = None
|
||||
|
||||
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"
|
||||
DetWeight = "/data1/Hatcher/model/Detection/yolov5/runs/train/KunMingCuiHu-Fish2/weights/best.pt"
|
||||
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","鲫鱼","麦穗鱼","鳑鲏"]
|
||||
BHG_chineseName = ["kong","鲫鱼","麦穗鱼","鳑鲏"]
|
||||
|
||||
# BHG_chineseName = ['Kong', '白额雁', '白骨顶', '苍鹭', '苍鹭', '白秋沙鸭', '白腰草鹬', '斑头雁', '斑嘴鸭', '苍鹭', '赤膀鸭', '赤颈鸭', '苍鹭', '大麻鳽',
|
||||
# '豆雁', '反嘴鹬', '凤头鸊鷉', '凤头麦鸡', '凤头潜鸭', '黑鹳', '黑水鸡', '红嘴鸥', '鸿雁', '灰鹤', '灰雁', '绿翅鸭', '绿头鸭', '琵嘴鸭',
|
||||
# '普通鸬鹚', '普通秋沙鸭', '翘鼻麻鸭', '鹊鸭', '扇尾沙锥', '小白额雁', '小天鹅', '针尾鸭', '苍鹭', '暗绿绣眼鸟', '八哥', '白腹鹞', '白鹡鸰',
|
||||
# '白眼潜鸭', '草鹭', '池鹭', '戴胜', '黑翅长脚鹬', '黑鸢', '红隼', '花脸鸭', '环颈雉', '灰头绿啄木鸟', '灰头麦鸡', '矶鹬', '栗苇鳽',
|
||||
# '罗纹鸭', '牛背鹭', '普通翠鸟', '雀鹰', '喜鹊', '苍鹭', '鸳鸯', '棕背伯劳', '红胸秋沙鸭', '普通燕鸥', '小白额燕鸥', '丘鹬', '凤头蜂鹰',
|
||||
# '大天鹅', '大鸨', '小田鸡', '山斑鸠', '帆背潜鸭', '日本松雀鹰', '普通鵟', '松雀鹰', '毛脚鵟', '灰斑鸠', '白头鹞', '白尾鹞', '白眉鸭',
|
||||
# '白鹈鹕', '红头潜鸭', '苍鹰', '蒙古银鸥', '西方秧鸡', '赤嘴潜鸭', '阔嘴鹬', '雕鸮', '鹌鹑', '鹗', '黄苇鳽', '黑颈鹤', '小䴙䴘', '赤麻鸭']
|
||||
# BHG_chineseName =["kong","绿头鸭","斑嘴鸭","灰雁","鸿雁","kong","小鷿鷈"]
|
||||
spiec_number_old = [0 for i in range(len(BHG_chineseName))]
|
||||
FineClassNum = 4
|
||||
color_show = (255, 255, 255)
|
||||
color_box = (255, 0, 0)
|
||||
NoneLabel = "鱼" # "鹤类"
|
||||
fine_thresh1 = 6000
|
||||
fine_thresh2 = 10000
|
||||
fontScale = 1
|
||||
"""
|
||||
1.change weight
|
||||
2.change BHG_chineseName
|
||||
3.change FineClassNum
|
||||
4.change color_box (0, 115, 51)green (255, 0, 0) red
|
||||
5.change parser1
|
||||
6.change NoneLabel
|
||||
7. change main
|
||||
8. change fine_thresh2
|
||||
9. GPU
|
||||
fontScale plot file para to adjust chinese 400W ---2
|
||||
200W ---1
|
||||
800W ---3
|
||||
"""
|
||||
+5
-3
@@ -1,7 +1,8 @@
|
||||
import os
|
||||
import cv2
|
||||
root_path = "/data1/Hatcher/model/data_MPKFNet/con/FFOutput(1)/"
|
||||
result_path = "/data1/Hatcher/model/data_MPKFNet/con/result/"
|
||||
root_path = "/data/Hatcher/con/8227/"
|
||||
result_path = "/data/Hatcher/con/result/"
|
||||
site = [[20,20,110,103],[111,20 , 225,103],[264,20 , 396,103],[416,20 , 550,103],[552,20 , 690,103],[720,20 , 850,103],[872,20 , 1000,103]]
|
||||
if not os.path.exists(result_path):
|
||||
os.mkdir(result_path)
|
||||
file_list = os.listdir(root_path)
|
||||
@@ -11,6 +12,7 @@ for file_path in file_list:
|
||||
for image_path in image_list:
|
||||
print(image_path)
|
||||
img = cv2.imread(os.path.join(os.path.join(root_path,file_path),image_path))
|
||||
Img = img.copy()[20:96, 806:903, :]
|
||||
for site_1 in site:
|
||||
Img = img.copy()[site_1[1]:site_1[3], site_1[0]:site_1[2], :]
|
||||
cv2.imwrite(os.path.join(result_path,"{}.jpg".format(str(num).zfill(4))),Img)
|
||||
num+=1
|
||||
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Binary file not shown.
@@ -3,12 +3,12 @@ import numpy as np
|
||||
import os
|
||||
import json
|
||||
import argparse
|
||||
dataset_name = "BirdCounting1"
|
||||
root_path ="../data_MPKFNet/data/BirdCounting"
|
||||
|
||||
dataset_name = "birdCounting6"
|
||||
#root_path ="../data_MPKFNet/data/BirdCounting"
|
||||
root_path ="/data1/zwq/Upload/tiaozini/"
|
||||
|
||||
parser = argparse.ArgumentParser(description="DensityVideodemo.")
|
||||
parser.add_argument("dataset_name", default='', type=str,
|
||||
parser.add_argument("--dataset_name", default='birdCounting6', type=str,
|
||||
help='Video name.')
|
||||
|
||||
parser.add_argument(
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import time
|
||||
|
||||
import cv2
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import numpy as np
|
||||
from common import global_para as gp
|
||||
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)
|
||||
# while(1):
|
||||
# frame = cv2.imread("/data1/Hatcher/model/data_MPKFNet/result/hiv00024Detection/0000001.jpg")
|
||||
# frame=cv2AddChineseText(frame,"ÊýÁ¿", (123, 123),(0, 255, 0), 30)
|
||||
# cv2.imshow('capture',frame)
|
||||
# if cv2.waitKey(1) & 0xFF == ord('q'):
|
||||
# break
|
||||
+2
-2
@@ -9,8 +9,8 @@ import numpy as np
|
||||
import cv2
|
||||
from scipy.io import loadmat
|
||||
import json
|
||||
from configs.config import *
|
||||
from configs.config import model_head
|
||||
from configs.configs import *
|
||||
from configs.configs import model_head
|
||||
import matplotlib.pyplot as plt
|
||||
import torch
|
||||
|
||||
|
||||
+191
-40
@@ -26,11 +26,12 @@ 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'] = '7'
|
||||
os.environ['CUDA_VISIBLE_DEVICES'] = '3'
|
||||
from PIL import ImageFile
|
||||
import time
|
||||
import cv2
|
||||
import torch,os
|
||||
from torch import nn
|
||||
import numpy as np
|
||||
from numpy import random
|
||||
import os,sys
|
||||
@@ -41,8 +42,19 @@ 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
|
||||
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
||||
fine_class_names = ("Anser albifrons","Fulica atra","Leucogeranus leucogeranus","Egretta garzetta","Platalea leucorodia","Mergus albellus","Grus monacha","Tringa ochropus","Numenius arquata","Anser indicus","Anas zonorhyncha","Ardea cinerea","Anas strepera","Mareca penelope","Tadorna ferruginea","Ardea alba","Numenius madagascariensis","Botaurus stellaris","Ciconia boyciana","Anser fabalis","Recurvirostra avosetta","Podiceps cristatus","Vanellus vanellus","Aythya fuligula","Tringa erythropus","Calidris alpina","Ciconia nigra","Gallinula chloropus","Porphyrio poliocephalus","Larus ridibundus","Anser cygnoides","Charadrius alexandrinus","Pluvialis squatarola","Grus grus" ,"Anser anser","Pluvialis fulva","Charadrius dubius","Anas crecca","Anas platyrhynchos","Spatula clypeata","Phalacrocorax carbo","Mergus merganser","Tadorna tadorna","Tringa nebulariaw","Bucephala clangula","Gallinago gallinago","Anser erythropus","Cygnus columbianus","Ichthyaetus ichthyaetus","Anas acuta","Ardea intermedia","Lalage melaschistos","Zosterops japonicus","Acridotheres cristatellus","Circus spilonotus","Motacilla alba","Garrulax sannio","Pycnonotus sinensis","Aythya nyroca","Lonchura striata","Turdus eunomus","Limosa lapponica","Lonchura punctulata","Phoenicurus auroreus","Ardea purpurea","Aethopyga christinae","Ardeola bacchus","Prinia inornata","Cuculus canorus","Parus major","Upupa epops","Asio fiammeus","Anthus roseatus","Phylloscopus reguloides","Phylloscopus fuscatus","Himantopus himantopus","Saxicola torquata","Dicrurus macrocercus","Eophona migratoria","Milvus migrans","Oriolus chinensis","Anthus cervinus","Falco tinnunculus","Stachyris ruficeps","Aegithalos concinnus","Turdus naumanni","Urocissa erythrorhyncha","Sibirionetta formosa","Phasianus colchicus","Anthus rubescens","Parus venustulus","Motacilla citreola","Emberiza aureola","Motacilla cinerea","Sturnus cineraceus","Picus canus","Vanellus cinereus","Emberiza spodocephala","Bambusicola thoracicus","Streptopelia tranquebarica","Actitis hypoleucos","Hirundo rustica","Carduelis sinica","Hirundo daurica","Luscinia svecicus","Monticola solitarius","Anthus richardi","Ixobrychus cinnamomeus","Spizixos semitorques","Mareca falcata","Parus monticolus","Passer montanus","Bubulcus coromandus","Turdus merula","Buteo buteo","Alcedo atthis","Horornis fortipes","Accipiter nisus","Copsychus saularis","Circus melanoleucos","Anthus hodgsoni","Anthus spinoletta","Spodiopsar sericeus","Cuculus micropterus","Motacilla flava","Pica pica","Tachybaptus ruficollis","Emberiza pusilla","Alauda gulgula","Lanius sphenocercus","Riparia riparia","Nycticorax nycticorax","Terpsiphone paradisi","Cuculus sparverioides","Falco Peregrinus","Aix galericulata","Charadrius placidus","Gallinago stenura","Mergus squamatus","Spilopelia chinensis","Lanius schach","Pomatorhinus ruficollis","Abroscopus albogularis","Turnix suscitator","Cisticola juncidis","Paradoxornis webbianus")
|
||||
from cv2AddChineseText import cv2AddChineseText
|
||||
#fine_class_names = ("Anser albifrons","Fulica atra","Leucogeranus leucogeranus","Egretta garzetta","Platalea leucorodia","Mergus albellus","Grus monacha","Tringa ochropus","Numenius arquata","Anser indicus","Anas zonorhyncha","Ardea cinerea","Anas strepera","Mareca penelope","Tadorna ferruginea","Ardea alba","Numenius madagascariensis","Botaurus stellaris","Ciconia boyciana","Anser fabalis","Recurvirostra avosetta","Podiceps cristatus","Vanellus vanellus","Aythya fuligula","Tringa erythropus","Calidris alpina","Ciconia nigra","Gallinula chloropus","Porphyrio poliocephalus","Larus ridibundus","Anser cygnoides","Charadrius alexandrinus","Pluvialis squatarola","Grus grus" ,"Anser anser","Pluvialis fulva","Charadrius dubius","Anas crecca","Anas platyrhynchos","Spatula clypeata","Phalacrocorax carbo","Mergus merganser","Tadorna tadorna","Tringa nebulariaw","Bucephala clangula","Gallinago gallinago","Anser erythropus","Cygnus columbianus","Ichthyaetus ichthyaetus","Anas acuta","Ardea intermedia","Lalage melaschistos","Zosterops japonicus","Acridotheres cristatellus","Circus spilonotus","Motacilla alba","Garrulax sannio","Pycnonotus sinensis","Aythya nyroca","Lonchura striata","Turdus eunomus","Limosa lapponica","Lonchura punctulata","Phoenicurus auroreus","Ardea purpurea","Aethopyga christinae","Ardeola bacchus","Prinia inornata","Cuculus canorus","Parus major","Upupa epops","Asio fiammeus","Anthus roseatus","Phylloscopus reguloides","Phylloscopus fuscatus","Himantopus himantopus","Saxicola torquata","Dicrurus macrocercus","Eophona migratoria","Milvus migrans","Oriolus chinensis","Anthus cervinus","Falco tinnunculus","Stachyris ruficeps","Aegithalos concinnus","Turdus naumanni","Urocissa erythrorhyncha","Sibirionetta formosa","Phasianus colchicus","Anthus rubescens","Parus venustulus","Motacilla citreola","Emberiza aureola","Motacilla cinerea","Sturnus cineraceus","Picus canus","Vanellus cinereus","Emberiza spodocephala","Bambusicola thoracicus","Streptopelia tranquebarica","Actitis hypoleucos","Hirundo rustica","Carduelis sinica","Hirundo daurica","Luscinia svecicus","Monticola solitarius","Anthus richardi","Ixobrychus cinnamomeus","Spizixos semitorques","Mareca falcata","Parus monticolus","Passer montanus","Bubulcus coromandus","Turdus merula","Buteo buteo","Alcedo atthis","Horornis fortipes","Accipiter nisus","Copsychus saularis","Circus melanoleucos","Anthus hodgsoni","Anthus spinoletta","Spodiopsar sericeus","Cuculus micropterus","Motacilla flava","Pica pica","Tachybaptus ruficollis","Emberiza pusilla","Alauda gulgula","Lanius sphenocercus","Riparia riparia","Nycticorax nycticorax","Terpsiphone paradisi","Cuculus sparverioides","Falco Peregrinus","Aix galericulata","Charadrius placidus","Gallinago stenura","Mergus squamatus","Spilopelia chinensis","Lanius schach","Pomatorhinus ruficollis","Abroscopus albogularis","Turnix suscitator","Cisticola juncidis","Paradoxornis webbianus")
|
||||
#CUB fine_class_names = ['kong','Black_Footed_Albatross', 'Laysan_Albatross', 'Sooty_Albatross', 'Groove_Billed_Ani', 'Crested_Auklet', 'Least_Auklet', 'Parakeet_Auklet', 'Rhinoceros_Auklet', 'Brewer_Blackbird', 'Red_Winged_Blackbird', 'Rusty_Blackbird', 'Yellow_Headed_Blackbird', 'Bobolink', 'Indigo_Bunting', 'Lazuli_Bunting', 'Painted_Bunting', 'Cardinal', 'Spotted_Catbird', 'Gray_Catbird', 'Yellow_Breasted_Chat', 'Eastern_Towhee', 'Chuck_Will_Widow', 'Brandt_Cormorant', 'Red_Faced_Cormorant', 'Pelagic_Cormorant', 'Bronzed_Cowbird', 'Shiny_Cowbird', 'Brown_Creeper', 'American_Crow', 'Fish_Crow', 'Black_Billed_Cuckoo', 'Mangrove_Cuckoo', 'Yellow_Billed_Cuckoo', 'Gray_Crowned_Rosy_Finch', 'Purple_Finch', 'Northern_Flicker', 'Acadian_Flycatcher', 'Great_Crested_Flycatcher', 'Least_Flycatcher', 'Olive_Sided_Flycatcher', 'Scissor_Tailed_Flycatcher', 'Vermilion_Flycatcher', 'Yellow_Bellied_Flycatcher', 'Frigatebird', 'Northern_Fulmar', 'Gadwall', 'American_Goldfinch', 'European_Goldfinch', 'Boat_Tailed_Grackle', 'Eared_Grebe', 'Horned_Grebe', 'Pied_Billed_Grebe', 'Western_Grebe', 'Blue_Grosbeak', 'Evening_Grosbeak', 'Pine_Grosbeak', 'Rose_Breasted_Grosbeak', 'Pigeon_Guillemot', 'California_Gull', 'Glaucous_Winged_Gull', 'Heermann_Gull', 'Herring_Gull', 'Ivory_Gull', 'Ring_Billed_Gull', 'Slaty_Backed_Gull', 'Western_Gull', 'Anna_Hummingbird', 'Ruby_Throated_Hummingbird', 'Rufous_Hummingbird', 'Green_Violetear', 'Long_Tailed_Jaeger', 'Pomarine_Jaeger', 'Blue_Jay', 'Florida_Jay', 'Green_Jay', 'Dark_Eyed_Junco', 'Tropical_Kingbird', 'Gray_Kingbird', 'Belted_Kingfisher', 'Green_Kingfisher', 'Pied_Kingfisher', 'Ringed_Kingfisher', 'White_Breasted_Kingfisher', 'Red_Legged_Kittiwake', 'Horned_Lark', 'Pacific_Loon', 'Mallard', 'Western_Meadowlark', 'Hooded_Merganser', 'Red_Breasted_Merganser', 'Mockingbird', 'Nighthawk', 'Clark_Nutcracker', 'White_Breasted_Nuthatch', 'Baltimore_Oriole', 'Hooded_Oriole', 'Orchard_Oriole', 'Scott_Oriole', 'Ovenbird', 'Brown_Pelican', 'White_Pelican', 'Western_Wood_Pewee', 'Sayornis', 'American_Pipit', 'Whip_Poor_Will', 'Horned_Puffin', 'Common_Raven', 'White_Necked_Raven', 'American_Redstart', 'Geococcyx', 'Loggerhead_Shrike', 'Great_Grey_Shrike', 'Baird_Sparrow', 'Black_Throated_Sparrow', 'Brewer_Sparrow', 'Chipping_Sparrow', 'Clay_Colored_Sparrow', 'House_Sparrow', 'Field_Sparrow', 'Fox_Sparrow', 'Grasshopper_Sparrow', 'Harris_Sparrow', 'Henslow_Sparrow', 'Le_Conte_Sparrow', 'Lincoln_Sparrow', 'Nelson_Sharp_Tailed_Sparrow', 'Savannah_Sparrow', 'Seaside_Sparrow', 'Song_Sparrow', 'Tree_Sparrow', 'Vesper_Sparrow', 'White_Crowned_Sparrow', 'White_Throated_Sparrow', 'Cape_Glossy_Starling', 'Bank_Swallow', 'Barn_Swallow', 'Cliff_Swallow', 'Tree_Swallow', 'Scarlet_Tanager', 'Summer_Tanager', 'Artic_Tern', 'Black_Tern', 'Caspian_Tern', 'Common_Tern', 'Elegant_Tern', 'Forsters_Tern', 'Least_Tern', 'Green_Tailed_Towhee', 'Brown_Thrasher', 'Sage_Thrasher', 'Black_Capped_Vireo', 'Blue_Headed_Vireo', 'Philadelphia_Vireo', 'Red_Eyed_Vireo', 'Warbling_Vireo', 'White_Eyed_Vireo', 'Yellow_Throated_Vireo', 'Bay_Breasted_Warbler', 'Black_And_White_Warbler', 'Black_Throated_Blue_Warbler', 'Blue_Winged_Warbler', 'Canada_Warbler', 'Cape_May_Warbler', 'Cerulean_Warbler', 'Chestnut_Sided_Warbler', 'Golden_Winged_Warbler', 'Hooded_Warbler', 'Kentucky_Warbler', 'Magnolia_Warbler', 'Mourning_Warbler', 'Myrtle_Warbler', 'Nashville_Warbler', 'Orange_Crowned_Warbler', 'Palm_Warbler', 'Pine_Warbler', 'Prairie_Warbler', 'Prothonotary_Warbler', 'Swainson_Warbler', 'Tennessee_Warbler', 'Wilson_Warbler', 'Worm_Eating_Warbler', 'Yellow_Warbler', 'Northern_Waterthrush', 'Louisiana_Waterthrush', 'Bohemian_Waxwing', 'Cedar_Waxwing', 'American_Three_Toed_Woodpecker', 'Pileated_Woodpecker', 'Red_Bellied_Woodpecker', 'Red_Cockaded_Woodpecker', 'Red_Headed_Woodpecker', 'Downy_Woodpecker', 'Bewick_Wren', 'Cactus_Wren', 'Carolina_Wren', 'House_Wren', 'Marsh_Wren', 'Rock_Wren', 'Winter_Wren', 'Common_Yellowthroat']
|
||||
CUB_CUIfine_class_names = ['kong','Black_Footed_Albatross', 'Laysan_Albatross', 'Sooty_Albatross', 'Groove_Billed_Ani', 'Crested_Auklet', 'Least_Auklet', 'Parakeet_Auklet', 'Rhinoceros_Auklet', 'Brewer_Blackbird', 'Red_Winged_Blackbird', 'Rusty_Blackbird', 'Yellow_Headed_Blackbird', 'Bobolink', 'Indigo_Bunting', 'Lazuli_Bunting', 'Painted_Bunting', 'Cardinal', 'Spotted_Catbird', 'Gray_Catbird', 'Yellow_Breasted_Chat', 'Eastern_Towhee', 'Chuck_Will_Widow', 'Brandt_Cormorant', 'Red_Faced_Cormorant', 'Pelagic_Cormorant', 'Bronzed_Cowbird', 'Shiny_Cowbird', 'Brown_Creeper', 'American_Crow', 'Fish_Crow', 'Black_Billed_Cuckoo', 'Mangrove_Cuckoo', 'Yellow_Billed_Cuckoo', 'Gray_Crowned_Rosy_Finch', 'Purple_Finch', 'Northern_Flicker', 'Acadian_Flycatcher', 'Great_Crested_Flycatcher', 'Least_Flycatcher', 'Olive_Sided_Flycatcher', 'Scissor_Tailed_Flycatcher', 'Vermilion_Flycatcher', 'Yellow_Bellied_Flycatcher', 'Frigatebird', 'Northern_Fulmar', 'Gadwall', 'American_Goldfinch', 'European_Goldfinch', 'Boat_Tailed_Grackle', 'Eared_Grebe', 'Horned_Grebe', 'Pied_Billed_Grebe', 'Western_Grebe', 'Blue_Grosbeak', 'Evening_Grosbeak', 'Pine_Grosbeak', 'Rose_Breasted_Grosbeak', 'Pigeon_Guillemot', 'California_Gull', 'Glaucous_Winged_Gull', 'Heermann_Gull', 'Herring_Gull', 'Ivory_Gull', 'Ring_Billed_Gull', 'Slaty_Backed_Gull', 'Western_Gull', 'Anna_Hummingbird', 'Ruby_Throated_Hummingbird', 'Rufous_Hummingbird', 'Green_Violetear', 'Long_Tailed_Jaeger', 'Pomarine_Jaeger', 'Blue_Jay', 'Florida_Jay', 'Green_Jay', 'Dark_Eyed_Junco', 'Tropical_Kingbird', 'Gray_Kingbird', 'Belted_Kingfisher', 'Green_Kingfisher', 'Pied_Kingfisher', 'Ringed_Kingfisher', 'White_Breasted_Kingfisher', 'Red_Legged_Kittiwake', 'Horned_Lark', 'Pacific_Loon', 'Mallard', 'Western_Meadowlark', 'Hooded_Merganser', 'Red_Breasted_Merganser', 'Mockingbird', 'Nighthawk', 'Clark_Nutcracker', 'White_Breasted_Nuthatch', 'Baltimore_Oriole', 'Hooded_Oriole', 'Orchard_Oriole', 'Scott_Oriole', 'Ovenbird', 'Brown_Pelican', 'White_Pelican', 'Western_Wood_Pewee', 'Sayornis', 'American_Pipit', 'Whip_Poor_Will', 'Horned_Puffin', 'Common_Raven', 'White_Necked_Raven', 'American_Redstart', 'Geococcyx', 'Loggerhead_Shrike', 'Great_Grey_Shrike', 'Baird_Sparrow', 'Black_Throated_Sparrow', 'Brewer_Sparrow', 'Chipping_Sparrow', 'Clay_Colored_Sparrow', 'House_Sparrow', 'Field_Sparrow', 'Fox_Sparrow', 'Grasshopper_Sparrow', 'Harris_Sparrow', 'Henslow_Sparrow', 'Le_Conte_Sparrow', 'Lincoln_Sparrow', 'Nelson_Sharp_Tailed_Sparrow', 'Savannah_Sparrow', 'Seaside_Sparrow', 'Song_Sparrow', 'Tree_Sparrow', 'Vesper_Sparrow', 'White_Crowned_Sparrow', 'White_Throated_Sparrow', 'Cape_Glossy_Starling', 'Bank_Swallow', 'Barn_Swallow', 'Cliff_Swallow', 'Tree_Swallow', 'Scarlet_Tanager', 'Summer_Tanager', 'Artic_Tern', 'Black_Tern', 'Caspian_Tern', 'Common_Tern', 'Elegant_Tern', 'Forsters_Tern', 'Least_Tern', 'Green_Tailed_Towhee', 'Brown_Thrasher', 'Sage_Thrasher', 'Black_Capped_Vireo', 'Blue_Headed_Vireo', 'Philadelphia_Vireo', 'Red_Eyed_Vireo', 'Warbling_Vireo', 'White_Eyed_Vireo', 'Yellow_Throated_Vireo', 'Bay_Breasted_Warbler', 'Black_And_White_Warbler', 'Black_Throated_Blue_Warbler', 'Blue_Winged_Warbler', 'Canada_Warbler', 'Cape_May_Warbler', 'Cerulean_Warbler', 'Chestnut_Sided_Warbler', 'Golden_Winged_Warbler', 'Hooded_Warbler', 'Kentucky_Warbler', 'Magnolia_Warbler', 'Mourning_Warbler', 'Myrtle_Warbler', 'Nashville_Warbler', 'Orange_Crowned_Warbler', 'Palm_Warbler', 'Pine_Warbler', 'Prairie_Warbler', 'Prothonotary_Warbler', 'Swainson_Warbler', 'Tennessee_Warbler', 'Wilson_Warbler', 'Worm_Eating_Warbler', 'Yellow_Warbler', 'Northern_Waterthrush', 'Louisiana_Waterthrush', 'Bohemian_Waxwing', 'Cedar_Waxwing', 'American_Three_Toed_Woodpecker', 'Pileated_Woodpecker', 'Red_Bellied_Woodpecker', 'Red_Cockaded_Woodpecker', 'Red_Headed_Woodpecker', 'Downy_Woodpecker', 'Bewick_Wren', 'Cactus_Wren', 'Carolina_Wren', 'House_Wren', 'Marsh_Wren', 'Rock_Wren', 'Winter_Wren', 'Common_Yellowthroat','Anas_poecilorhyncha', 'Greylag_Goose', 'Swan_Goose', 'Domestic_goose', 'Podiceps_ruficollis']
|
||||
PYH_3_class = ['Grus_vipio','Grus_leucogeranus','Grus_monacha']
|
||||
fine_class_names = PYH_3_class
|
||||
# CUI BHQ_name = ["Mallard", "Anas_poecilorhyncha", "Greylag_Goose", "Swan_Goose", "Domestic_goose","Podiceps_ruficollis"]
|
||||
BHQ_name = ['Grus_vipio','Grus_leucogeranus','Grus_monacha']
|
||||
|
||||
# CUI BHQ_chinese = ['绿头鸭', '斑嘴鸭', '灰雁', '鸿雁', '家鹅', '小鷿鷈']
|
||||
BHQ_chinese = ['白枕鹤', '白鹤', '白头鹤']
|
||||
class Detector:
|
||||
|
||||
def __init__(self, device):
|
||||
@@ -53,7 +65,7 @@ class Detector:
|
||||
self.stride = 1
|
||||
#self.weights = "/data1/Hatcher/model/yolov5/runs/train/exp15/weights/best.pt"
|
||||
#self.weights = '/data1/Hatcher/model/yolov5/runs/train/exp10/weights/best.pt'
|
||||
self.weights = '/data1/Hatcher/model/data_MPKFNet/weigth/detection/Y/best.pt'
|
||||
self.weights = '/data1/Hatcher/model/yolov5/runs/train/exp19/weights/best.pt'
|
||||
self.device = device
|
||||
#self.device = select_device(self.device)
|
||||
model = attempt_load(self.weights, map_location=self.device)
|
||||
@@ -80,6 +92,7 @@ class Detector:
|
||||
#im 原图 imo 1024 img 640
|
||||
def detect(self, im):
|
||||
img_detect = cv2.resize(im, (1024, 768))
|
||||
# twice image resize or-->1024--->640
|
||||
im0, img = self.preprocess(img_detect)
|
||||
|
||||
pred = self.model(img, augment=False)[0]
|
||||
@@ -192,7 +205,57 @@ class Fine_grained:
|
||||
print("fine data final is ", (t4 - t3) * 1000)
|
||||
|
||||
return imagelist, labellist, scorelist
|
||||
class Fine_grained_Transformer:
|
||||
def __init__(self,device):
|
||||
self.device = device
|
||||
self.WeightPath = '/data/Hatcher/data/weigth/areaproject/resnet50-PYH-3_0.7/_3911_PYH-3/best.pth'
|
||||
self.net = 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']}
|
||||
model_dict.update(pretrained_dict)
|
||||
self.net.load_state_dict(model_dict)
|
||||
self.transformers = load_data_transformers(600, 448, [7, 7])
|
||||
print("load model weight is ok")
|
||||
self.net.train(False)
|
||||
self.softmax = nn.Softmax()
|
||||
def inference(self,img,imagelist,labellist,scorelist):
|
||||
with torch.no_grad():
|
||||
ratio_x = (3840.0 / 1024.0)
|
||||
ratio_y = (2160.0 / 768.0)
|
||||
for i,box in enumerate(imagelist):
|
||||
Img = img.copy()[int(box[1]):int(box[3]), int(box[0]):int(box[2]), :]
|
||||
#cv2.imwrite("/data/Hatcher/detectout6/{}.jpg".format(str(i)),Img)
|
||||
#height_or, width_or = Img.shape[:2]
|
||||
#Img = cv2.resize(Img,(int(width_or/ratio_x),int(height_or/ratio_y)))
|
||||
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()
|
||||
|
||||
print("fine data deal is ", (t2 - t1) * 1000)
|
||||
outputs = self.net(inputs)
|
||||
t3 = time.time()
|
||||
|
||||
print("fine inference is ", (t3 - t2) * 1000)
|
||||
|
||||
outputs[0] = self.softmax(outputs[0])
|
||||
top3_val, top3_pos = torch.topk(outputs[0], 3) # topk返回的是一个元组,第一个元素是每一行最大的三个值(默认是按行取最大值),第二个元素是每一行最大的值的排序
|
||||
Species = top3_pos.cpu().numpy()[0]
|
||||
ConfidenceLevel = top3_val.cpu().numpy()[0]
|
||||
ConfidenceLevel = ConfidenceLevel.astype(np.float64)
|
||||
#ConfidenceLevel = ConfidenceLevel/26.0
|
||||
print("hhhhhhhhhhhhhhhhhhhhhhh is ",ConfidenceLevel)
|
||||
labellist[i] = Species
|
||||
scorelist[i] = ConfidenceLevel
|
||||
t4 = time.time()
|
||||
print("fine data final is ", (t4 - t3) * 1000)
|
||||
|
||||
return imagelist, labellist, scorelist
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(description="SSD Demo.")
|
||||
parser.add_argument(
|
||||
@@ -351,13 +414,14 @@ def run_demo_fine_SSD(cfg, ckpt, score_threshold, images_dir, output_dir, datase
|
||||
Image.fromarray(drawn_image).save(os.path.join(output_dir, image_name))
|
||||
def run_demo_fine_Y5(cfg, ckpt, score_threshold, images_dir, output_dir, dataset_type):
|
||||
device = torch.device(cfg.MODEL.DEVICE)
|
||||
fine1 = Fine_grained(device)
|
||||
fine1 = Fine_grained_Transformer(device)
|
||||
detector = Detector(device)
|
||||
image_paths = glob.glob(os.path.join(images_dir, '*.jpg'))
|
||||
image_paths.sort()
|
||||
mkdir(output_dir)
|
||||
|
||||
cpu_device = torch.device("cpu")
|
||||
|
||||
num_image = 0
|
||||
for i_D, image_path in enumerate(image_paths):
|
||||
|
||||
image_name = os.path.basename(image_path)
|
||||
@@ -373,17 +437,19 @@ def run_demo_fine_Y5(cfg, ckpt, score_threshold, images_dir, output_dir, dataset
|
||||
continue
|
||||
indices_label_left = labels < 1
|
||||
indices_label_right = labels <1
|
||||
indices = []
|
||||
indices=torch.empty(len(labels)).bool()
|
||||
for i in range(len(indices_label_left)):
|
||||
indices.append(indices_label_left[i] and indices_label_right[i])
|
||||
|
||||
indices_temp = (indices_label_left[i] and indices_label_right[i])
|
||||
#print(indices_temp.item())
|
||||
indices[i] = indices_temp.item()
|
||||
#indices = torch.Tensor(indices)
|
||||
pred_boxes = pred_boxes[indices]
|
||||
labels = labels[indices]
|
||||
scores = scores[indices] # 因为莫名奇妙多了一个list维度,所以加了这个0
|
||||
if len(labels)>0:
|
||||
boxes = pred_boxes[0]
|
||||
labels = labels[0]
|
||||
scores = scores[0]
|
||||
boxes = pred_boxes
|
||||
# labels = labels[0]
|
||||
# scores = scores[0]
|
||||
print(len(scores))
|
||||
ratio_x = (width_or / 1024.0)
|
||||
ratio_y = (height_or / 768.0)
|
||||
@@ -410,8 +476,11 @@ def run_demo_fine_Y5(cfg, ckpt, score_threshold, images_dir, output_dir, dataset
|
||||
]
|
||||
)
|
||||
print('({:04d}/{:04d}) {}: {}'.format(i_D + 1, len(image_paths), image_name, meters))
|
||||
num_detect = 0
|
||||
spiec_number = [0 for i in range(len(BHQ_chinese))]
|
||||
|
||||
for i in range(len(scores)):
|
||||
|
||||
xyxy = boxes[i]
|
||||
conf = scores[i]
|
||||
cls = labels[i]
|
||||
@@ -419,39 +488,70 @@ def run_demo_fine_Y5(cfg, ckpt, score_threshold, images_dir, output_dir, dataset
|
||||
#label = f'{int(cls)} {conf:.2f}'
|
||||
#if int(cls)==3:
|
||||
if int(cls)==99999:
|
||||
label = f'{int(cls)} {conf:.2f}'
|
||||
label = f'{int(cls)}'
|
||||
else:
|
||||
label = f'{fine_class_names[int(cls)]} {conf:.2f}'
|
||||
label = f'{fine_class_names[int(cls)]}'
|
||||
# if int(cls) == 11:
|
||||
# label = f'{"苍鹭"} {conf:.2f}'
|
||||
# if label == 3:
|
||||
# label = "白鹭"
|
||||
# if label ==11:
|
||||
# label = "苍鹭"
|
||||
print(label)
|
||||
if label in BHQ_name:
|
||||
label = BHQ_chinese[BHQ_name.index(label)]
|
||||
spiec_number[BHQ_chinese.index(label)] +=1
|
||||
else:
|
||||
#label = '未知鸟类'
|
||||
label = None
|
||||
cls = -1
|
||||
palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1)
|
||||
colors = [int((p * (cls ** 2 - cls + 1)) % 255) for p in palette]
|
||||
plot_one_box(xyxy, img, label=label, color=colors, line_thickness=3)
|
||||
img = plot_one_box(xyxy, img, label=label, color=colors, line_thickness=2)
|
||||
num_detect+=1
|
||||
else:
|
||||
boxes, labels, scores = [],[],[]
|
||||
#drawn_image = draw_boxes(image, boxes_fine, labels_fine, scores_fine).astype(np.uint8)
|
||||
xml_outputpath = os.path.join(output_dir, image_name).replace("/result/","/result_xml/").replace(".jpg",".xml")
|
||||
make_xml(image_name,im0.shape[0],im0.shape[1],boxes,labels,scores,xml_outputpath)
|
||||
cv2.imwrite(os.path.join(output_dir, image_name),im0)
|
||||
if num_image%10 ==0:
|
||||
num_count_old = num_detect
|
||||
spiec_number_old = spiec_number
|
||||
if width_or == 2560:
|
||||
img = cv2AddChineseText(img, "识别总数: {}只".format(str(num_count_old)), (50, 1200), textColor=(255, 255, 255),
|
||||
textSize=40)
|
||||
img = cv2AddChineseText(img, "分类识别:", (50, 1250), textColor=(255, 255, 255),
|
||||
textSize=40)
|
||||
for i in range(len(spiec_number)):
|
||||
img = cv2AddChineseText(img, "{}数量:{}只".format(str(BHQ_chinese[i]), str(spiec_number_old[i])),
|
||||
(250 + i * 300, 1250), textColor=(255, 255, 255),
|
||||
textSize=40)
|
||||
if width_or == 1920:
|
||||
radio_w = 1920 / 2560.0
|
||||
radio_h = 1080 / 1440.0
|
||||
img = cv2AddChineseText(img, "识别总数: {}只".format(str(num_count_old)),
|
||||
(int(50 * radio_w), int(1200 * radio_h)), textColor=(255, 255, 255),
|
||||
textSize=40)
|
||||
img = cv2AddChineseText(img, "分类识别:", (int(50 * radio_w), int(1250 * radio_h)), textColor=(255, 255, 255),
|
||||
textSize=40)
|
||||
for i in range(len(spiec_number)):
|
||||
img = cv2AddChineseText(img, "{}数量:{}只".format(str(BHQ_chinese[i]), str(spiec_number_old[i])),
|
||||
(int(250) + i * int(300), int(1250 * radio_h)), textColor=(255, 255, 255),
|
||||
textSize=40)
|
||||
cv2.imwrite(os.path.join(output_dir, image_name),img)
|
||||
num_image += 1
|
||||
#Image.fromarray(drawn_image).save(os.path.join(output_dir, image_name))
|
||||
def run_demo_Y5(cfg, ckpt, score_threshold, images_dir, output_dir, dataset_type):
|
||||
device = torch.device(cfg.MODEL.DEVICE)
|
||||
#fine1 = Fine_grained(device)
|
||||
fine1 = Fine_grained_Transformer(device)
|
||||
detector = Detector(device)
|
||||
image_paths = glob.glob(os.path.join(images_dir, '*.jpg'))
|
||||
image_paths.sort()
|
||||
mkdir(output_dir)
|
||||
|
||||
cpu_device = torch.device("cpu")
|
||||
|
||||
num_image = 0
|
||||
for i_D, image_path in enumerate(image_paths):
|
||||
|
||||
image_name = os.path.basename(image_path)
|
||||
print(image_name)
|
||||
#a = Image.open(image_path)
|
||||
img = cv2.imread(image_path) # BG
|
||||
height_or, width_or = img.shape[:2]
|
||||
t3 = time.time()
|
||||
@@ -461,34 +561,85 @@ def run_demo_Y5(cfg, ckpt, score_threshold, images_dir, output_dir, dataset_type
|
||||
print(type(labels))
|
||||
if len(labels) == 0:
|
||||
continue
|
||||
indices_label_left = labels < 1
|
||||
indices_label_right = labels < 1
|
||||
indices = torch.empty(len(labels)).bool()
|
||||
for i in range(len(indices_label_left)):
|
||||
indices_temp = (indices_label_left[i] and indices_label_right[i])
|
||||
indices[i] = indices_temp.item()
|
||||
pred_boxes = pred_boxes[indices]
|
||||
labels = labels[indices]
|
||||
scores = scores[indices] # 因为莫名奇妙多了一个list维度,所以加了这个0
|
||||
if len(labels) > 0:
|
||||
boxes = pred_boxes
|
||||
print(len(scores))
|
||||
ratio_x = (width_or / 1024.0)
|
||||
ratio_y = (height_or / 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 = boxes, labels, scores
|
||||
meters = ' | '.join(
|
||||
[
|
||||
'objects {:02d}'.format(len(pred_boxes)),
|
||||
'objects {:02d}'.format(len(boxes_fine)),
|
||||
]
|
||||
)
|
||||
print('({:04d}/{:04d}) {}: {}'.format(i_D + 1, len(image_paths), image_name, meters))
|
||||
ratio_x = (width_or / 1024.0)
|
||||
ratio_y = (height_or/ 768.0)
|
||||
|
||||
num_detect = 0
|
||||
|
||||
for i in range(len(scores)):
|
||||
xyxy = pred_boxes[i]
|
||||
xyxy[0] = xyxy[0] * ratio_x
|
||||
xyxy[2] = xyxy[2] * ratio_x
|
||||
xyxy[1] = xyxy[1] * ratio_y
|
||||
xyxy[3] = xyxy[3] * ratio_y
|
||||
conf = scores[i]
|
||||
|
||||
xyxy = boxes[i]
|
||||
|
||||
cls = labels[i]
|
||||
print(cls)
|
||||
label = f'{int(cls)} {conf:.2f}'
|
||||
if int(cls) == 99999:
|
||||
label = f'{int(cls)}'
|
||||
else:
|
||||
label = f'{fine_class_names[int(cls)]}'
|
||||
|
||||
|
||||
|
||||
label = None
|
||||
cls = -1
|
||||
palette = (2 ** 11 - 1, 2 ** 15 - 1, 2 ** 20 - 1)
|
||||
colors = [int((p * ((cls+10) ** 2 - cls + 1)) % 255) for p in palette]
|
||||
plot_one_box(xyxy, im0, label=label, color=colors, line_thickness=6)
|
||||
#drawn_image = draw_boxes(image, boxes_fine, labels_fine, scores_fine).astype(np.uint8)
|
||||
xml_outputpath = os.path.join(output_dir, image_name).replace("/result/","/result_xml/").replace(".jpg",".xml")
|
||||
make_xml(image_name,im0.shape[0],im0.shape[1],pred_boxes,labels,scores,xml_outputpath)
|
||||
cv2.imwrite(os.path.join(output_dir, image_name),im0)
|
||||
#Image.fromarray(drawn_image).save(os.path.join(output_dir, image_name))
|
||||
colors = [int((p * (cls ** 2 - cls + 1)) % 255) for p in palette]
|
||||
img = plot_one_box(xyxy, img, label=label, color=colors, line_thickness=2)
|
||||
num_detect += 1
|
||||
else:
|
||||
boxes, labels, scores = [], [], []
|
||||
# drawn_image = draw_boxes(image, boxes_fine, labels_fine, scores_fine).astype(np.uint8)
|
||||
xml_outputpath = os.path.join(output_dir, image_name).replace("/result/", "/result_xml/").replace(".jpg",
|
||||
".xml")
|
||||
make_xml(image_name, im0.shape[0], im0.shape[1], boxes, labels, scores, xml_outputpath)
|
||||
if num_image % 10 == 0:
|
||||
num_count_old = num_detect
|
||||
if width_or == 2560:
|
||||
img = cv2AddChineseText(img, "识别总数: {}只".format(str(num_count_old)), (50, 1200), textColor=(255, 255, 255),
|
||||
textSize=70)
|
||||
|
||||
if width_or == 1920:
|
||||
radio_w = 1920 / 2560.0
|
||||
radio_h = 1080 / 1440.0
|
||||
img = cv2AddChineseText(img, "识别总数: {}只".format(str(num_count_old)),
|
||||
(int(50 * radio_w), int(1200 * radio_h)), textColor=(255, 255, 255),
|
||||
textSize=70)
|
||||
|
||||
cv2.imwrite(os.path.join(output_dir, image_name), img)
|
||||
num_image += 1
|
||||
|
||||
|
||||
def main(args):
|
||||
@@ -511,7 +662,7 @@ def main(args):
|
||||
if not os.path.exists(output_temp):
|
||||
os.mkdir(output_temp)
|
||||
run_demo_fine_Y5(cfg=cfg,
|
||||
ckpt=args.ckpt,
|
||||
ckpt=None,
|
||||
score_threshold=args.score_threshold,
|
||||
images_dir=args.images_dir,
|
||||
output_dir=args.output_dir,
|
||||
|
||||
@@ -1,2 +1,88 @@
|
||||
import os
|
||||
import cv2
|
||||
import random
|
||||
from PIL import Image
|
||||
from lxml import etree
|
||||
path_unit= "/data1/zwq/model/data_MPKFNet/data/ConstructionSite/Hatcher_One"
|
||||
path_raw = "/data1/zwq/model/data_MPKFNet/data/ConstructionSite/NO"
|
||||
result_path = "/data1/zwq/model/data_MPKFNet/data/ConstructionSite/result"
|
||||
|
||||
class GEN_Annotations:
|
||||
def __init__(self, filename):
|
||||
self.root = etree.Element("annotation")
|
||||
|
||||
child1 = etree.SubElement(self.root, "folder")
|
||||
child1.text = "VOC2007"
|
||||
|
||||
child2 = etree.SubElement(self.root, "filename")
|
||||
child2.text = filename
|
||||
|
||||
child3 = etree.SubElement(self.root, "source")
|
||||
|
||||
child4 = etree.SubElement(child3, "annotation")
|
||||
child4.text = "PASCAL VOC2007"
|
||||
child5 = etree.SubElement(child3, "database")
|
||||
child5.text = "Unknown"
|
||||
|
||||
child6 = etree.SubElement(child3, "image")
|
||||
child6.text = "flickr"
|
||||
child7 = etree.SubElement(child3, "flickrid")
|
||||
child7.text = "35435"
|
||||
|
||||
def set_size(self, witdh, height, channel):
|
||||
size = etree.SubElement(self.root, "size")
|
||||
widthn = etree.SubElement(size, "width")
|
||||
widthn.text = str(witdh)
|
||||
heightn = etree.SubElement(size, "height")
|
||||
heightn.text = str(height)
|
||||
channeln = etree.SubElement(size, "depth")
|
||||
channeln.text = str(channel)
|
||||
|
||||
def savefile(self, filename):
|
||||
tree = etree.ElementTree(self.root)
|
||||
tree.write(filename, pretty_print=True, xml_declaration=False, encoding='utf-8')
|
||||
|
||||
def add_pic_attr(self, label, xmin, ymin, xmax, ymax):
|
||||
object = etree.SubElement(self.root, "object")
|
||||
namen = etree.SubElement(object, "name")
|
||||
namen.text = label
|
||||
bndbox = etree.SubElement(object, "bndbox")
|
||||
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)
|
||||
|
||||
|
||||
def negative_samples():
|
||||
unit_list = os.listdir(path_unit)
|
||||
unit_img_list = []
|
||||
for unit_img in unit_list:
|
||||
img1 = Image.open(os.path.join(path_unit,unit_img))
|
||||
unit_img_list.append(img1)
|
||||
raw_list = os.listdir(path_raw)
|
||||
for raw_path in raw_list:
|
||||
print(raw_list)
|
||||
print("\n")
|
||||
raw_img = Image.open(os.path.join(path_raw,raw_path))
|
||||
unit_num = random.randint(0,10)
|
||||
x_left = random.randint(0,raw_img.size[0]-unit_img_list[unit_num].size[0])
|
||||
y_left = random.randint(0,raw_img.size[1]-unit_img_list[unit_num].size[1])
|
||||
x_right = x_left+unit_img_list[unit_num].size[0]
|
||||
y_right = y_left+unit_img_list[unit_num].size[1]
|
||||
raw_img.paste(unit_img_list[unit_num],(x_left,y_left,x_right,y_right))
|
||||
raw_img.save(os.path.join(path_raw,raw_path).replace("/NO/","/result/Images/"))
|
||||
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.savefile(os.path.join(path_raw,raw_path).replace("/NO/","/result/Ground_truth/").replace(".jpg",".xml"))
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
negative_samples()
|
||||
BIN
Binary file not shown.
Binary file not shown.
+140
@@ -0,0 +1,140 @@
|
||||
import os
|
||||
import pandas as pd
|
||||
import torch
|
||||
|
||||
from transforms import transforms
|
||||
from util.autoaugment import ImageNetPolicy
|
||||
|
||||
# pretrained model checkpoints
|
||||
pretrained_model = {'resnet50' : '/data1/Hatcher/model/data_MPKFNet/weigth/FinedGrainedRecognition/pretrained/vgg16-397923af.pth',}
|
||||
|
||||
# transforms dict
|
||||
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), # 将图片进行随机旋转
|
||||
transforms.RandomCrop((crop_reso,crop_reso)), # 图片进行随机裁剪
|
||||
transforms.RandomHorizontalFlip(), # 随机水平翻转
|
||||
]),
|
||||
'train_totensor': transforms.Compose([
|
||||
transforms.Resize((crop_reso, crop_reso)),
|
||||
# ImageNetPolicy(),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
||||
]),
|
||||
'val_totensor': transforms.Compose([
|
||||
transforms.Resize((crop_reso, crop_reso)),
|
||||
transforms.ToTensor(),
|
||||
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.ToTensor(),
|
||||
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
||||
]),
|
||||
'None': None,
|
||||
}
|
||||
return data_transforms
|
||||
|
||||
''' change three paths dataset save '''
|
||||
|
||||
class LoadConfig(object):
|
||||
def __init__(self, args, version):
|
||||
if version == 'train':
|
||||
get_list = ['train', 'val']
|
||||
elif version == 'val':
|
||||
get_list = ['val']
|
||||
elif version == 'test':
|
||||
get_list = ['test']
|
||||
else:
|
||||
raise Exception("train/val/test ???\n")
|
||||
|
||||
###############################
|
||||
#### add dataset info here ####
|
||||
###############################
|
||||
|
||||
# put image data in $PATH/data
|
||||
# put annotation txt file in $PATH/anno
|
||||
|
||||
if args.dataset == 'product':
|
||||
self.dataset = args.dataset
|
||||
self.rawdata_root = './../FGVC_product/data'
|
||||
self.anno_root = './../FGVC_product/anno'
|
||||
self.numcls = 2019
|
||||
elif args.dataset == 'CUB':
|
||||
self.dataset = args.dataset
|
||||
self.rawdata_root = './datasets/CUB_200_2011/data'
|
||||
self.anno_root = './datasets/CUB_200_2011/anno'
|
||||
self.numcls = 200
|
||||
elif args.dataset == 'STCAR':
|
||||
self.dataset = args.dataset
|
||||
self.rawdata_root = './dataset/st_car/data'
|
||||
self.anno_root = './dataset/st_car/anno'
|
||||
self.numcls = 196
|
||||
elif args.dataset == 'AIR':
|
||||
self.dataset = args.dataset
|
||||
self.rawdata_root = './dataset/aircraft/data'
|
||||
self.anno_root = './dataset/aircraft/anno'
|
||||
self.numcls = 200
|
||||
|
||||
elif args.dataset == 'HCData':
|
||||
self.dataset = args.dataset
|
||||
self.rawdata_root = '../../data_MPKFNet/data/DCL/datasets/HCData/data'
|
||||
self.anno_root = '../../data_MPKFNet/data/DCL/datasets/HCData/anno'
|
||||
self.numcls = 50
|
||||
else:
|
||||
raise Exception('dataset not defined ???')
|
||||
|
||||
# annotation file organized as :
|
||||
# path/image_name cls_num\n
|
||||
|
||||
if 'train' in get_list:
|
||||
self.train_anno = pd.read_csv(os.path.join(self.anno_root, 'train.txt'),
|
||||
sep=" ",
|
||||
header=None,
|
||||
names=['ImageName', 'label'])
|
||||
|
||||
if 'val' in get_list:
|
||||
self.val_anno = pd.read_csv(os.path.join(self.anno_root, 'test.txt'),
|
||||
sep=" ",
|
||||
header=None,
|
||||
names=['ImageName', 'label'])
|
||||
|
||||
if 'test' in get_list:
|
||||
self.test_anno = pd.read_csv(os.path.join(self.anno_root, 'test.txt'),
|
||||
sep=" ",
|
||||
header=None,
|
||||
names=['ImageName', 'label'])
|
||||
|
||||
self.swap_num = args.swap_num
|
||||
|
||||
self.save_dir = '../../data_MPKFNet/weigth/FinedGrainedRecognition/Train'
|
||||
if not os.path.exists(self.save_dir):
|
||||
os.mkdir(self.save_dir)
|
||||
self.backbone = args.backbone
|
||||
|
||||
self.use_dcl = True
|
||||
self.use_backbone = False if self.use_dcl else True
|
||||
self.use_Asoftmax = False
|
||||
self.use_focal_loss = False
|
||||
self.use_fpn = False
|
||||
self.use_hier = False
|
||||
|
||||
self.weighted_sample = False
|
||||
self.cls_2 = True
|
||||
self.cls_2xmul = False
|
||||
|
||||
self.log_folder = './logs'
|
||||
if not os.path.exists(self.log_folder):
|
||||
os.mkdir(self.log_folder)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import os
|
||||
import pandas as pd
|
||||
import torch
|
||||
|
||||
from fine.transforms import transforms
|
||||
|
||||
|
||||
|
||||
# pretrained model checkpoints
|
||||
pretrained_model = {'resnet50' : '/data1/Hatcher/model/data_MPKFNet/weigth/FinedGrainedRecognition/pretrained/vgg16-397923af.pth',}
|
||||
|
||||
# transforms dict
|
||||
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), # 将图片进行随机旋转
|
||||
transforms.RandomCrop((crop_reso,crop_reso)), # 图片进行随机裁剪
|
||||
transforms.RandomHorizontalFlip(), # 随机水平翻转
|
||||
]),
|
||||
'train_totensor': transforms.Compose([
|
||||
transforms.Resize((crop_reso, crop_reso)),
|
||||
# ImageNetPolicy(),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
||||
]),
|
||||
'val_totensor': transforms.Compose([
|
||||
transforms.Resize((crop_reso, crop_reso)),
|
||||
transforms.ToTensor(),
|
||||
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.ToTensor(),
|
||||
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
||||
]),
|
||||
'None': None,
|
||||
}
|
||||
return data_transforms
|
||||
|
||||
''' change three paths dataset save '''
|
||||
|
||||
class LoadConfig(object):
|
||||
def __init__(self, args, version):
|
||||
get_list = []
|
||||
if version == 'train':
|
||||
get_list = ['train', 'val']
|
||||
elif version == 'val':
|
||||
get_list = ['val']
|
||||
elif version == 'test':
|
||||
get_list = ['test']
|
||||
|
||||
|
||||
###############################
|
||||
#### add dataset info here ####
|
||||
###############################
|
||||
|
||||
# put image data in $PATH/data
|
||||
# put annotation txt file in $PATH/anno
|
||||
|
||||
if args.dataset == 'product':
|
||||
self.dataset = args.dataset
|
||||
self.rawdata_root = './../FGVC_product/data'
|
||||
self.anno_root = './../FGVC_product/anno'
|
||||
self.numcls = 2019
|
||||
elif args.dataset == 'CUB':
|
||||
self.dataset = args.dataset
|
||||
self.rawdata_root = './datasets/CUB_200_2011/data'
|
||||
self.anno_root = './datasets/CUB_200_2011/anno'
|
||||
self.numcls = 200
|
||||
elif args.dataset == 'STCAR':
|
||||
self.dataset = args.dataset
|
||||
self.rawdata_root = './dataset/st_car/data'
|
||||
self.anno_root = './dataset/st_car/anno'
|
||||
self.numcls = 196
|
||||
elif args.dataset == 'AIR':
|
||||
self.dataset = args.dataset
|
||||
self.rawdata_root = './dataset/aircraft/data'
|
||||
self.anno_root = './dataset/aircraft/anno'
|
||||
self.numcls = 200
|
||||
|
||||
elif args.dataset == 'HCData':
|
||||
self.dataset = args.dataset
|
||||
self.rawdata_root = '../../data_MPKFNet/data/DCL/datasets/HCData/data'
|
||||
self.anno_root = '../../data_MPKFNet/data/DCL/datasets/HCData/anno'
|
||||
self.numcls = 50
|
||||
else:
|
||||
raise Exception('dataset not defined ???')
|
||||
|
||||
# annotation file organized as :
|
||||
# path/image_name cls_num\n
|
||||
|
||||
if 'train' in get_list:
|
||||
self.train_anno = pd.read_csv(os.path.join(self.anno_root, 'train.txt'),
|
||||
sep=" ",
|
||||
header=None,
|
||||
names=['ImageName', 'label'])
|
||||
|
||||
if 'val' in get_list:
|
||||
self.val_anno = pd.read_csv(os.path.join(self.anno_root, 'test.txt'),
|
||||
sep=" ",
|
||||
header=None,
|
||||
names=['ImageName', 'label'])
|
||||
|
||||
if 'test' in get_list:
|
||||
self.test_anno = pd.read_csv(os.path.join(self.anno_root, 'test.txt'),
|
||||
sep=" ",
|
||||
header=None,
|
||||
names=['ImageName', 'label'])
|
||||
|
||||
self.swap_num = args.swap_num
|
||||
self.backbone = args.backbone
|
||||
|
||||
self.use_dcl = True
|
||||
self.use_backbone = False if self.use_dcl else True
|
||||
self.use_Asoftmax = False
|
||||
self.use_focal_loss = False
|
||||
self.use_fpn = False
|
||||
self.use_hier = False
|
||||
|
||||
self.weighted_sample = False
|
||||
self.cls_2 = True
|
||||
self.cls_2xmul = False
|
||||
|
||||
self.log_folder = './logs'
|
||||
if not os.path.exists(self.log_folder):
|
||||
os.mkdir(self.log_folder)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import numpy as np
|
||||
from torch import nn
|
||||
import torch
|
||||
from torchvision import models, transforms, datasets
|
||||
import torch.nn.functional as F
|
||||
# import pretrainedmodels
|
||||
|
||||
pretrained_model = {'resnet50' : '../data_MPKFNet/weigth/FinedGrainedRecognition/pretrained/vgg16-397923af.pth',}
|
||||
|
||||
|
||||
import pdb
|
||||
|
||||
class MainModel(nn.Module):
|
||||
def __init__(self, config):
|
||||
super(MainModel, self).__init__()
|
||||
self.use_dcl = config.use_dcl
|
||||
self.num_classes = config.numcls
|
||||
self.backbone_arch = config.backbone
|
||||
self.use_Asoftmax = config.use_Asoftmax
|
||||
# 返回属性值
|
||||
if self.backbone_arch in dir(models):
|
||||
self.model = getattr(models, 'vgg16')() # getattr models.vgg16
|
||||
if self.backbone_arch in pretrained_model:
|
||||
self.model.load_state_dict(torch.load(pretrained_model[self.backbone_arch])) # 加载权重
|
||||
#else:
|
||||
# 在 Python 类的内部,无论是类属性还是实例属性,都是以字典的形式进行存储的,其中属性名作为键,而值作为该键对应的值
|
||||
# 将键对应的键值提取出来
|
||||
|
||||
#if self.backbone_arch in pretrained_model:
|
||||
#self.model = pretrainedmodels.__dict__[self.backbone_arch](num_classes=1000, pretrained=None)
|
||||
#else:
|
||||
#self.model = pretrainedmodels.__dict__[self.backbone_arch](num_classes=1000)
|
||||
# 去掉全连接层 模型结构转换
|
||||
if self.backbone_arch == 'resnet50' or self.backbone_arch == 'se_resnet50':
|
||||
self.model = nn.Sequential(*list(self.model.children())[:-2])
|
||||
if self.backbone_arch == 'senet154':
|
||||
self.model = nn.Sequential(*list(self.model.children())[:-3])
|
||||
if self.backbone_arch == 'se_resnext101_32x4d':
|
||||
self.model = nn.Sequential(*list(self.model.children())[:-2])
|
||||
if self.backbone_arch == 'se_resnet101':
|
||||
self.model = nn.Sequential(*list(self.model.children())[:-2])
|
||||
self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)
|
||||
self.classifier = nn.Linear(512, self.num_classes, bias=False) # 输入通道进行了改变 原来是2048
|
||||
if self.use_dcl:
|
||||
# if config.cls_2:
|
||||
self.classifier_swap = nn.Linear(512, 2, bias=False)
|
||||
if config.cls_2xmul:
|
||||
self.classifier_swap = nn.Linear(512, 2*self.num_classes, bias=False)
|
||||
self.Convmask = nn.Conv2d(512, 1, 1, stride=1, padding=0, bias=True) # 输入 输出 卷积核大小 步长
|
||||
self.avgpool2 = nn.AvgPool2d(2, stride=2)
|
||||
|
||||
# if self.use_Asoftmax:
|
||||
# self.Aclassifier = AngleLinear(2048, self.num_classes, bias=False)
|
||||
# 分类网络:output[0] 对抗损失网络:output[1] 区域对齐网络:output[2]
|
||||
def forward(self, x, last_cont=None):
|
||||
x = self.model(x)
|
||||
if self.use_dcl:
|
||||
mask = self.Convmask(x) # 加一个全卷积层
|
||||
mask = self.avgpool2(mask)# 平均池化
|
||||
mask = torch.tanh(mask)
|
||||
mask = mask.view(mask.size(0), -1)
|
||||
x = self.avgpool(x) # 平均值池化
|
||||
x = x.view(x.size(0), -1)
|
||||
out = []
|
||||
out.append(self.classifier(x))
|
||||
|
||||
if self.use_dcl:
|
||||
out.append(self.classifier_swap(x))
|
||||
out.append(mask)
|
||||
|
||||
# if self.use_Asoftmax:
|
||||
# if last_cont is None:
|
||||
# x_size = x.size(0)
|
||||
# out.append(self.Aclassifier(x[0:x_size:2]))
|
||||
# else:
|
||||
# last_x = self.model(last_cont)
|
||||
# last_x = self.avgpool(last_x)
|
||||
# last_x = last_x.view(last_x.size(0), -1)
|
||||
# out.append(self.Aclassifier(last_x))
|
||||
|
||||
return out
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
from .transforms import *
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,750 @@
|
||||
from __future__ import division
|
||||
import torch
|
||||
import math
|
||||
import random
|
||||
from PIL import Image, ImageOps, ImageEnhance
|
||||
try:
|
||||
import accimage
|
||||
except ImportError:
|
||||
accimage = None
|
||||
import numpy as np
|
||||
import numbers
|
||||
import types
|
||||
import collections
|
||||
import warnings
|
||||
|
||||
|
||||
def _is_pil_image(img):
|
||||
if accimage is not None:
|
||||
return isinstance(img, (Image.Image, accimage.Image))
|
||||
else:
|
||||
return isinstance(img, Image.Image)
|
||||
|
||||
|
||||
def _is_tensor_image(img):
|
||||
return torch.is_tensor(img) and img.ndimension() == 3
|
||||
|
||||
|
||||
def _is_numpy_image(img):
|
||||
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
|
||||
|
||||
|
||||
def to_tensor(pic):
|
||||
"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
|
||||
|
||||
See ``ToTensor`` for more details.
|
||||
|
||||
Args:
|
||||
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
|
||||
|
||||
Returns:
|
||||
Tensor: Converted image.
|
||||
"""
|
||||
if not(_is_pil_image(pic) or _is_numpy_image(pic)):
|
||||
raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic)))
|
||||
|
||||
if isinstance(pic, np.ndarray):
|
||||
# handle numpy array
|
||||
img = torch.from_numpy(pic.transpose((2, 0, 1)))
|
||||
# backward compatibility
|
||||
if isinstance(img, torch.ByteTensor):
|
||||
return img.float().div(255)
|
||||
else:
|
||||
return img
|
||||
|
||||
if accimage is not None and isinstance(pic, accimage.Image):
|
||||
nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32)
|
||||
pic.copyto(nppic)
|
||||
return torch.from_numpy(nppic)
|
||||
|
||||
# handle PIL Image
|
||||
if pic.mode == 'I':
|
||||
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
|
||||
elif pic.mode == 'I;16':
|
||||
img = torch.from_numpy(np.array(pic, np.int16, copy=False))
|
||||
elif pic.mode == 'F':
|
||||
img = torch.from_numpy(np.array(pic, np.float32, copy=False))
|
||||
elif pic.mode == '1':
|
||||
img = 255 * torch.from_numpy(np.array(pic, np.uint8, copy=False))
|
||||
else:
|
||||
img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes()))
|
||||
# PIL image mode: L, P, I, F, RGB, YCbCr, RGBA, CMYK
|
||||
if pic.mode == 'YCbCr':
|
||||
nchannel = 3
|
||||
elif pic.mode == 'I;16':
|
||||
nchannel = 1
|
||||
else:
|
||||
nchannel = len(pic.mode)
|
||||
img = img.view(pic.size[1], pic.size[0], nchannel)
|
||||
# put it from HWC to CHW format
|
||||
# yikes, this transpose takes 80% of the loading time/CPU
|
||||
img = img.transpose(0, 1).transpose(0, 2).contiguous()
|
||||
if isinstance(img, torch.ByteTensor):
|
||||
return img.float().div(255)
|
||||
else:
|
||||
return img
|
||||
|
||||
|
||||
def to_pil_image(pic, mode=None):
|
||||
"""Convert a tensor or an ndarray to PIL Image.
|
||||
|
||||
See :class:`~torchvision.transforms.ToPIlImage` for more details.
|
||||
|
||||
Args:
|
||||
pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
|
||||
mode (`PIL.Image mode`_): color space and pixel depth of input data (optional).
|
||||
|
||||
.. _PIL.Image mode: http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#modes
|
||||
|
||||
Returns:
|
||||
PIL Image: Image converted to PIL Image.
|
||||
"""
|
||||
if not(_is_numpy_image(pic) or _is_tensor_image(pic)):
|
||||
raise TypeError('pic should be Tensor or ndarray. Got {}.'.format(type(pic)))
|
||||
|
||||
npimg = pic
|
||||
if isinstance(pic, torch.FloatTensor):
|
||||
pic = pic.mul(255).byte()
|
||||
if torch.is_tensor(pic):
|
||||
npimg = np.transpose(pic.numpy(), (1, 2, 0))
|
||||
|
||||
if not isinstance(npimg, np.ndarray):
|
||||
raise TypeError('Input pic must be a torch.Tensor or NumPy ndarray, ' +
|
||||
'not {}'.format(type(npimg)))
|
||||
|
||||
if npimg.shape[2] == 1:
|
||||
expected_mode = None
|
||||
npimg = npimg[:, :, 0]
|
||||
if npimg.dtype == np.uint8:
|
||||
expected_mode = 'L'
|
||||
elif npimg.dtype == np.int16:
|
||||
expected_mode = 'I;16'
|
||||
elif npimg.dtype == np.int32:
|
||||
expected_mode = 'I'
|
||||
elif npimg.dtype == np.float32:
|
||||
expected_mode = 'F'
|
||||
if mode is not None and mode != expected_mode:
|
||||
raise ValueError("Incorrect mode ({}) supplied for input type {}. Should be {}"
|
||||
.format(mode, np.dtype, expected_mode))
|
||||
mode = expected_mode
|
||||
|
||||
elif npimg.shape[2] == 4:
|
||||
permitted_4_channel_modes = ['RGBA', 'CMYK']
|
||||
if mode is not None and mode not in permitted_4_channel_modes:
|
||||
raise ValueError("Only modes {} are supported for 4D inputs".format(permitted_4_channel_modes))
|
||||
|
||||
if mode is None and npimg.dtype == np.uint8:
|
||||
mode = 'RGBA'
|
||||
else:
|
||||
permitted_3_channel_modes = ['RGB', 'YCbCr', 'HSV']
|
||||
if mode is not None and mode not in permitted_3_channel_modes:
|
||||
raise ValueError("Only modes {} are supported for 3D inputs".format(permitted_3_channel_modes))
|
||||
if mode is None and npimg.dtype == np.uint8:
|
||||
mode = 'RGB'
|
||||
|
||||
if mode is None:
|
||||
raise TypeError('Input type {} is not supported'.format(npimg.dtype))
|
||||
|
||||
return Image.fromarray(npimg, mode=mode)
|
||||
|
||||
|
||||
def normalize(tensor, mean, std):
|
||||
"""Normalize a tensor image with mean and standard deviation.
|
||||
|
||||
See ``Normalize`` for more details.
|
||||
|
||||
Args:
|
||||
tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
|
||||
mean (sequence): Sequence of means for each channel.
|
||||
std (sequence): Sequence of standard deviations for each channely.
|
||||
|
||||
Returns:
|
||||
Tensor: Normalized Tensor image.
|
||||
"""
|
||||
if not _is_tensor_image(tensor):
|
||||
raise TypeError('tensor is not a torch image.')
|
||||
# TODO: make efficient
|
||||
for t, m, s in zip(tensor, mean, std):
|
||||
t.sub_(m).div_(s)
|
||||
return tensor
|
||||
|
||||
|
||||
def resize(img, size, interpolation=Image.BILINEAR):
|
||||
"""Resize the input PIL Image to the given size.
|
||||
|
||||
Args:
|
||||
img (PIL Image): Image to be resized.
|
||||
size (sequence or int): Desired output size. If size is a sequence like
|
||||
(h, w), the output size will be matched to this. If size is an int,
|
||||
the smaller edge of the image will be matched to this number maintaing
|
||||
the aspect ratio. i.e, if height > width, then image will be rescaled to
|
||||
(size * height / width, size)
|
||||
interpolation (int, optional): Desired interpolation. Default is
|
||||
``PIL.Image.BILINEAR``
|
||||
|
||||
Returns:
|
||||
PIL Image: Resized image.
|
||||
"""
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)):
|
||||
raise TypeError('Got inappropriate size arg: {}'.format(size))
|
||||
|
||||
if isinstance(size, int):
|
||||
w, h = img.size
|
||||
if (w <= h and w == size) or (h <= w and h == size):
|
||||
return img
|
||||
if w < h:
|
||||
ow = size
|
||||
oh = int(size * h / w)
|
||||
return img.resize((ow, oh), interpolation)
|
||||
else:
|
||||
oh = size
|
||||
ow = int(size * w / h)
|
||||
return img.resize((ow, oh), interpolation)
|
||||
else:
|
||||
return img.resize(size[::-1], interpolation)
|
||||
|
||||
|
||||
def scale(*args, **kwargs):
|
||||
warnings.warn("The use of the transforms.Scale transform is deprecated, " +
|
||||
"please use transforms.Resize instead.")
|
||||
return resize(*args, **kwargs)
|
||||
|
||||
|
||||
def pad(img, padding, fill=0, padding_mode='constant'):
|
||||
"""Pad the given PIL Image on all sides with speficified padding mode and fill value.
|
||||
|
||||
Args:
|
||||
img (PIL Image): Image to be padded.
|
||||
padding (int or tuple): Padding on each border. If a single int is provided this
|
||||
is used to pad all borders. If tuple of length 2 is provided this is the padding
|
||||
on left/right and top/bottom respectively. If a tuple of length 4 is provided
|
||||
this is the padding for the left, top, right and bottom borders
|
||||
respectively.
|
||||
fill: Pixel fill value for constant fill. Default is 0. If a tuple of
|
||||
length 3, it is used to fill R, G, B channels respectively.
|
||||
This value is only used when the padding_mode is constant
|
||||
padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
|
||||
constant: pads with a constant value, this value is specified with fill
|
||||
edge: pads with the last value on the edge of the image
|
||||
reflect: pads with reflection of image (without repeating the last value on the edge)
|
||||
padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
|
||||
will result in [3, 2, 1, 2, 3, 4, 3, 2]
|
||||
symmetric: pads with reflection of image (repeating the last value on the edge)
|
||||
padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
|
||||
will result in [2, 1, 1, 2, 3, 4, 4, 3]
|
||||
|
||||
Returns:
|
||||
PIL Image: Padded image.
|
||||
"""
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
if not isinstance(padding, (numbers.Number, tuple)):
|
||||
raise TypeError('Got inappropriate padding arg')
|
||||
if not isinstance(fill, (numbers.Number, str, tuple)):
|
||||
raise TypeError('Got inappropriate fill arg')
|
||||
if not isinstance(padding_mode, str):
|
||||
raise TypeError('Got inappropriate padding_mode arg')
|
||||
|
||||
if isinstance(padding, collections.Sequence) and len(padding) not in [2, 4]:
|
||||
raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " +
|
||||
"{} element tuple".format(len(padding)))
|
||||
|
||||
assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], \
|
||||
'Padding mode should be either constant, edge, reflect or symmetric'
|
||||
|
||||
if padding_mode == 'constant':
|
||||
return ImageOps.expand(img, border=padding, fill=fill)
|
||||
else:
|
||||
if isinstance(padding, int):
|
||||
pad_left = pad_right = pad_top = pad_bottom = padding
|
||||
if isinstance(padding, collections.Sequence) and len(padding) == 2:
|
||||
pad_left = pad_right = padding[0]
|
||||
pad_top = pad_bottom = padding[1]
|
||||
if isinstance(padding, collections.Sequence) and len(padding) == 4:
|
||||
pad_left = padding[0]
|
||||
pad_top = padding[1]
|
||||
pad_right = padding[2]
|
||||
pad_bottom = padding[3]
|
||||
|
||||
img = np.asarray(img)
|
||||
# RGB image
|
||||
if len(img.shape) == 3:
|
||||
img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), padding_mode)
|
||||
# Grayscale image
|
||||
if len(img.shape) == 2:
|
||||
img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode)
|
||||
|
||||
return Image.fromarray(img)
|
||||
|
||||
|
||||
def crop(img, i, j, h, w):
|
||||
"""Crop the given PIL Image.
|
||||
|
||||
Args:
|
||||
img (PIL Image): Image to be cropped.
|
||||
i: Upper pixel coordinate.
|
||||
j: Left pixel coordinate.
|
||||
h: Height of the cropped image.
|
||||
w: Width of the cropped image.
|
||||
|
||||
Returns:
|
||||
PIL Image: Cropped image.
|
||||
"""
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
return img.crop((j, i, j + w, i + h))
|
||||
|
||||
|
||||
def center_crop(img, output_size):
|
||||
if isinstance(output_size, numbers.Number):
|
||||
output_size = (int(output_size), int(output_size))
|
||||
w, h = img.size
|
||||
th, tw = output_size
|
||||
i = int(round((h - th) / 2.))
|
||||
j = int(round((w - tw) / 2.))
|
||||
return crop(img, i, j, th, tw)
|
||||
|
||||
|
||||
def resized_crop(img, i, j, h, w, size, interpolation=Image.BILINEAR):
|
||||
"""Crop the given PIL Image and resize it to desired size.
|
||||
|
||||
Notably used in RandomResizedCrop.
|
||||
|
||||
Args:
|
||||
img (PIL Image): Image to be cropped.
|
||||
i: Upper pixel coordinate.
|
||||
j: Left pixel coordinate.
|
||||
h: Height of the cropped image.
|
||||
w: Width of the cropped image.
|
||||
size (sequence or int): Desired output size. Same semantics as ``scale``.
|
||||
interpolation (int, optional): Desired interpolation. Default is
|
||||
``PIL.Image.BILINEAR``.
|
||||
Returns:
|
||||
PIL Image: Cropped image.
|
||||
"""
|
||||
assert _is_pil_image(img), 'img should be PIL Image'
|
||||
img = crop(img, i, j, h, w)
|
||||
img = resize(img, size, interpolation)
|
||||
return img
|
||||
|
||||
|
||||
def hflip(img):
|
||||
"""Horizontally flip the given PIL Image.
|
||||
|
||||
Args:
|
||||
img (PIL Image): Image to be flipped.
|
||||
|
||||
Returns:
|
||||
PIL Image: Horizontall flipped image.
|
||||
"""
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
return img.transpose(Image.FLIP_LEFT_RIGHT)
|
||||
|
||||
|
||||
def vflip(img):
|
||||
"""Vertically flip the given PIL Image.
|
||||
|
||||
Args:
|
||||
img (PIL Image): Image to be flipped.
|
||||
|
||||
Returns:
|
||||
PIL Image: Vertically flipped image.
|
||||
"""
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
return img.transpose(Image.FLIP_TOP_BOTTOM)
|
||||
|
||||
|
||||
def swap(img, crop):
|
||||
def crop_image(image, cropnum):
|
||||
width, high = image.size
|
||||
crop_x = [int((width / cropnum[0]) * i) for i in range(cropnum[0] + 1)]
|
||||
crop_y = [int((high / cropnum[1]) * i) for i in range(cropnum[1] + 1)]
|
||||
im_list = []
|
||||
for j in range(len(crop_y) - 1):
|
||||
for i in range(len(crop_x) - 1):
|
||||
im_list.append(image.crop((crop_x[i], crop_y[j], min(crop_x[i + 1], width), min(crop_y[j + 1], high))))
|
||||
return im_list
|
||||
|
||||
widthcut, highcut = img.size
|
||||
img = img.crop((10, 10, widthcut-10, highcut-10))
|
||||
images = crop_image(img, crop)
|
||||
pro = 5
|
||||
if pro >= 5:
|
||||
tmpx = []
|
||||
tmpy = []
|
||||
count_x = 0
|
||||
count_y = 0
|
||||
k = 1
|
||||
RAN = 2
|
||||
for i in range(crop[1] * crop[0]):
|
||||
tmpx.append(images[i])
|
||||
count_x += 1
|
||||
if len(tmpx) >= k:
|
||||
tmp = tmpx[count_x - RAN:count_x]
|
||||
random.shuffle(tmp)
|
||||
tmpx[count_x - RAN:count_x] = tmp
|
||||
if count_x == crop[0]:
|
||||
tmpy.append(tmpx)
|
||||
count_x = 0
|
||||
count_y += 1
|
||||
tmpx = []
|
||||
if len(tmpy) >= k:
|
||||
tmp2 = tmpy[count_y - RAN:count_y]
|
||||
random.shuffle(tmp2)
|
||||
tmpy[count_y - RAN:count_y] = tmp2
|
||||
random_im = []
|
||||
for line in tmpy:
|
||||
random_im.extend(line)
|
||||
|
||||
# random.shuffle(images)
|
||||
width, high = img.size
|
||||
iw = int(width / crop[0])
|
||||
ih = int(high / crop[1])
|
||||
toImage = Image.new('RGB', (iw * crop[0], ih * crop[1]))
|
||||
x = 0
|
||||
y = 0
|
||||
for i in random_im:
|
||||
i = i.resize((iw, ih), Image.ANTIALIAS)
|
||||
toImage.paste(i, (x * iw, y * ih))
|
||||
x += 1
|
||||
if x == crop[0]:
|
||||
x = 0
|
||||
y += 1
|
||||
else:
|
||||
toImage = img
|
||||
toImage = toImage.resize((widthcut, highcut))
|
||||
return toImage
|
||||
|
||||
|
||||
|
||||
def five_crop(img, size):
|
||||
"""Crop the given PIL Image into four corners and the central crop.
|
||||
|
||||
.. Note::
|
||||
This transform returns a tuple of images and there may be a
|
||||
mismatch in the number of inputs and targets your ``Dataset`` returns.
|
||||
|
||||
Args:
|
||||
size (sequence or int): Desired output size of the crop. If size is an
|
||||
int instead of sequence like (h, w), a square crop (size, size) is
|
||||
made.
|
||||
Returns:
|
||||
tuple: tuple (tl, tr, bl, br, center) corresponding top left,
|
||||
top right, bottom left, bottom right and center crop.
|
||||
"""
|
||||
if isinstance(size, numbers.Number):
|
||||
size = (int(size), int(size))
|
||||
else:
|
||||
assert len(size) == 2, "Please provide only two dimensions (h, w) for size."
|
||||
|
||||
w, h = img.size
|
||||
crop_h, crop_w = size
|
||||
if crop_w > w or crop_h > h:
|
||||
raise ValueError("Requested crop size {} is bigger than input size {}".format(size,
|
||||
(h, w)))
|
||||
tl = img.crop((0, 0, crop_w, crop_h))
|
||||
tr = img.crop((w - crop_w, 0, w, crop_h))
|
||||
bl = img.crop((0, h - crop_h, crop_w, h))
|
||||
br = img.crop((w - crop_w, h - crop_h, w, h))
|
||||
center = center_crop(img, (crop_h, crop_w))
|
||||
return (tl, tr, bl, br, center)
|
||||
|
||||
|
||||
def ten_crop(img, size, vertical_flip=False):
|
||||
"""Crop the given PIL Image into four corners and the central crop plus the
|
||||
flipped version of these (horizontal flipping is used by default).
|
||||
|
||||
.. Note::
|
||||
This transform returns a tuple of images and there may be a
|
||||
mismatch in the number of inputs and targets your ``Dataset`` returns.
|
||||
|
||||
Args:
|
||||
size (sequence or int): Desired output size of the crop. If size is an
|
||||
int instead of sequence like (h, w), a square crop (size, size) is
|
||||
made.
|
||||
vertical_flip (bool): Use vertical flipping instead of horizontal
|
||||
|
||||
Returns:
|
||||
tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip,
|
||||
br_flip, center_flip) corresponding top left, top right,
|
||||
bottom left, bottom right and center crop and same for the
|
||||
flipped image.
|
||||
"""
|
||||
if isinstance(size, numbers.Number):
|
||||
size = (int(size), int(size))
|
||||
else:
|
||||
assert len(size) == 2, "Please provide only two dimensions (h, w) for size."
|
||||
|
||||
first_five = five_crop(img, size)
|
||||
|
||||
if vertical_flip:
|
||||
img = vflip(img)
|
||||
else:
|
||||
img = hflip(img)
|
||||
|
||||
second_five = five_crop(img, size)
|
||||
return first_five + second_five
|
||||
|
||||
|
||||
def adjust_brightness(img, brightness_factor):
|
||||
"""Adjust brightness of an Image.
|
||||
|
||||
Args:
|
||||
img (PIL Image): PIL Image to be adjusted.
|
||||
brightness_factor (float): How much to adjust the brightness. Can be
|
||||
any non negative number. 0 gives a black image, 1 gives the
|
||||
original image while 2 increases the brightness by a factor of 2.
|
||||
|
||||
Returns:
|
||||
PIL Image: Brightness adjusted image.
|
||||
"""
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
enhancer = ImageEnhance.Brightness(img)
|
||||
img = enhancer.enhance(brightness_factor)
|
||||
return img
|
||||
|
||||
|
||||
def adjust_contrast(img, contrast_factor):
|
||||
"""Adjust contrast of an Image.
|
||||
|
||||
Args:
|
||||
img (PIL Image): PIL Image to be adjusted.
|
||||
contrast_factor (float): How much to adjust the contrast. Can be any
|
||||
non negative number. 0 gives a solid gray image, 1 gives the
|
||||
original image while 2 increases the contrast by a factor of 2.
|
||||
|
||||
Returns:
|
||||
PIL Image: Contrast adjusted image.
|
||||
"""
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
enhancer = ImageEnhance.Contrast(img)
|
||||
img = enhancer.enhance(contrast_factor)
|
||||
return img
|
||||
|
||||
|
||||
def adjust_saturation(img, saturation_factor):
|
||||
"""Adjust color saturation of an image.
|
||||
|
||||
Args:
|
||||
img (PIL Image): PIL Image to be adjusted.
|
||||
saturation_factor (float): How much to adjust the saturation. 0 will
|
||||
give a black and white image, 1 will give the original image while
|
||||
2 will enhance the saturation by a factor of 2.
|
||||
|
||||
Returns:
|
||||
PIL Image: Saturation adjusted image.
|
||||
"""
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
enhancer = ImageEnhance.Color(img)
|
||||
img = enhancer.enhance(saturation_factor)
|
||||
return img
|
||||
|
||||
|
||||
def adjust_hue(img, hue_factor):
|
||||
"""Adjust hue of an image.
|
||||
|
||||
The image hue is adjusted by converting the image to HSV and
|
||||
cyclically shifting the intensities in the hue channel (H).
|
||||
The image is then converted back to original image mode.
|
||||
|
||||
`hue_factor` is the amount of shift in H channel and must be in the
|
||||
interval `[-0.5, 0.5]`.
|
||||
|
||||
See https://en.wikipedia.org/wiki/Hue for more details on Hue.
|
||||
|
||||
Args:
|
||||
img (PIL Image): PIL Image to be adjusted.
|
||||
hue_factor (float): How much to shift the hue channel. Should be in
|
||||
[-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in
|
||||
HSV space in positive and negative direction respectively.
|
||||
0 means no shift. Therefore, both -0.5 and 0.5 will give an image
|
||||
with complementary colors while 0 gives the original image.
|
||||
|
||||
Returns:
|
||||
PIL Image: Hue adjusted image.
|
||||
"""
|
||||
if not(-0.5 <= hue_factor <= 0.5):
|
||||
raise ValueError('hue_factor is not in [-0.5, 0.5].'.format(hue_factor))
|
||||
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
input_mode = img.mode
|
||||
if input_mode in {'L', '1', 'I', 'F'}:
|
||||
return img
|
||||
|
||||
h, s, v = img.convert('HSV').split()
|
||||
|
||||
np_h = np.array(h, dtype=np.uint8)
|
||||
# uint8 addition take cares of rotation across boundaries
|
||||
with np.errstate(over='ignore'):
|
||||
np_h += np.uint8(hue_factor * 255)
|
||||
h = Image.fromarray(np_h, 'L')
|
||||
|
||||
img = Image.merge('HSV', (h, s, v)).convert(input_mode)
|
||||
return img
|
||||
|
||||
|
||||
def adjust_gamma(img, gamma, gain=1):
|
||||
"""Perform gamma correction on an image.
|
||||
|
||||
Also known as Power Law Transform. Intensities in RGB mode are adjusted
|
||||
based on the following equation:
|
||||
|
||||
I_out = 255 * gain * ((I_in / 255) ** gamma)
|
||||
|
||||
See https://en.wikipedia.org/wiki/Gamma_correction for more details.
|
||||
|
||||
Args:
|
||||
img (PIL Image): PIL Image to be adjusted.
|
||||
gamma (float): Non negative real number. gamma larger than 1 make the
|
||||
shadows darker, while gamma smaller than 1 make dark regions
|
||||
lighter.
|
||||
gain (float): The constant multiplier.
|
||||
"""
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
if gamma < 0:
|
||||
raise ValueError('Gamma should be a non-negative real number')
|
||||
|
||||
input_mode = img.mode
|
||||
img = img.convert('RGB')
|
||||
|
||||
gamma_map = [255 * gain * pow(ele / 255., gamma) for ele in range(256)] * 3
|
||||
img = img.point(gamma_map) # use PIL's point-function to accelerate this part
|
||||
|
||||
img = img.convert(input_mode)
|
||||
return img
|
||||
|
||||
|
||||
def rotate(img, angle, resample=False, expand=False, center=None):
|
||||
"""Rotate the image by angle.
|
||||
|
||||
|
||||
Args:
|
||||
img (PIL Image): PIL Image to be rotated.
|
||||
angle ({float, int}): In degrees degrees counter clockwise order.
|
||||
resample ({PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC}, optional):
|
||||
An optional resampling filter.
|
||||
See http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#filters
|
||||
If omitted, or if the image has mode "1" or "P", it is set to PIL.Image.NEAREST.
|
||||
expand (bool, optional): Optional expansion flag.
|
||||
If true, expands the output image to make it large enough to hold the entire rotated image.
|
||||
If false or omitted, make the output image the same size as the input image.
|
||||
Note that the expand flag assumes rotation around the center and no translation.
|
||||
center (2-tuple, optional): Optional center of rotation.
|
||||
Origin is the upper left corner.
|
||||
Default is the center of the image.
|
||||
"""
|
||||
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
return img.rotate(angle, resample, expand, center)
|
||||
|
||||
|
||||
def _get_inverse_affine_matrix(center, angle, translate, scale, shear):
|
||||
# Helper method to compute inverse matrix for affine transformation
|
||||
|
||||
# As it is explained in PIL.Image.rotate
|
||||
# We need compute INVERSE of affine transformation matrix: M = T * C * RSS * C^-1
|
||||
# where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1]
|
||||
# C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1]
|
||||
# RSS is rotation with scale and shear matrix
|
||||
# RSS(a, scale, shear) = [ cos(a)*scale -sin(a + shear)*scale 0]
|
||||
# [ sin(a)*scale cos(a + shear)*scale 0]
|
||||
# [ 0 0 1]
|
||||
# Thus, the inverse is M^-1 = C * RSS^-1 * C^-1 * T^-1
|
||||
|
||||
angle = math.radians(angle)
|
||||
shear = math.radians(shear)
|
||||
scale = 1.0 / scale
|
||||
|
||||
# Inverted rotation matrix with scale and shear
|
||||
d = math.cos(angle + shear) * math.cos(angle) + math.sin(angle + shear) * math.sin(angle)
|
||||
matrix = [
|
||||
math.cos(angle + shear), math.sin(angle + shear), 0,
|
||||
-math.sin(angle), math.cos(angle), 0
|
||||
]
|
||||
matrix = [scale / d * m for m in matrix]
|
||||
|
||||
# Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1
|
||||
matrix[2] += matrix[0] * (-center[0] - translate[0]) + matrix[1] * (-center[1] - translate[1])
|
||||
matrix[5] += matrix[3] * (-center[0] - translate[0]) + matrix[4] * (-center[1] - translate[1])
|
||||
|
||||
# Apply center translation: C * RSS^-1 * C^-1 * T^-1
|
||||
matrix[2] += center[0]
|
||||
matrix[5] += center[1]
|
||||
return matrix
|
||||
|
||||
|
||||
def affine(img, angle, translate, scale, shear, resample=0, fillcolor=None):
|
||||
"""Apply affine transformation on the image keeping image center invariant
|
||||
|
||||
Args:
|
||||
img (PIL Image): PIL Image to be rotated.
|
||||
angle ({float, int}): rotation angle in degrees between -180 and 180, clockwise direction.
|
||||
translate (list or tuple of integers): horizontal and vertical translations (post-rotation translation)
|
||||
scale (float): overall scale
|
||||
shear (float): shear angle value in degrees between -180 to 180, clockwise direction.
|
||||
resample ({PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC}, optional):
|
||||
An optional resampling filter.
|
||||
See http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#filters
|
||||
If omitted, or if the image has mode "1" or "P", it is set to PIL.Image.NEAREST.
|
||||
fillcolor (int): Optional fill color for the area outside the transform in the output image. (Pillow>=5.0.0)
|
||||
"""
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
assert isinstance(translate, (tuple, list)) and len(translate) == 2, \
|
||||
"Argument translate should be a list or tuple of length 2"
|
||||
|
||||
assert scale > 0.0, "Argument scale should be positive"
|
||||
|
||||
output_size = img.size
|
||||
center = (img.size[0] * 0.5 + 0.5, img.size[1] * 0.5 + 0.5)
|
||||
matrix = _get_inverse_affine_matrix(center, angle, translate, scale, shear)
|
||||
kwargs = {}
|
||||
return img.transform(output_size, Image.AFFINE, matrix, resample, **kwargs)
|
||||
|
||||
|
||||
def to_grayscale(img, num_output_channels=1):
|
||||
"""Convert image to grayscale version of image.
|
||||
|
||||
Args:
|
||||
img (PIL Image): Image to be converted to grayscale.
|
||||
|
||||
Returns:
|
||||
PIL Image: Grayscale version of the image.
|
||||
if num_output_channels == 1 : returned image is single channel
|
||||
if num_output_channels == 3 : returned image is 3 channel with r == g == b
|
||||
"""
|
||||
if not _is_pil_image(img):
|
||||
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
|
||||
|
||||
if num_output_channels == 1:
|
||||
img = img.convert('L')
|
||||
elif num_output_channels == 3:
|
||||
img = img.convert('L')
|
||||
np_img = np.array(img, dtype=np.uint8)
|
||||
np_img = np.dstack([np_img, np_img, np_img])
|
||||
img = Image.fromarray(np_img, 'RGB')
|
||||
else:
|
||||
raise ValueError('num_output_channels should be either 1 or 3')
|
||||
|
||||
return img
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,47 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.autograd import Variable
|
||||
import torch.nn.functional as F
|
||||
from torch.nn import Parameter
|
||||
import math
|
||||
|
||||
import pdb
|
||||
|
||||
class AngleLoss(nn.Module):
|
||||
def __init__(self, gamma=0):
|
||||
super(AngleLoss, self).__init__()
|
||||
self.gamma = gamma
|
||||
self.it = 0
|
||||
self.LambdaMin = 50.0
|
||||
self.LambdaMax = 1500.0
|
||||
self.lamb = 1500.0
|
||||
|
||||
def forward(self, input, target, decay=None):
|
||||
self.it += 1
|
||||
cos_theta,phi_theta = input
|
||||
target = target.view(-1,1) #size=(B,1)
|
||||
|
||||
index = cos_theta.data * 0.0 #size=(B,Classnum)
|
||||
index.scatter_(1,target.data.view(-1,1),1)
|
||||
index = index.byte()
|
||||
index = Variable(index)
|
||||
|
||||
if decay is None:
|
||||
self.lamb = max(self.LambdaMin,self.LambdaMax/(1+0.1*self.it ))
|
||||
else:
|
||||
self.LambdaMax *= decay
|
||||
self.lamb = max(self.LambdaMin, self.LambdaMax)
|
||||
output = cos_theta * 1.0 #size=(B,Classnum)
|
||||
output[index] -= cos_theta[index]*(1.0+0)/(1+self.lamb)
|
||||
output[index] += phi_theta[index]*(1.0+0)/(1+self.lamb)
|
||||
|
||||
logpt = F.log_softmax(output, 1)
|
||||
logpt = logpt.gather(1,target)
|
||||
logpt = logpt.view(-1)
|
||||
pt = Variable(logpt.data.exp())
|
||||
|
||||
loss = -1 * (1-pt)**self.gamma * logpt
|
||||
loss = loss.mean()
|
||||
|
||||
return loss
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,232 @@
|
||||
from PIL import Image, ImageEnhance, ImageOps
|
||||
import numpy as np
|
||||
import random
|
||||
|
||||
|
||||
class ImageNetPolicy(object):
|
||||
""" Randomly choose one of the best 24 Sub-policies on ImageNet.
|
||||
Example:
|
||||
>>> policy = ImageNetPolicy()
|
||||
>>> transformed = policy(image)
|
||||
Example as a PyTorch Transform:
|
||||
>>> transform=transforms.Compose([
|
||||
>>> transforms.Resize(256),
|
||||
>>> ImageNetPolicy(),
|
||||
>>> transforms.ToTensor()])
|
||||
"""
|
||||
def __init__(self, fillcolor=(128, 128, 128)):
|
||||
self.policies = [
|
||||
SubPolicy(0.4, "posterize", 8, 0.6, "rotate", 9, fillcolor),
|
||||
SubPolicy(0.6, "solarize", 5, 0.6, "autocontrast", 5, fillcolor),
|
||||
SubPolicy(0.8, "equalize", 8, 0.6, "equalize", 3, fillcolor),
|
||||
SubPolicy(0.6, "posterize", 7, 0.6, "posterize", 6, fillcolor),
|
||||
SubPolicy(0.4, "equalize", 7, 0.2, "solarize", 4, fillcolor),
|
||||
|
||||
SubPolicy(0.4, "equalize", 4, 0.8, "rotate", 8, fillcolor),
|
||||
SubPolicy(0.6, "solarize", 3, 0.6, "equalize", 7, fillcolor),
|
||||
SubPolicy(0.8, "posterize", 5, 1.0, "equalize", 2, fillcolor),
|
||||
SubPolicy(0.2, "rotate", 3, 0.6, "solarize", 8, fillcolor),
|
||||
SubPolicy(0.6, "equalize", 8, 0.4, "posterize", 6, fillcolor),
|
||||
|
||||
SubPolicy(0.8, "rotate", 8, 0.4, "color", 0, fillcolor),
|
||||
SubPolicy(0.4, "rotate", 9, 0.6, "equalize", 2, fillcolor),
|
||||
SubPolicy(0.0, "equalize", 7, 0.8, "equalize", 8, fillcolor),
|
||||
SubPolicy(0.6, "invert", 4, 1.0, "equalize", 8, fillcolor),
|
||||
SubPolicy(0.6, "color", 4, 1.0, "contrast", 8, fillcolor),
|
||||
|
||||
SubPolicy(0.8, "rotate", 8, 1.0, "color", 2, fillcolor),
|
||||
SubPolicy(0.8, "color", 8, 0.8, "solarize", 7, fillcolor),
|
||||
SubPolicy(0.4, "sharpness", 7, 0.6, "invert", 8, fillcolor),
|
||||
SubPolicy(0.6, "shearX", 5, 1.0, "equalize", 9, fillcolor),
|
||||
SubPolicy(0.4, "color", 0, 0.6, "equalize", 3, fillcolor),
|
||||
|
||||
SubPolicy(0.4, "equalize", 7, 0.2, "solarize", 4, fillcolor),
|
||||
SubPolicy(0.6, "solarize", 5, 0.6, "autocontrast", 5, fillcolor),
|
||||
SubPolicy(0.6, "invert", 4, 1.0, "equalize", 8, fillcolor),
|
||||
SubPolicy(0.6, "color", 4, 1.0, "contrast", 8, fillcolor),
|
||||
SubPolicy(0.8, "equalize", 8, 0.6, "equalize", 3, fillcolor)
|
||||
]
|
||||
|
||||
|
||||
def __call__(self, img):
|
||||
policy_idx = random.randint(0, len(self.policies) - 1)
|
||||
return self.policies[policy_idx](img)
|
||||
|
||||
def __repr__(self):
|
||||
return "AutoAugment ImageNet Policy"
|
||||
|
||||
|
||||
class CIFAR10Policy(object):
|
||||
""" Randomly choose one of the best 25 Sub-policies on CIFAR10.
|
||||
Example:
|
||||
>>> policy = CIFAR10Policy()
|
||||
>>> transformed = policy(image)
|
||||
Example as a PyTorch Transform:
|
||||
>>> transform=transforms.Compose([
|
||||
>>> transforms.Resize(256),
|
||||
>>> CIFAR10Policy(),
|
||||
>>> transforms.ToTensor()])
|
||||
"""
|
||||
def __init__(self, fillcolor=(128, 128, 128)):
|
||||
self.policies = [
|
||||
SubPolicy(0.1, "invert", 7, 0.2, "contrast", 6, fillcolor),
|
||||
SubPolicy(0.7, "rotate", 2, 0.3, "translateX", 9, fillcolor),
|
||||
SubPolicy(0.8, "sharpness", 1, 0.9, "sharpness", 3, fillcolor),
|
||||
SubPolicy(0.5, "shearY", 8, 0.7, "translateY", 9, fillcolor),
|
||||
SubPolicy(0.5, "autocontrast", 8, 0.9, "equalize", 2, fillcolor),
|
||||
|
||||
SubPolicy(0.2, "shearY", 7, 0.3, "posterize", 7, fillcolor),
|
||||
SubPolicy(0.4, "color", 3, 0.6, "brightness", 7, fillcolor),
|
||||
SubPolicy(0.3, "sharpness", 9, 0.7, "brightness", 9, fillcolor),
|
||||
SubPolicy(0.6, "equalize", 5, 0.5, "equalize", 1, fillcolor),
|
||||
SubPolicy(0.6, "contrast", 7, 0.6, "sharpness", 5, fillcolor),
|
||||
|
||||
SubPolicy(0.7, "color", 7, 0.5, "translateX", 8, fillcolor),
|
||||
SubPolicy(0.3, "equalize", 7, 0.4, "autocontrast", 8, fillcolor),
|
||||
SubPolicy(0.4, "translateY", 3, 0.2, "sharpness", 6, fillcolor),
|
||||
SubPolicy(0.9, "brightness", 6, 0.2, "color", 8, fillcolor),
|
||||
SubPolicy(0.5, "solarize", 2, 0.0, "invert", 3, fillcolor),
|
||||
|
||||
SubPolicy(0.2, "equalize", 0, 0.6, "autocontrast", 0, fillcolor),
|
||||
SubPolicy(0.2, "equalize", 8, 0.8, "equalize", 4, fillcolor),
|
||||
SubPolicy(0.9, "color", 9, 0.6, "equalize", 6, fillcolor),
|
||||
SubPolicy(0.8, "autocontrast", 4, 0.2, "solarize", 8, fillcolor),
|
||||
SubPolicy(0.1, "brightness", 3, 0.7, "color", 0, fillcolor),
|
||||
|
||||
SubPolicy(0.4, "solarize", 5, 0.9, "autocontrast", 3, fillcolor),
|
||||
SubPolicy(0.9, "translateY", 9, 0.7, "translateY", 9, fillcolor),
|
||||
SubPolicy(0.9, "autocontrast", 2, 0.8, "solarize", 3, fillcolor),
|
||||
SubPolicy(0.8, "equalize", 8, 0.1, "invert", 3, fillcolor),
|
||||
SubPolicy(0.7, "translateY", 9, 0.9, "autocontrast", 1, fillcolor)
|
||||
]
|
||||
|
||||
|
||||
def __call__(self, img):
|
||||
policy_idx = random.randint(0, len(self.policies) - 1)
|
||||
return self.policies[policy_idx](img)
|
||||
|
||||
def __repr__(self):
|
||||
return "AutoAugment CIFAR10 Policy"
|
||||
|
||||
|
||||
class SVHNPolicy(object):
|
||||
""" Randomly choose one of the best 25 Sub-policies on SVHN.
|
||||
Example:
|
||||
>>> policy = SVHNPolicy()
|
||||
>>> transformed = policy(image)
|
||||
Example as a PyTorch Transform:
|
||||
>>> transform=transforms.Compose([
|
||||
>>> transforms.Resize(256),
|
||||
>>> SVHNPolicy(),
|
||||
>>> transforms.ToTensor()])
|
||||
"""
|
||||
def __init__(self, fillcolor=(128, 128, 128)):
|
||||
self.policies = [
|
||||
SubPolicy(0.9, "shearX", 4, 0.2, "invert", 3, fillcolor),
|
||||
SubPolicy(0.9, "shearY", 8, 0.7, "invert", 5, fillcolor),
|
||||
SubPolicy(0.6, "equalize", 5, 0.6, "solarize", 6, fillcolor),
|
||||
SubPolicy(0.9, "invert", 3, 0.6, "equalize", 3, fillcolor),
|
||||
SubPolicy(0.6, "equalize", 1, 0.9, "rotate", 3, fillcolor),
|
||||
|
||||
SubPolicy(0.9, "shearX", 4, 0.8, "autocontrast", 3, fillcolor),
|
||||
SubPolicy(0.9, "shearY", 8, 0.4, "invert", 5, fillcolor),
|
||||
SubPolicy(0.9, "shearY", 5, 0.2, "solarize", 6, fillcolor),
|
||||
SubPolicy(0.9, "invert", 6, 0.8, "autocontrast", 1, fillcolor),
|
||||
SubPolicy(0.6, "equalize", 3, 0.9, "rotate", 3, fillcolor),
|
||||
|
||||
SubPolicy(0.9, "shearX", 4, 0.3, "solarize", 3, fillcolor),
|
||||
SubPolicy(0.8, "shearY", 8, 0.7, "invert", 4, fillcolor),
|
||||
SubPolicy(0.9, "equalize", 5, 0.6, "translateY", 6, fillcolor),
|
||||
SubPolicy(0.9, "invert", 4, 0.6, "equalize", 7, fillcolor),
|
||||
SubPolicy(0.3, "contrast", 3, 0.8, "rotate", 4, fillcolor),
|
||||
|
||||
SubPolicy(0.8, "invert", 5, 0.0, "translateY", 2, fillcolor),
|
||||
SubPolicy(0.7, "shearY", 6, 0.4, "solarize", 8, fillcolor),
|
||||
SubPolicy(0.6, "invert", 4, 0.8, "rotate", 4, fillcolor),
|
||||
SubPolicy(0.3, "shearY", 7, 0.9, "translateX", 3, fillcolor),
|
||||
SubPolicy(0.1, "shearX", 6, 0.6, "invert", 5, fillcolor),
|
||||
|
||||
SubPolicy(0.7, "solarize", 2, 0.6, "translateY", 7, fillcolor),
|
||||
SubPolicy(0.8, "shearY", 4, 0.8, "invert", 8, fillcolor),
|
||||
SubPolicy(0.7, "shearX", 9, 0.8, "translateY", 3, fillcolor),
|
||||
SubPolicy(0.8, "shearY", 5, 0.7, "autocontrast", 3, fillcolor),
|
||||
SubPolicy(0.7, "shearX", 2, 0.1, "invert", 5, fillcolor)
|
||||
]
|
||||
|
||||
|
||||
def __call__(self, img):
|
||||
policy_idx = random.randint(0, len(self.policies) - 1)
|
||||
return self.policies[policy_idx](img)
|
||||
|
||||
def __repr__(self):
|
||||
return "AutoAugment SVHN Policy"
|
||||
|
||||
|
||||
class SubPolicy(object):
|
||||
def __init__(self, p1, operation1, magnitude_idx1, p2, operation2, magnitude_idx2, fillcolor=(128, 128, 128)):
|
||||
ranges = {
|
||||
"shearX": np.linspace(0, 0.3, 10),
|
||||
"shearY": np.linspace(0, 0.3, 10),
|
||||
"translateX": np.linspace(0, 150 / 331, 10),
|
||||
"translateY": np.linspace(0, 150 / 331, 10),
|
||||
"rotate": np.linspace(0, 30, 10),
|
||||
"color": np.linspace(0.0, 0.9, 10),
|
||||
"posterize": np.round(np.linspace(8, 4, 10), 0).astype(np.int),
|
||||
"solarize": np.linspace(256, 0, 10),
|
||||
"contrast": np.linspace(0.0, 0.9, 10),
|
||||
"sharpness": np.linspace(0.0, 0.9, 10),
|
||||
"brightness": np.linspace(0.0, 0.9, 10),
|
||||
"autocontrast": [0] * 10,
|
||||
"equalize": [0] * 10,
|
||||
"invert": [0] * 10
|
||||
}
|
||||
|
||||
# from https://stackoverflow.com/questions/5252170/specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand
|
||||
def rotate_with_fill(img, magnitude):
|
||||
rot = img.convert("RGBA").rotate(magnitude)
|
||||
return Image.composite(rot, Image.new("RGBA", rot.size, (128,) * 4), rot).convert(img.mode)
|
||||
|
||||
func = {
|
||||
"shearX": lambda img, magnitude: img.transform(
|
||||
img.size, Image.AFFINE, (1, magnitude * random.choice([-1, 1]), 0, 0, 1, 0),
|
||||
Image.BICUBIC, fillcolor=fillcolor),
|
||||
"shearY": lambda img, magnitude: img.transform(
|
||||
img.size, Image.AFFINE, (1, 0, 0, magnitude * random.choice([-1, 1]), 1, 0),
|
||||
Image.BICUBIC, fillcolor=fillcolor),
|
||||
"translateX": lambda img, magnitude: img.transform(
|
||||
img.size, Image.AFFINE, (1, 0, magnitude * img.size[0] * random.choice([-1, 1]), 0, 1, 0),
|
||||
fillcolor=fillcolor),
|
||||
"translateY": lambda img, magnitude: img.transform(
|
||||
img.size, Image.AFFINE, (1, 0, 0, 0, 1, magnitude * img.size[1] * random.choice([-1, 1])),
|
||||
fillcolor=fillcolor),
|
||||
"rotate": lambda img, magnitude: rotate_with_fill(img, magnitude),
|
||||
# "rotate": lambda img, magnitude: img.rotate(magnitude * random.choice([-1, 1])),
|
||||
"color": lambda img, magnitude: ImageEnhance.Color(img).enhance(1 + magnitude * random.choice([-1, 1])),
|
||||
"posterize": lambda img, magnitude: ImageOps.posterize(img, magnitude),
|
||||
"solarize": lambda img, magnitude: ImageOps.solarize(img, magnitude),
|
||||
"contrast": lambda img, magnitude: ImageEnhance.Contrast(img).enhance(
|
||||
1 + magnitude * random.choice([-1, 1])),
|
||||
"sharpness": lambda img, magnitude: ImageEnhance.Sharpness(img).enhance(
|
||||
1 + magnitude * random.choice([-1, 1])),
|
||||
"brightness": lambda img, magnitude: ImageEnhance.Brightness(img).enhance(
|
||||
1 + magnitude * random.choice([-1, 1])),
|
||||
"autocontrast": lambda img, magnitude: ImageOps.autocontrast(img),
|
||||
"equalize": lambda img, magnitude: ImageOps.equalize(img),
|
||||
"invert": lambda img, magnitude: ImageOps.invert(img)
|
||||
}
|
||||
|
||||
# self.name = "{}_{:.2f}_and_{}_{:.2f}".format(
|
||||
# operation1, ranges[operation1][magnitude_idx1],
|
||||
# operation2, ranges[operation2][magnitude_idx2])
|
||||
self.p1 = p1
|
||||
self.operation1 = func[operation1]
|
||||
self.magnitude1 = ranges[operation1][magnitude_idx1]
|
||||
self.p2 = p2
|
||||
self.operation2 = func[operation2]
|
||||
self.magnitude2 = ranges[operation2][magnitude_idx2]
|
||||
|
||||
|
||||
def __call__(self, img):
|
||||
if random.random() < self.p1: img = self.operation1(img, self.magnitude1)
|
||||
if random.random() < self.p2: img = self.operation2(img, self.magnitude2)
|
||||
return img
|
||||
@@ -0,0 +1,183 @@
|
||||
# coding=utf8
|
||||
from __future__ import division
|
||||
import os
|
||||
import torch
|
||||
import torch.utils.data as data
|
||||
import pandas
|
||||
import random
|
||||
import PIL.Image as Image
|
||||
from PIL import ImageStat
|
||||
|
||||
import pdb
|
||||
|
||||
def random_sample(img_names, labels):
|
||||
anno_dict = {}
|
||||
img_list = []
|
||||
anno_list = []
|
||||
for img, anno in zip(img_names, labels):
|
||||
if not anno in anno_dict:
|
||||
anno_dict[anno] = [img]
|
||||
else:
|
||||
anno_dict[anno].append(img)
|
||||
|
||||
for anno in anno_dict.keys():
|
||||
anno_len = len(anno_dict[anno])
|
||||
fetch_keys = random.sample(list(range(anno_len)), anno_len//10)
|
||||
img_list.extend([anno_dict[anno][x] for x in fetch_keys])
|
||||
anno_list.extend([anno for x in fetch_keys])
|
||||
return img_list, anno_list
|
||||
|
||||
|
||||
|
||||
class dataset(data.Dataset):
|
||||
def __init__(self, Config, anno, swap_size=[7,7], common_aug=None, swap=None, totensor=None, train=False, train_val=False, test=False):
|
||||
self.root_path = Config.rawdata_root
|
||||
self.numcls = Config.numcls
|
||||
self.dataset = Config.dataset
|
||||
self.use_cls_2 = Config.cls_2
|
||||
self.use_cls_mul = Config.cls_2xmul
|
||||
if isinstance(anno, pandas.core.frame.DataFrame): # 判断类型
|
||||
self.paths = anno['ImageName'].tolist()
|
||||
self.labels = anno['label'].tolist()
|
||||
elif isinstance(anno, dict):
|
||||
self.paths = anno['img_name']
|
||||
self.labels = anno['label']
|
||||
|
||||
if train_val:
|
||||
self.paths, self.labels = random_sample(self.paths, self.labels)
|
||||
self.common_aug = common_aug
|
||||
self.swap = swap
|
||||
self.totensor = totensor
|
||||
self.cfg = Config
|
||||
self.train = train
|
||||
self.swap_size = swap_size
|
||||
self.test = test
|
||||
|
||||
def __len__(self):
|
||||
return len(self.paths)
|
||||
|
||||
def __getitem__(self, item):
|
||||
img_path = os.path.join(self.root_path, self.paths[item])
|
||||
img = self.pil_loader(img_path)
|
||||
if self.test:
|
||||
img = self.totensor(img)
|
||||
label = self.labels[item]
|
||||
return img, label, self.paths[item]
|
||||
img_unswap = self.common_aug(img) if not self.common_aug is None else img # 原图数据
|
||||
|
||||
image_unswap_list = self.crop_image(img_unswap, self.swap_size)
|
||||
|
||||
swap_range = self.swap_size[0] * self.swap_size[1]
|
||||
swap_law1 = [(i-(swap_range//2))/swap_range for i in range(swap_range)]
|
||||
# 在训练的时候 self.train是true
|
||||
if self.train:
|
||||
img_swap = self.swap(img_unswap) # RCM机制处理后的照片
|
||||
image_swap_list = self.crop_image(img_swap, self.swap_size)
|
||||
unswap_stats = [sum(ImageStat.Stat(im).mean) for im in image_unswap_list]
|
||||
swap_stats = [sum(ImageStat.Stat(im).mean) for im in image_swap_list]
|
||||
swap_law2 = []
|
||||
for swap_im in swap_stats:
|
||||
distance = [abs(swap_im - unswap_im) for unswap_im in unswap_stats]
|
||||
index = distance.index(min(distance))
|
||||
swap_law2.append((index-(swap_range//2))/swap_range)
|
||||
img_swap = self.totensor(img_swap)
|
||||
label = self.labels[item]
|
||||
if self.use_cls_mul:
|
||||
label_swap = label + self.numcls
|
||||
if self.use_cls_2:
|
||||
label_swap = -1
|
||||
img_unswap = self.totensor(img_unswap)
|
||||
return img_unswap, img_swap, label, label_swap, swap_law1, swap_law2, self.paths[item]
|
||||
else:
|
||||
label = self.labels[item]
|
||||
swap_law2 = [(i-(swap_range//2))/swap_range for i in range(swap_range)]
|
||||
label_swap = label
|
||||
img_unswap = self.totensor(img_unswap)
|
||||
return img_unswap, label, label_swap, swap_law1, swap_law2, self.paths[item]
|
||||
#inputs, labels, labels_swap, swap_law, img_names
|
||||
def pil_loader(self,imgpath):
|
||||
with open(imgpath, 'rb') as f:
|
||||
with Image.open(f) as img:
|
||||
return img.convert('RGB')
|
||||
|
||||
def crop_image(self, image, cropnum):
|
||||
width, high = image.size
|
||||
crop_x = [int((width / cropnum[0]) * i) for i in range(cropnum[0] + 1)]
|
||||
crop_y = [int((high / cropnum[1]) * i) for i in range(cropnum[1] + 1)]
|
||||
im_list = []
|
||||
for j in range(len(crop_y) - 1):
|
||||
for i in range(len(crop_x) - 1):
|
||||
im_list.append(image.crop((crop_x[i], crop_y[j], min(crop_x[i + 1], width), min(crop_y[j + 1], high))))
|
||||
return im_list
|
||||
|
||||
|
||||
def get_weighted_sampler(self):
|
||||
img_nums = len(self.labels)
|
||||
weights = [self.labels.count(x) for x in range(self.numcls)]
|
||||
return torch.utils.data.sampler.WeightedRandomSampler(weights, num_samples=img_nums)
|
||||
|
||||
|
||||
def collate_fn4train(batch):
|
||||
imgs = []
|
||||
label = []
|
||||
label_swap = []
|
||||
law_swap = []
|
||||
img_name = []
|
||||
for sample in batch:
|
||||
imgs.append(sample[0]) # 原始图片
|
||||
imgs.append(sample[1]) # RCM混淆机制打乱后的图片
|
||||
label.append(sample[2])# 类别标签
|
||||
label.append(sample[2])
|
||||
# 给每张图片贴上标签以区分是否被破坏过
|
||||
if sample[3] == -1:
|
||||
label_swap.append(1)
|
||||
label_swap.append(0)
|
||||
else:
|
||||
label_swap.append(sample[2])
|
||||
label_swap.append(sample[3])
|
||||
law_swap.append(sample[4]) # 未打乱时每个小块的位置
|
||||
law_swap.append(sample[5]) # 打乱后每个小块的的位置
|
||||
img_name.append(sample[-1])# 图片名字
|
||||
|
||||
return torch.stack(imgs, 0), label, label_swap, law_swap, img_name # 张量0维度扩展
|
||||
|
||||
def collate_fn4val(batch):
|
||||
imgs = []
|
||||
label = []
|
||||
label_swap = []
|
||||
law_swap = []
|
||||
img_name = []
|
||||
for sample in batch:
|
||||
imgs.append(sample[0])
|
||||
label.append(sample[1])
|
||||
if sample[3] == -1:
|
||||
label_swap.append(1)
|
||||
else:
|
||||
label_swap.append(sample[2])
|
||||
law_swap.append(sample[3])
|
||||
img_name.append(sample[-1])
|
||||
return torch.stack(imgs, 0), label, label_swap, law_swap, img_name
|
||||
|
||||
def collate_fn4backbone(batch):
|
||||
imgs = []
|
||||
label = []
|
||||
img_name = []
|
||||
for sample in batch:
|
||||
imgs.append(sample[0])
|
||||
if len(sample) == 7:
|
||||
label.append(sample[2])
|
||||
else:
|
||||
label.append(sample[1])
|
||||
img_name.append(sample[-1])
|
||||
return torch.stack(imgs, 0), label, img_name
|
||||
|
||||
|
||||
def collate_fn4test(batch):
|
||||
imgs = []
|
||||
label = []
|
||||
img_name = []
|
||||
for sample in batch:
|
||||
imgs.append(sample[0])
|
||||
label.append(sample[1])
|
||||
img_name.append(sample[-1])
|
||||
return torch.stack(imgs, 0), label, img_name
|
||||
@@ -0,0 +1,81 @@
|
||||
#coding=utf8
|
||||
from __future__ import print_function, division
|
||||
import os,time,datetime
|
||||
import numpy as np
|
||||
import datetime
|
||||
from math import ceil
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.autograd import Variable
|
||||
import torch.nn.functional as F
|
||||
|
||||
from util.utils import LossRecord
|
||||
|
||||
import pdb
|
||||
|
||||
def dt():
|
||||
return datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
|
||||
|
||||
def eval_turn(Config, model, data_loader, val_version, epoch_num, log_file):
|
||||
|
||||
model.train(False)
|
||||
|
||||
val_corrects1 = 0
|
||||
val_corrects2 = 0
|
||||
val_corrects3 = 0
|
||||
val_size = data_loader.__len__()
|
||||
item_count = data_loader.total_item_len
|
||||
t0 = time.time()
|
||||
get_l1_loss = nn.L1Loss()
|
||||
get_ce_loss = nn.CrossEntropyLoss()
|
||||
|
||||
val_batch_size = data_loader.batch_size
|
||||
val_epoch_step = data_loader.__len__()
|
||||
num_cls = data_loader.num_cls
|
||||
|
||||
val_loss_recorder = LossRecord(val_batch_size)
|
||||
val_celoss_recorder = LossRecord(val_batch_size)
|
||||
print('evaluating %s ...'%val_version, flush=True)
|
||||
with torch.no_grad():
|
||||
for batch_cnt_val, data_val in enumerate(data_loader):
|
||||
inputs = Variable(data_val[0].cuda())
|
||||
labels = Variable(torch.from_numpy(np.array(data_val[1])).long().cuda())
|
||||
outputs = model(inputs)
|
||||
loss = 0
|
||||
# 前向预测的时候只做分类
|
||||
ce_loss = get_ce_loss(outputs[0], labels).item() # 获取tensor的值不包括类型
|
||||
loss += ce_loss
|
||||
|
||||
val_loss_recorder.update(loss)
|
||||
val_celoss_recorder.update(ce_loss)
|
||||
|
||||
if Config.use_dcl and Config.cls_2xmul:
|
||||
outputs_pred = outputs[0] + outputs[1][:,0:num_cls] + outputs[1][:,num_cls:2*num_cls]
|
||||
else:
|
||||
outputs_pred = outputs[0]
|
||||
top3_val, top3_pos = torch.topk(outputs_pred, 3) # 获取某一维度上 的前k个最大值(张量 k的值)
|
||||
|
||||
print('{:s} eval_batch: {:-6d} / {:d} loss: {:8.4f}'.format(val_version, batch_cnt_val, val_epoch_step, loss), flush=True)
|
||||
|
||||
batch_corrects1 = torch.sum((top3_pos[:, 0] == labels)).data.item() # .data返回的是tensor
|
||||
val_corrects1 += batch_corrects1
|
||||
batch_corrects2 = torch.sum((top3_pos[:, 1] == labels)).data.item()
|
||||
val_corrects2 += (batch_corrects2 + batch_corrects1)
|
||||
batch_corrects3 = torch.sum((top3_pos[:, 2] == labels)).data.item()
|
||||
val_corrects3 += (batch_corrects3 + batch_corrects2 + batch_corrects1)
|
||||
|
||||
val_acc1 = val_corrects1 / item_count
|
||||
val_acc2 = val_corrects2 / item_count
|
||||
val_acc3 = val_corrects3 / item_count
|
||||
|
||||
log_file.write(val_version + '\t' +str(val_loss_recorder.get_val())+'\t' + str(val_celoss_recorder.get_val()) + '\t' + str(val_acc1) + '\t' + str(val_acc3) + '\n')
|
||||
|
||||
t1 = time.time()
|
||||
since = t1-t0
|
||||
print('--'*30, flush=True)
|
||||
print('% 3d %s %s %s-loss: %.4f ||%s-acc@1: %.4f %s-acc@2: %.4f %s-acc@3: %.4f ||time: %d' % (epoch_num, val_version, dt(), val_version, val_loss_recorder.get_val(init=True), val_version, val_acc1,val_version, val_acc2, val_version, val_acc3, since), flush=True)
|
||||
print('--' * 30, flush=True)
|
||||
|
||||
return val_acc1, val_acc2, val_acc3
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import os
|
||||
import math
|
||||
import numpy as np
|
||||
import cv2
|
||||
import datetime
|
||||
|
||||
import torch
|
||||
from torchvision.utils import save_image, make_grid
|
||||
|
||||
import pdb
|
||||
|
||||
def dt():
|
||||
return datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
|
||||
|
||||
def set_text(text, img):
|
||||
font = cv2.FONT_HERSHEY_SIMPLEX
|
||||
if isinstance(text, str):
|
||||
cont = text
|
||||
cv2.putText(img, cont, (20, 50), font, 0.5, (0, 0, 255), 1, cv2.LINE_AA)
|
||||
if isinstance(text, float):
|
||||
cont = '%.4f'%text
|
||||
cv2.putText(img, cont, (20, 50), font, 0.5, (0, 0, 255), 1, cv2.LINE_AA)
|
||||
if isinstance(text, list):
|
||||
for count in range(len(img)):
|
||||
cv2.putText(img[count], text[count], (20, 50), font, 0.5, (0, 0, 255), 1, cv2.LINE_AA)
|
||||
return img
|
||||
|
||||
def save_multi_img(img_list, text_list, grid_size=[5,5], sub_size=200, save_dir='./', save_name=None):
|
||||
if len(img_list) > grid_size[0]*grid_size[1]:
|
||||
merge_height = math.ceil(len(img_list) / grid_size[0]) * sub_size
|
||||
else:
|
||||
merge_height = grid_size[1]*sub_size
|
||||
merged_img = np.zeros((merge_height, grid_size[0]*sub_size, 3))
|
||||
|
||||
if isinstance(img_list[0], str):
|
||||
img_name_list = img_list
|
||||
img_list = []
|
||||
for img_name in img_name_list:
|
||||
img_list.append(cv2.imread(img_name))
|
||||
|
||||
img_counter = 0
|
||||
for img, txt in zip(img_list, text_list):
|
||||
img = cv2.resize(img, (sub_size, sub_size))
|
||||
img = set_text(txt, img)
|
||||
pos = [img_counter // grid_size[1], img_counter % grid_size[1]]
|
||||
sub_pos = [pos[0]*sub_size, (pos[0]+1)*sub_size,
|
||||
pos[1]*sub_size, (pos[1]+1)*sub_size]
|
||||
merged_img[sub_pos[0]:sub_pos[1], sub_pos[2]:sub_pos[3], :] = img
|
||||
img_counter += 1
|
||||
|
||||
if save_name is None:
|
||||
img_save_path = os.path.join(save_dir, dt()+'.png')
|
||||
else:
|
||||
img_save_path = os.path.join(save_dir, save_name+'.png')
|
||||
cv2.imwrite(img_save_path, merged_img)
|
||||
print('saved img in %s ...'%img_save_path)
|
||||
|
||||
|
||||
def cls_base_acc(result_gather):
|
||||
top1_acc = {}
|
||||
top3_acc = {}
|
||||
cls_count = {}
|
||||
for img_item in result_gather.keys():
|
||||
acc_case = result_gather[img_item]
|
||||
|
||||
if acc_case['label'] in cls_count:
|
||||
cls_count[acc_case['label']] += 1
|
||||
if acc_case['top1_cat'] == acc_case['label']:
|
||||
top1_acc[acc_case['label']] += 1
|
||||
if acc_case['label'] in [acc_case['top1_cat'], acc_case['top2_cat'], acc_case['top3_cat']]:
|
||||
top3_acc[acc_case['label']] += 1
|
||||
else:
|
||||
cls_count[acc_case['label']] = 1
|
||||
if acc_case['top1_cat'] == acc_case['label']:
|
||||
top1_acc[acc_case['label']] = 1
|
||||
else:
|
||||
top1_acc[acc_case['label']] = 0
|
||||
|
||||
if acc_case['label'] in [acc_case['top1_cat'], acc_case['top2_cat'], acc_case['top3_cat']]:
|
||||
top3_acc[acc_case['label']] = 1
|
||||
else:
|
||||
top3_acc[acc_case['label']] = 0
|
||||
|
||||
for label_item in cls_count:
|
||||
top1_acc[label_item] /= max(1.0*cls_count[label_item], 0.001)
|
||||
top3_acc[label_item] /= max(1.0*cls_count[label_item], 0.001)
|
||||
|
||||
print('top1_acc:', top1_acc)
|
||||
print('top3_acc:', top3_acc)
|
||||
print('cls_count', cls_count)
|
||||
|
||||
return top1_acc, top3_acc, cls_count
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
#coding=utf8
|
||||
from __future__ import print_function, division
|
||||
|
||||
import os,time,datetime
|
||||
import numpy as np
|
||||
from math import ceil
|
||||
import datetime
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.autograd import Variable
|
||||
#from torchvision.utils import make_grid, save_image
|
||||
|
||||
from util.utils import LossRecord, clip_gradient
|
||||
from models.focal_loss import FocalLoss
|
||||
from util.eval_model import eval_turn
|
||||
from util.Asoftmax_loss import AngleLoss
|
||||
|
||||
import pdb
|
||||
|
||||
def dt():
|
||||
return datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
|
||||
|
||||
|
||||
def train(Config,
|
||||
model,
|
||||
epoch_num,
|
||||
start_epoch,
|
||||
optimizer,
|
||||
exp_lr_scheduler,
|
||||
data_loader,
|
||||
save_dir,
|
||||
data_size=448,
|
||||
savepoint=500,
|
||||
checkpoint=1000
|
||||
):
|
||||
# savepoint: save without evalution
|
||||
# checkpoint: save with evaluation
|
||||
# print(epoch_num, start_epoch) # 360 0
|
||||
step = 0
|
||||
eval_train_flag = False
|
||||
rec_loss = []
|
||||
checkpoint_list = []
|
||||
|
||||
train_batch_size = data_loader['train'].batch_size
|
||||
train_epoch_step = data_loader['train'].__len__()
|
||||
train_loss_recorder = LossRecord(train_batch_size)
|
||||
if savepoint > train_epoch_step:
|
||||
savepoint = 1*train_epoch_step
|
||||
checkpoint = savepoint
|
||||
|
||||
date_suffix = dt()
|
||||
log_file = open(os.path.join(Config.log_folder, 'formal_log_r50_dcl_%s_%s.log'%(str(data_size), date_suffix)), 'a')
|
||||
|
||||
add_loss = nn.L1Loss()
|
||||
get_ce_loss = nn.CrossEntropyLoss()
|
||||
get_focal_loss = FocalLoss()
|
||||
get_angle_loss = AngleLoss()
|
||||
|
||||
for epoch in range(start_epoch,epoch_num-1):
|
||||
exp_lr_scheduler.step(epoch)
|
||||
model.train(True)
|
||||
|
||||
save_grad = []
|
||||
step = 0
|
||||
for batch_cnt, data in enumerate(data_loader['train']):
|
||||
step += 1
|
||||
loss = 0
|
||||
model.train(True)
|
||||
if Config.use_backbone:
|
||||
inputs, labels, img_names = data
|
||||
|
||||
inputs = Variable(inputs.cuda())
|
||||
labels = Variable(torch.from_numpy(np.array(labels)).cuda())
|
||||
|
||||
if Config.use_dcl:
|
||||
inputs, labels, labels_swap, swap_law, img_names = data
|
||||
inputs = Variable(inputs.cuda())
|
||||
labels = Variable(torch.from_numpy(np.array(labels)).long().cuda())
|
||||
labels_swap = Variable(torch.from_numpy(np.array(labels_swap)).long().cuda())
|
||||
swap_law = Variable(torch.from_numpy(np.array(swap_law)).float().cuda())
|
||||
optimizer.zero_grad()
|
||||
# print(inputs.size())
|
||||
if inputs.size(0) < 2*train_batch_size:
|
||||
outputs = model(inputs, inputs[0:-1:2])
|
||||
else:
|
||||
outputs = model(inputs, None)
|
||||
if Config.use_focal_loss:
|
||||
ce_loss = get_focal_loss(outputs[0], labels)
|
||||
else:
|
||||
ce_loss = get_ce_loss(outputs[0], labels) #交叉熵损失函数 用来分类
|
||||
|
||||
# if Config.use_Asoftmax:
|
||||
# fetch_batch = labels.size(0)
|
||||
# if batch_cnt % (train_epoch_step // 5) == 0:
|
||||
# angle_loss = get_angle_loss(outputs[3], labels[0:fetch_batch:2], decay=0.9)
|
||||
# else:
|
||||
# angle_loss = get_angle_loss(outputs[3], labels[0:fetch_batch:2])
|
||||
# loss += angle_loss
|
||||
|
||||
loss += ce_loss
|
||||
alpha_ = 1
|
||||
beta_ = 1
|
||||
gamma_ = 0.01 if Config.dataset == 'STCAR' or Config.dataset == 'AIR' else 1
|
||||
if Config.use_dcl:
|
||||
swap_loss = get_ce_loss(outputs[1], labels_swap) * beta_ # 对抗学习
|
||||
loss += swap_loss
|
||||
law_loss = add_loss(outputs[2], swap_law) * gamma_ # 重建学习损失
|
||||
loss += law_loss
|
||||
|
||||
loss.backward()
|
||||
torch.cuda.synchronize() #统计时间
|
||||
|
||||
optimizer.step()
|
||||
torch.cuda.synchronize()
|
||||
|
||||
if Config.use_dcl:
|
||||
# 8d不足就右对齐 加上-左对齐
|
||||
print('epoch: {} step: {:-8d} / {:d} loss=ce_loss+swap_loss+law_loss: {:6.4f} = {:6.4f} + {:6.4f} + {:6.4f} '.format(epoch, step, train_epoch_step, loss.detach().item(), ce_loss.detach().item(), swap_loss.detach().item(), law_loss.detach().item()), flush=True)
|
||||
# print(savepoint)
|
||||
if Config.use_backbone:
|
||||
print('step: {:-8d} / {:d} loss=ce_loss+swap_loss+law_loss: {:6.4f} = {:6.4f} '.format(step, train_epoch_step, loss.detach().item(), ce_loss.detach().item()), flush=True)
|
||||
rec_loss.append(loss.detach().item())# 对loss进行叠加的时候一定要加detach,返回的是叶子节点,不然会进行计算图的叠加,
|
||||
|
||||
train_loss_recorder.update(loss.detach().item())
|
||||
# evaluation & save
|
||||
# checkpoint = 5000
|
||||
if step % checkpoint == 0:
|
||||
rec_loss = []
|
||||
print(32*'-', flush=True)
|
||||
print('step: {:d} / {:d} global_step: {:8.2f} train_epoch: {:04d} rec_train_loss: {:6.4f}'.format(step, train_epoch_step, 1.0*step/train_epoch_step, epoch, train_loss_recorder.get_val()), flush=True)
|
||||
print('current lr:%s' % exp_lr_scheduler.get_lr(), flush=True)
|
||||
if eval_train_flag:
|
||||
trainval_acc1, trainval_acc2, trainval_acc3 = eval_turn(Config, model, data_loader['trainval'], 'trainval', epoch, log_file)
|
||||
if abs(trainval_acc1 - trainval_acc3) < 0.01:
|
||||
eval_train_flag = False
|
||||
|
||||
val_acc1, val_acc2, val_acc3 = eval_turn(Config, model, data_loader['val'], 'val', epoch, log_file)
|
||||
|
||||
save_path = os.path.join(save_dir, 'weights_%d_%d_%.4f_%.4f.pth'%(epoch, batch_cnt, val_acc1, val_acc3))
|
||||
torch.cuda.synchronize()
|
||||
torch.save(model.state_dict(), save_path)
|
||||
print('saved model to %s' % (save_path), flush=True)
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
# save only
|
||||
# elif step % savepoint == 0:
|
||||
# print('step')
|
||||
# train_loss_recorder.update(rec_loss)
|
||||
# rec_loss = []
|
||||
# save_path = os.path.join(save_dir, 'savepoint_weights-%d-%s.pth'%(step, dt()))
|
||||
#
|
||||
# checkpoint_list.append(save_path)
|
||||
# if len(checkpoint_list) == 6:
|
||||
# os.remove(checkpoint_list[0])
|
||||
# del checkpoint_list[0]
|
||||
# torch.save(model.state_dict(), save_path)
|
||||
# torch.cuda.empty_cache()
|
||||
|
||||
|
||||
log_file.close()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
import pdb
|
||||
|
||||
|
||||
class LossRecord(object):
|
||||
def __init__(self, batch_size):
|
||||
self.rec_loss = 0
|
||||
self.count = 0
|
||||
self.batch_size = batch_size
|
||||
|
||||
def update(self, loss):
|
||||
if isinstance(loss, list):
|
||||
avg_loss = sum(loss)
|
||||
avg_loss /= (len(loss)*self.batch_size)
|
||||
self.rec_loss += avg_loss
|
||||
self.count += 1
|
||||
if isinstance(loss, float):
|
||||
self.rec_loss += loss/self.batch_size
|
||||
self.count += 1
|
||||
|
||||
def get_val(self, init=False):
|
||||
pop_loss = self.rec_loss / self.count
|
||||
if init:
|
||||
self.rec_loss = 0
|
||||
self.count = 0
|
||||
return pop_loss
|
||||
|
||||
|
||||
def weights_normal_init(model, dev=0.01):
|
||||
if isinstance(model, list):
|
||||
for m in model:
|
||||
weights_normal_init(m, dev)
|
||||
else:
|
||||
for m in model.modules():
|
||||
if isinstance(m, nn.Conv2d):
|
||||
m.weight.data.normal_(0.0, dev)
|
||||
elif isinstance(m, nn.Linear):
|
||||
m.weight.data.normal_(0.0, dev)
|
||||
|
||||
|
||||
def clip_gradient(model, clip_norm):
|
||||
"""Computes a gradient clipping coefficient based on gradient norm."""
|
||||
totalnorm = 0
|
||||
for p in model.parameters():
|
||||
if p.requires_grad:
|
||||
modulenorm = p.grad.data.norm()
|
||||
totalnorm += modulenorm ** 2
|
||||
totalnorm = torch.sqrt(totalnorm).item()
|
||||
norm = (clip_norm / max(totalnorm, clip_norm))
|
||||
for p in model.parameters():
|
||||
if p.requires_grad:
|
||||
p.grad.mul_(norm)
|
||||
|
||||
|
||||
def Linear(in_features, out_features, bias=True):
|
||||
"""Weight-normalized Linear layer (input: N x T x C)"""
|
||||
m = nn.Linear(in_features, out_features, bias=bias)
|
||||
m.weight.data.uniform_(-0.1, 0.1)
|
||||
if bias:
|
||||
m.bias.data.uniform_(-0.1, 0.1)
|
||||
return m
|
||||
|
||||
|
||||
class convolution(nn.Module):
|
||||
def __init__(self, k, inp_dim, out_dim, stride=1, with_bn=True):
|
||||
super(convolution, self).__init__()
|
||||
|
||||
pad = (k - 1) // 2
|
||||
self.conv = nn.Conv2d(inp_dim, out_dim, (k, k), padding=(pad, pad), stride=(stride, stride), bias=not with_bn)
|
||||
self.bn = nn.BatchNorm2d(out_dim) if with_bn else nn.Sequential()
|
||||
self.relu = nn.ReLU(inplace=True)
|
||||
|
||||
def forward(self, x):
|
||||
conv = self.conv(x)
|
||||
bn = self.bn(conv)
|
||||
relu = self.relu(bn)
|
||||
return relu
|
||||
|
||||
class fully_connected(nn.Module):
|
||||
def __init__(self, inp_dim, out_dim, with_bn=True):
|
||||
super(fully_connected, self).__init__()
|
||||
self.with_bn = with_bn
|
||||
|
||||
self.linear = nn.Linear(inp_dim, out_dim)
|
||||
if self.with_bn:
|
||||
self.bn = nn.BatchNorm1d(out_dim)
|
||||
self.relu = nn.ReLU(inplace=True)
|
||||
|
||||
def forward(self, x):
|
||||
linear = self.linear(x)
|
||||
bn = self.bn(linear) if self.with_bn else linear
|
||||
relu = self.relu(bn)
|
||||
return relu
|
||||
|
||||
class residual(nn.Module):
|
||||
def __init__(self, k, inp_dim, out_dim, stride=1, with_bn=True):
|
||||
super(residual, self).__init__()
|
||||
|
||||
self.conv1 = nn.Conv2d(inp_dim, out_dim, (3, 3), padding=(1, 1), stride=(stride, stride), bias=False)
|
||||
self.bn1 = nn.BatchNorm2d(out_dim)
|
||||
self.relu1 = nn.ReLU(inplace=True)
|
||||
|
||||
self.conv2 = nn.Conv2d(out_dim, out_dim, (3, 3), padding=(1, 1), bias=False)
|
||||
self.bn2 = nn.BatchNorm2d(out_dim)
|
||||
|
||||
self.skip = nn.Sequential(
|
||||
nn.Conv2d(inp_dim, out_dim, (1, 1), stride=(stride, stride), bias=False),
|
||||
nn.BatchNorm2d(out_dim)
|
||||
) if stride != 1 or inp_dim != out_dim else nn.Sequential()
|
||||
self.relu = nn.ReLU(inplace=True)
|
||||
|
||||
def forward(self, x):
|
||||
conv1 = self.conv1(x)
|
||||
bn1 = self.bn1(conv1)
|
||||
relu1 = self.relu1(bn1)
|
||||
|
||||
conv2 = self.conv2(relu1)
|
||||
bn2 = self.bn2(conv2)
|
||||
|
||||
skip = self.skip(x)
|
||||
return self.relu(bn2 + skip)
|
||||
+21
-25
@@ -6,19 +6,11 @@ import os
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
from jpg import jpg
|
||||
txt_root_path = "E:\\dataset\\VOC5"
|
||||
txt_root_path = "/data/DataManagement/Project/005_kunmingdianchi/0002_20220412_800_200/Dataset/VOC0050201"
|
||||
#xml_files = glob('./temp2/*.xml')
|
||||
f_num = open(txt_root_path+"/num.txt", "r")
|
||||
|
||||
num_count = f_num.read()
|
||||
f_num.close()
|
||||
if num_count == "":
|
||||
num_count=0
|
||||
else:
|
||||
num_count= int(num_count)
|
||||
num = 0
|
||||
root_path = "E:\\dataset\\VOC5\\Annotations"
|
||||
class_name = ["Anser albifrons" ,"Fulica atra" ,"Leucogeranus leucogeranus" ,"Egretta garzetta","Platalea leucorodia" ,"Mergellus albellus" ,"Grus monacha" ,"Tringa ochropus" ,"Numenius arquata" ,"Anser indicus","Anas zonorhyncha","Ardea cinerea","Mareca strepera" ,"Mareca penelope" ,"Tadorna ferruginea","Ardea alba","Numenius madagascariensis" ,"Botaurus stellaris" ,"Ciconia boyciana" ,"Anser fabalis" ,"Recurvirostra avosetta" ,"Podiceps cristatus","Vanellus vanellus" ,"Aythya fuligula" ,"Tringa erythropus","Calidris alpina" ,"Ciconia nigra" ,"Gallinula chloropus","Porphyrio poliocephalus","Larus ridibundus" ,"Anser cygnoides" ,"Charadrius alexandrinusw" ,"Pluvialis squatarola" ,"Grus grus" ,"Anser anser" ,"Pluvialis fulva" ,"Charadrius dubius" ,"Anas crecca","Anas platyrhynchos","Spatula clypeata","Phalacrocorax carbo","Mergus merganser" ,"Tadorna tadorna" ,"Tringa nebulariaw","Bucephala clangula" ,"Gallinago gallinago" ,"Anser erythropus","Cygnus columbianus" ,"Ichthyaetus ichthyaetus","Anas acuta" ,"Ardea intermedia"]
|
||||
image_T = 50
|
||||
num_count = 0
|
||||
root_path = "/data/DataManagement/Project/005_kunmingdianchi/0002_20220412_800_200/Dataset/VOC0050201/Annotations/"
|
||||
def cv2_crop(im, box):
|
||||
'''cv2实现类似PIL的裁剪
|
||||
|
||||
@@ -91,17 +83,17 @@ def convert(size, box):
|
||||
# print(num_count)
|
||||
|
||||
xml_files = glob(os.path.join(root_path,"*.xml"))
|
||||
print(os.path.join(root_path.replace("Annotations","JPEGOriginal")))
|
||||
jpg(os.path.join(root_path.replace("Annotations","JPEGOriginal")))
|
||||
#print(os.path.join(root_path.replace("Annotations","JPEGImages")))
|
||||
jpg(os.path.join(root_path.replace("Annotations","JPEGImages")))
|
||||
f = open(txt_root_path+"/Hatcher_ALL.txt", "a")
|
||||
txt_lists = []
|
||||
for xml_file in tqdm(xml_files):
|
||||
|
||||
print(xml_file+" is doing")
|
||||
#print(xml_file+" is doing")
|
||||
DOMTree = xml.dom.minidom.parse(xml_file)
|
||||
collection = DOMTree.documentElement
|
||||
#img_name = collection.getElementsByTagName("filename")[0].childNodes[0].data
|
||||
img_name = xml_file.replace("\\Annotations\\","\\JPEGOriginal\\").replace(".xml",".jpg")
|
||||
img_name = xml_file.replace("Annotations","JPEGImages").replace(".xml",".jpg")
|
||||
objects = collection.getElementsByTagName("object")
|
||||
#img = cv2.imread(img_name)
|
||||
img = cv2.imdecode(np.fromfile(img_name,dtype=np.uint8),-1)
|
||||
@@ -116,19 +108,23 @@ for xml_file in tqdm(xml_files):
|
||||
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
|
||||
ratio_x = (3840.0/1024.0)
|
||||
ratio_y = (2160.0/768.0)
|
||||
print(ratio_x," ",ratio_y)
|
||||
print(type(xmin))
|
||||
ratio_x = (3840.0/3840.0)
|
||||
ratio_y = (2160.0/2160.0)
|
||||
#print(ratio_x," ",ratio_y)
|
||||
#print(type(xmin))
|
||||
#exit()
|
||||
xmin = int(float(xmin)*ratio_x)
|
||||
xmax = int(float(xmax)*ratio_x)
|
||||
ymin = int(float(ymin)*ratio_y)
|
||||
ymax = int(float(ymax)*ratio_y)
|
||||
class_index = class_name.index(str(name).replace("\t","").strip())
|
||||
if ((xmax - xmin)<image_T) | ((ymax - ymin)<image_T):
|
||||
continue
|
||||
#class_index = class_name.index(str(name).replace("\t","").strip())
|
||||
img1 = cv2_crop(img,(xmin, ymin,xmax, ymax))
|
||||
cv2.imwrite("E:\\dataset\\VOC5\Hatcher_One\\" + str(name).replace("\t","").strip().replace(" ","_" )+"_{}.jpg".format(num_count), img1)
|
||||
txt_lists.append(str(name).replace("\t","").strip().replace(" ","_" )+"_{}.jpg".format(num_count)+" "+str(class_index)+'\n')
|
||||
if not os.path.exists(os.path.join(root_path.replace("Annotations","FineDataset_{}".format(str(image_T))),str(name).replace("\t","").strip())):
|
||||
os.makedirs(os.path.join(root_path.replace("Annotations","FineDataset_{}".format(str(image_T))),str(name).replace("\t","").strip()))
|
||||
cv2.imwrite(os.path.join(root_path.replace("Annotations","FineDataset_{}".format(str(image_T))),str(name).replace("\t","").strip(),"{}.jpg".format(str(num_count).zfill(5))), img1)
|
||||
#txt_lists.append(str(name).replace("\t","").strip()+"{}.jpg".format(str(num_count).zfill(5))+" "+str(class_index)+'\n')
|
||||
#f.write(str(name).replace("\t","").strip().replace(" ","_" )+"_{}.jpg".format(num_count)+" "+str(class_index)+'\n')
|
||||
num_count += 1
|
||||
for txt_list in txt_lists:
|
||||
@@ -138,8 +134,8 @@ f_num = open("./num.txt", "w")
|
||||
f_num.write(str(num_count))
|
||||
f_num.close()
|
||||
print(num_count)
|
||||
for xml_file in tqdm(xml_files):
|
||||
os.remove(xml_file)
|
||||
# for xml_file in tqdm(xml_files):
|
||||
# os.remove(xml_file)
|
||||
|
||||
#os.remove(xml_file)
|
||||
print(num_count)
|
||||
|
||||
@@ -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-20191Line truncated
|
||||
+27
-1
@@ -35,6 +35,32 @@ def images_to_video(InputPath, OutputPath):
|
||||
for i in range(len(img_array)):
|
||||
out.write(img_array[i])
|
||||
out.release()
|
||||
def images_to_video_bigtosmall(InputPath, OutputPath):
|
||||
img_array = []
|
||||
img_list = [os.path.join(InputPath,nm) for nm in os.listdir(InputPath) if 1]
|
||||
img_list.sort()
|
||||
i=0
|
||||
for filename in img_list:
|
||||
print(i)
|
||||
i+=1
|
||||
img = cv2.imread(filename)
|
||||
if i == 1:
|
||||
ImgHeight = np.shape(img)[0]
|
||||
ImgWidth = np.shape(img)[1]
|
||||
if img is None:
|
||||
print(filename + " is error!")
|
||||
continue
|
||||
img_array.append(img)
|
||||
if (i % 1500)==0:
|
||||
|
||||
# 图片的大小需要一致
|
||||
#img_array, size = resize(img_array, 'largest')
|
||||
fps = 25
|
||||
out = cv2.VideoWriter(OutputPath.replace("Detectionnew1","Detectionnew1{}".format(str(i))), cv2.VideoWriter_fourcc(*'DIVX'), fps, (ImgWidth,ImgHeight))
|
||||
|
||||
for j in range(len(img_array)):
|
||||
out.write(img_array[j])
|
||||
out.release()
|
||||
def images_to_video_big(InputPath, OutputPath):
|
||||
img_array = []
|
||||
img_list = [os.path.join(InputPath,nm) for nm in os.listdir(InputPath) if 1]
|
||||
@@ -75,6 +101,6 @@ def images_to_video_big(InputPath, OutputPath):
|
||||
|
||||
if __name__ == "__main__":
|
||||
T1 = time.time()
|
||||
images_to_video('../data_MPKFNet/result/images', '../data_MPKFNet/result_vedio/images.avi')
|
||||
images_to_video('../2', './test.avi')
|
||||
T2 = time.time()
|
||||
print("chengxuyunxingshijian is ",(T2-T1)*1000)
|
||||
@@ -1 +0,0 @@
|
||||
/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/视频监控截图/录像监控-白琵鹭.mp4_snapshot_00.17_[2020.04.10_17.53.08].jpg
|
||||
@@ -1 +0,0 @@
|
||||
/data1/Hatcher/DATA/Hat_Raw_Data/dongtingD/灰鹤.mp4
|
||||
+1
-1
@@ -11,7 +11,7 @@ import torch
|
||||
import os
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
os.environ['CUDA_VISIBLE_DEVICE'] = '6'
|
||||
os.environ['CUDA_VISIBLE_DEVICE'] = '5'
|
||||
|
||||
class MCNN(nn.Module):
|
||||
def __init__(self, load_vgg=True):
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import torch.nn as nn
|
||||
import torch
|
||||
from pytorch_pretrained_vit import ViT,VoT,VVT
|
||||
from vgg import vgg16 as backbone
|
||||
from common import global_para as gp
|
||||
|
||||
|
||||
|
||||
class Multi_transform_image(nn.Module):
|
||||
def __init__(self, load_pretrain=True):
|
||||
super(Multi_transform_image, self).__init__()
|
||||
#frontend_feat
|
||||
#self.frontend = backbone(pretrained=load_pretrain)
|
||||
self.pixel_model = ViT('B_16_imagenet1k', pretrained=True,num_classes=gp.FineClassNum,image_size=448)
|
||||
def forward(self, x):
|
||||
x = x.float()
|
||||
output_pixel = self.pixel_model(x)
|
||||
return output_pixel
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
||||
print(device)
|
||||
net = Multi_transform().to(device)
|
||||
input1 = torch.randn(1, 3, 448,448).to(device)
|
||||
input2 = torch.randn(1, 3, 448, 448).to(device)
|
||||
output = net(input1,input2)
|
||||
print(output.shape)
|
||||
# torch.Size([1, 1, 96, 128]) torch.Size([1, 5]) torch.Size([1, 13])
|
||||
@@ -6,6 +6,7 @@ import numpy as np
|
||||
import matplotlib as mpl
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
print("数据")
|
||||
# 这里导入你自己的数据
|
||||
# ......
|
||||
# ......
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
output/
|
||||
mot_benchmark
|
||||
+674
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
{one line to give the program's name and a brief idea of what it does.}
|
||||
Copyright (C) {year} {name of author}
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
{project} Copyright (C) {year} {fullname}
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
SORT
|
||||
=====
|
||||
|
||||
A simple online and realtime tracking algorithm for 2D multiple object tracking in video sequences.
|
||||
See an example [video here](https://alex.bewley.ai/misc/SORT-MOT17-06-FRCNN.webm).
|
||||
|
||||
By Alex Bewley
|
||||
|
||||
### Introduction
|
||||
|
||||
SORT is a barebones implementation of a visual multiple object tracking framework based on rudimentary data association and state estimation techniques. It is designed for online tracking applications where only past and current frames are available and the method produces object identities on the fly. While this minimalistic tracker doesn't handle occlusion or re-entering objects its purpose is to serve as a baseline and testbed for the development of future trackers.
|
||||
|
||||
SORT was initially described in [this paper](http://arxiv.org/abs/1602.00763). At the time of the initial publication, SORT was ranked the best *open source* multiple object tracker on the [MOT benchmark](https://motchallenge.net/results/2D_MOT_2015/).
|
||||
|
||||
**Note:** A significant proportion of SORT's accuracy is attributed to the detections.
|
||||
For your convenience, this repo also contains *Faster* RCNN detections for the MOT benchmark sequences in the [benchmark format](https://motchallenge.net/instructions/). To run the detector yourself please see the original [*Faster* RCNN project](https://github.com/ShaoqingRen/faster_rcnn) or the python reimplementation of [py-faster-rcnn](https://github.com/rbgirshick/py-faster-rcnn) by Ross Girshick.
|
||||
|
||||
**Also see:**
|
||||
A new and improved version of SORT with a Deep Association Metric implemented in tensorflow is available at [https://github.com/nwojke/deep_sort](https://github.com/nwojke/deep_sort) .
|
||||
|
||||
### License
|
||||
|
||||
SORT is released under the GPL License (refer to the LICENSE file for details) to promote the open use of the tracker and future improvements. If you require a permissive license contact Alex (alex@bewley.ai).
|
||||
|
||||
### Citing SORT
|
||||
|
||||
If you find this repo useful in your research, please consider citing:
|
||||
|
||||
@inproceedings{Bewley2016_sort,
|
||||
author={Bewley, Alex and Ge, Zongyuan and Ott, Lionel and Ramos, Fabio and Upcroft, Ben},
|
||||
booktitle={2016 IEEE International Conference on Image Processing (ICIP)},
|
||||
title={Simple online and realtime tracking},
|
||||
year={2016},
|
||||
pages={3464-3468},
|
||||
keywords={Benchmark testing;Complexity theory;Detectors;Kalman filters;Target tracking;Visualization;Computer Vision;Data Association;Detection;Multiple Object Tracking},
|
||||
doi={10.1109/ICIP.2016.7533003}
|
||||
}
|
||||
|
||||
|
||||
### Dependencies:
|
||||
|
||||
To install required dependencies run:
|
||||
```
|
||||
$ pip install -r requirements.txt
|
||||
```
|
||||
|
||||
|
||||
### Demo:
|
||||
|
||||
To run the tracker with the provided detections:
|
||||
|
||||
```
|
||||
$ cd path/to/sort
|
||||
$ python sort.py
|
||||
```
|
||||
|
||||
To display the results you need to:
|
||||
|
||||
1. Download the [2D MOT 2015 benchmark dataset](https://motchallenge.net/data/2D_MOT_2015/#download)
|
||||
0. Create a symbolic link to the dataset
|
||||
```
|
||||
$ ln -s /path/to/MOT2015_challenge/data/2DMOT2015 mot_benchmark
|
||||
```
|
||||
0. Run the demo with the ```--display``` flag
|
||||
```
|
||||
$ python sort.py --display
|
||||
```
|
||||
|
||||
|
||||
### Main Results
|
||||
|
||||
Using the [MOT challenge devkit](https://motchallenge.net/devkit/) the method produces the following results (as described in the paper).
|
||||
|
||||
Sequence | Rcll | Prcn | FAR | GT MT PT ML| FP FN IDs FM| MOTA MOTP MOTAL
|
||||
--------------- |:----:|:----:|:----:|:-------------:|:-------------------:|:------------------:
|
||||
TUD-Campus | 68.5 | 94.3 | 0.21 | 8 6 2 0| 15 113 6 9| 62.7 73.7 64.1
|
||||
ETH-Sunnyday | 77.5 | 81.9 | 0.90 | 30 11 16 3| 319 418 22 54| 59.1 74.4 60.3
|
||||
ETH-Pedcross2 | 51.9 | 90.8 | 0.39 | 133 17 60 56| 330 3014 77 103| 45.4 74.8 46.6
|
||||
ADL-Rundle-8 | 44.3 | 75.8 | 1.47 | 28 6 16 6| 959 3781 103 211| 28.6 71.1 30.1
|
||||
Venice-2 | 42.5 | 64.8 | 2.75 | 26 7 9 10| 1650 4109 57 106| 18.6 73.4 19.3
|
||||
KITTI-17 | 67.1 | 92.3 | 0.26 | 9 1 8 0| 38 225 9 16| 60.2 72.3 61.3
|
||||
*Overall* | 49.5 | 77.5 | 1.24 | 234 48 111 75| 3311 11660 274 499| 34.0 73.3 35.1
|
||||
|
||||
|
||||
### Using SORT in your own project
|
||||
|
||||
Below is the gist of how to instantiate and update SORT. See the ['__main__'](https://github.com/abewley/sort/blob/master/sort.py#L239) section of [sort.py](https://github.com/abewley/sort/blob/master/sort.py#L239) for a complete example.
|
||||
|
||||
from sort import *
|
||||
|
||||
#create instance of SORT
|
||||
mot_tracker = Sort()
|
||||
|
||||
# get detections
|
||||
...
|
||||
|
||||
# update SORT
|
||||
track_bbs_ids = mot_tracker.update(detections)
|
||||
|
||||
# track_bbs_ids is a np array where each row contains a valid bounding box and track_id (last column)
|
||||
...
|
||||
|
||||
|
||||
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user