def _main(): args = get_args() if args.image: detect_img(YOLO(args)) else: detect_video(YOLO(args), args.video, args.output) print('Well done!!!')
def testview(): yolo = YOLO(score=0.15) path = 'yolo/00013000_640x480.png' try: image = Image.open(path) except: print('Open Error! Check path and try again!') else: r_image, posList = yolo.detect_image(image) # r_image.show() print(posList) # yolo.close_session() return render_template('posList.html', posList=posList)
def _main(): # Get the arguments args = get_args() if args.image: # Image detection mode print('[i] ==> Image detection mode\n') detect_img(YOLO(args)) else: print('[i] ==> Video detection mode\n') # Call the detect_video method here detect_video(YOLO(args), args.video, args.output) print('Well done!!!')
def __init__(self, load_checkpoint=True, is_site=False, model_image_size=[0, 0]): self.img_counter = 0 # for yolo debug self.is_site = is_site self.is_camera = is_camera rospy.loginfo("[tl_classifier] is site: %d", self.is_site) if not is_site and self.is_camera: rospy.loginfo( "[tl_classifier] Loading simulator classification model") self.model = self.simple_conv_net() checkpoint = '../../src/model_files/simulator_model_weights.08-0.03.hdf5' if load_checkpoint: self.model.load_weights(checkpoint) self.model._make_predict_function() elif self.is_camera: self.yolo = YOLO(model_image_size=model_image_size) # self.yolo = YOLO() self.real_traffic_light_net() rospy.loginfo( "[tl_classifier] Loading real life classification model") # TODO - add trained real traffic light net that will work on carla checkpoint = None
def __init__(self, type, scale=1, **kwargs): self.type = type self.scale = scale if self.type == 'yolo': from yolo.yolo import YOLO self.face_detector = YOLO(img_size=kwargs['model_img_size']) if self.type == 'haar': self.face_detector = cv2.CascadeClassifier( 'cascade_model/cascade_ignore_shirt.xml') elif self.type == 'mtcnn': from mtcnn import MTCNN kwargs['min_face_size'] //= self.scale self.min_face_size = kwargs['min_face_size'] self.face_detector = MTCNN(**kwargs) elif self.type == 'mtcnn_torch': import mtcnn_torch as mtcnn pnet, rnet, onet = mtcnn.get_net_caffe('mtcnn_torch/model') self.face_detector = mtcnn.FaceDetector(pnet, rnet, onet, device='cuda:0')
def train_xnet(dataset=None, defaults=None, train_config=None, callbacks=None, mode="finetune"): """Trains an X-Net/YOLO model :param dataset: dataset path (default: None) :param defaults: default dict (default: None) :param train_config: training config dict (default: None) :param callbacks: list of callbacks (default: None) :param mode: 'finetune' or 'full train' (default: finetune) :returns: trained x-net model """ global DATASET, DEFAULTS, TRAIN_CONFIG, CALLBACKS # overwriting default configs with user-supplied configs DATASET = dataset if dataset is not None else DATASET DEFAULTS = {**DEFAULTS, **defaults} if defaults is not None else DEFAULTS if mode == "full train": TRAIN_CONFIG = {**TRAIN_CONFIG, **FULL_TRAIN_CONFIG} elif mode == "finetune": TRAIN_CONFIG = {**TRAIN_CONFIG, **FINETUNE_CONFIG} else: raise ValueError("supported modes are 'full train' and 'finetune'") TRAIN_CONFIG = {**TRAIN_CONFIG, **train_config} if train_config is not None else TRAIN_CONFIG CALLBACKS = {**CALLBACKS, **callbacks} if callbacks is not None else CALLBACKS # cd into dataset directory os.chdir(DATASET) # make and compile x-net xnet = YOLO(**DEFAULTS) xnet.prepare_for_training(freeze=YOLO.freeze, optimizer=TRAIN_CONFIG["optimizer"], mode=mode) # train x-net xnet.train(annotation_path=TRAIN_CONFIG["annotation_path"], save_path=TRAIN_CONFIG["log_dir"] + TRAIN_CONFIG["save_path"], epochs=TRAIN_CONFIG["epochs"], batch_size=TRAIN_CONFIG["batch_size"], val_split=TRAIN_CONFIG["val_split"], callbacks=CALLBACKS ) return xnet
class ConfigDefault: def __init__(self): self.model = 'model-weights/YOLO_Face.h5' self.anchors = 'cfg/yolo_anchors.txt' self.classes = 'cfg/face_classes.txt' self.score = 0.5 self.iou = 0.45 self.img_size = (416, 416) self.image = False self.output = 'defaults/' args = ConfigDefault() model = YOLO(args) PATH_SOURCE_ANNOTATION = '/home/carlosb/python-workspace/upc-aidl-19-team4/datasets/FDDB-folds' PATH_SOURCE_WIDER_TRAIN_ANNOTATION = '/home/carlosb/python-workspace/upc-aidl-19-team4/datasets/wider_face_split/wider_face_train_bbx_gt.txt' PATH_SOURCE_WIDER_VALID_ANNOTATION = '/home/carlosb/python-workspace/upc-aidl-19-team4/datasets/wider_face_split/wider_face_val_bbx_gt.txt' PATH_SOURCE_WIDER_TRAIN_IMAGES = '/home/carlosb/python-workspace/upc-aidl-19-team4/datasets/WIDER_train' PATH_SOURCE_WIDER_VALID_IMAGES = '/home/carlosb/python-workspace/upc-aidl-19-team4/datasets/WIDER_val' def get_fddb_dataset(): from db.FDDB_dataset import FDDBDataset dataset = FDDBDataset() dataset.read(PATH_SOURCE_ANNOTATION) test_data = dataset.get_data()[1]
plt.show(block=False) plt.waitforbuttonpress(0) print("Continuing slideshow") # ---------------- TESTING ---------------- if __name__ == "__main__": if "/home/ryan" in os.path.expanduser("~"): path_to_sixray = "/media/ryan/Data/x-ray-datasets/sixray/images/" elif "/Users/ryan" in os.path.expanduser("~"): path_to_sixray = "/Users/ryan/data/sixray/" else: raise ValueError("cannot run tests on this computer") annotations = retrieve_annotations( path_to_sixray.replace("images/", "") + "annotations.csv") sorted_imgs = sort_by_class(annotations) imgs = ["P03879.jpg", "P06792.jpg", "P08109.jpg", "P06241.jpg"] imgs = [os.path.join(path_to_sixray, img) for img in imgs] detections = "results/examples/detection.txt" # slideshow(imgs, detections, sec_per_img=1) net = YOLO(**DEFAULTS) test(net, sorted_imgs["gun"], display=False, write_to="results/examples/detection.txt")
from yolo.yolo import YOLO import numpy as np import imutils # from edge import get_new if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", type=str, default="video/offside2_2.mp4", help="path to input video file") args = vars(ap.parse_args()) vs = cv2.VideoCapture(args["video"]) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = YOLO() while True: frame = vs.read() frame = frame[1] if args.get("video", False) else frame frame = imutils.resize(frame, height=1080 // 2, width=1920 // 2) # frame = get_new(frame) # print(frame.shape) frame = cv2.resize(frame, (frame.shape[1] // 2, frame.shape[0] // 2)) frame = Image.fromarray(np.uint8(frame)) # print(np.array(frame).shape) frame = model.detect_image(frame) # frame = np.array(frame)[:,:,:-1] frame = cv2.cvtColor(np.asarray(frame), cv2.COLOR_RGB2BGR) cv2.imshow("result", frame) cv2.waitKey(1)
from yolo.yolo import YOLO from PIL import Image from glob import glob import os yolo_defaults = { "model_path": 'yolo/model_data/custom_model_test9.h5', "classes_path": 'yolo/model_data/custom_classes4.txt' } # yolo = YOLO() yolo = YOLO(**yolo_defaults) def detect_img(filename, output=None, car_dist_mode=False): image = Image.open(filename) image.thumbnail((640, 640), Image.ANTIALIAS) image.save(filename) r_image = yolo.detect_image(image, car_dist_mode=car_dist_mode) print("image Detect by Yolo : {}".format(filename)) if output: r_image.save(output) def main(): path2 = 'D:/기타/sample/' files = glob(path2 + '*.jpg') for file in files: name = os.path.split(file)[-1] detect_img(file, path2 + 'out/{}'.format(name))
from yolo.yolo import YOLO from PIL import Image from glob import glob import os yolo_defaults = { "model_path": 'yolo/model_data/custom_model_test9.h5', "classes_path": 'yolo/model_data/custom_classes4.txt' } # yolo = YOLO() # coco dataset h5 yolo = YOLO(**yolo_defaults) # custom h5 def detect_img(filename, output=None, car_dist_mode=False): image = Image.open(filename) image.thumbnail((640, 640), Image.ANTIALIAS) image.save(filename) r_image = yolo.detect_image(image, car_dist_mode=car_dist_mode) print("image Detect by Yolo : {}".format(filename)) if output: r_image.save(output) def main(): path2 = 'D:/기타/sample/' files = glob(path2 + '*.jpg') for file in files: name = os.path.split(file)[-1] detect_img(file, path2 + 'out/{}'.format(name))
from yolo.yolo import YOLO from yolo.configs import Config cfg = Config() yolo = YOLO( input_shape=(320, 320, 3), anchors=cfg.anchors, anchors_mask=cfg.anchors_mask, num_classes=cfg.num_classes, ) model = yolo.model()
resultqueues.append(torch.multiprocessing.Queue()) worker = Multi_Tracker(i, frame, dataqueues[-1], resultqueues[-1]) worker.start() # commandqueue = torch.multiprocessing.Queue() # controlProcess = torch.multiprocessing.Process(target=command_process, args=(commandqueue,)) # controlProcess.start() balldatequeue = torch.multiprocessing.Queue() ballresultqueue = torch.multiprocessing.Queue() ballTrack = torch.multiprocessing.Process(target=ball_track, args=(balldatequeue, ballresultqueue)) ballTrack.start() yolo = YOLO() framecount = -1 while True: # for i in range(1000): # frame=vs.read() frame = vs.read() frame = frame[1] if args.get("video", False) else frame if frame is None: break #frame = imutils.resize(frame, height=frame.shape[0]//scale_size, width=frame.shape[1]//scale_size) frame = cv2.resize(frame, (1920, 1080)) # frame = imutils.resize(frame, width=1920, height=1080) origin_frame = frame.copy() framecount += 1
def main(flags): yolo = YOLO() line = LINE() vid = cv2.VideoCapture( flags.input) if flags.input != '' else cv2.VideoCapture(0) if not vid.isOpened(): raise IOError("Couldn't open webcam or video") # video_FourCC = int(vid.get(cv2.CAP_PROP_FOURCC)) video_FourCC = cv2.VideoWriter_fourcc(*flags.fourcc) video_fps = vid.get(cv2.CAP_PROP_FPS) video_size = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)), int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))) isOutput = True if flags.output != '' else False if isOutput: print("!!! TYPE:", type(flags.output), type(video_FourCC), type(video_fps), type(video_size)) out = cv2.VideoWriter(flags.output, video_FourCC, video_fps, video_size) accum_time = 0 curr_fps = 0 fps = "FPS: ??" prev_time = timer() while vid.isOpened(): ret, frame = vid.read() if ret: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = line.calculate_img(frame) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) image = Image.fromarray(frame) image = yolo.detect_image(image) result = np.asarray(image) curr_time = timer() exec_time = curr_time - prev_time prev_time = curr_time accum_time = accum_time + exec_time curr_fps += 1 if accum_time > 1: accum_time = accum_time - 1 fps = "FPS: " + str(curr_fps) curr_fps = 0 cv2.putText(result, text=fps, org=(3, 15), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.50, color=(255, 0, 0), thickness=2) if isOutput: out.write(result) if flags.show: cv2.namedWindow("result", cv2.WINDOW_NORMAL) cv2.imshow("result", result) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break yolo.close_session()