def on_init(): global detector global labels global anchors gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: # Restrict TensorFlow to only allocate 1GB of memory on the first GPU try: tf.config.experimental.set_virtual_device_configuration( gpus[0], [ tf.config.experimental.VirtualDeviceConfiguration( memory_limit=2048) ]) logical_gpus = tf.config.experimental.list_logical_devices('GPU') sys.stdout.write( f"{len(gpus)} Physical GPUs, {len(logical_gpus)} Logical GPUs\n" ) sys.stdout.flush() except RuntimeError as e: # Virtual devices must be set before GPUs have been initialized sys.stdout.write(e) sys.stdout.flush() detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath(detection_model_path=weights) detector.setJsonPath(configuration_json=config) detector.loadModel() detection_model_json = json.load(open(config)) labels = detection_model_json["labels"] anchors = detection_model_json["anchors"] return True
def __init__(self): execution_path = os.getcwd() self.detector = CustomObjectDetection() self.detector.setModelTypeAsYOLOv3() self.detector.setModelPath("detection_model-ex-044--loss-0022.165.h5") self.detector.setJsonPath("detection_config.json") self.detector.loadModel()
def setUpNN(model_path, json_path): detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath(model_path) detector.setJsonPath(json_path) detector.loadModel() return detector
def init_object_detection(self): print("Initializing object detection model: {}".format(self.DIR_MODEL)) self.detector = CustomObjectDetection() self.detector.setModelTypeAsYOLOv3() self.detector.setJsonPath(self.DIR_CONFIG) self.detector.setModelPath(self.DIR_MODEL) self.detector.loadModel() print("Model loaded")
def load_model(): detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath( "tomato/models/detection_model-ex-052--loss-0033.691.h5") detector.setJsonPath("tomato/json/detection_config.json") detector.loadModel() return detector
class FireDetection: def __init__(self): self.execution_path = "/home/swc/spark-2.4.5-bin-hadoop2.7/CCTV-pyspark/" self.detector = CustomObjectDetection() self.detector.setModelTypeAsYOLOv3() self.detector.setModelPath(detection_model_path=os.path.join( self.execution_path, "detection_model-ex-33--loss-4.97.h5")) self.detector.setJsonPath(configuration_json=os.path.join( self.execution_path, "detection_config.json")) self.detector.loadModel() def FireDetection(self, decoded_img): detections = self.detector.detectObjectsFromImage( input_image=decoded_img, input_type="array", output_image_path=os.path.join(self.execution_path, "fire_detected.jpg"), minimum_percentage_probability=40) if len(detections) == 0: fire_broken = False else: fire_broken = True return fire_broken
def init(): global detector execution_path = os.getcwd() detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath(detection_model_path=os.path.join( execution_path, "detection_model-ex-33--loss-4.97.h5")) detector.setJsonPath(configuration_json=os.path.join( execution_path, "detection_config.json")) detector.loadModel()
def __init__(self): self.execution_path = "/home/swc/spark-2.4.5-bin-hadoop2.7/CCTV-pyspark/" self.detector = CustomObjectDetection() self.detector.setModelTypeAsYOLOv3() self.detector.setModelPath(detection_model_path=os.path.join( self.execution_path, "detection_model-ex-33--loss-4.97.h5")) self.detector.setJsonPath(configuration_json=os.path.join( self.execution_path, "detection_config.json")) self.detector.loadModel()
def init_video_processing(configs): global global_configs, rekognition_client, image_ai_detector print("Initiated video processing") global_configs = configs session = boto3.Session(profile_name='rekognition') rekognition_client = session.client('rekognition', region_name='us-east-1') image_ai_detector = CustomObjectDetection() image_ai_detector.setModelTypeAsYOLOv3() image_ai_detector.setModelPath( "../model/detection_model-ex-002--loss-0000.363.h5") image_ai_detector.setJsonPath("../model/detection_config.json") image_ai_detector.loadModel()
def __init__(self): self.detector = CustomObjectDetection() self.detector.setModelTypeAsYOLOv3() self.detector.setModelPath("detection_model-ex-046--loss-8.848.h5") self.detector.setJsonPath("detection1_config.json") self.detector.loadModel() self.username="******" self.password="******" self.data={ "kadi" : f"{self.username}", "sifre" : f"{self.password}" } self.baseurl="***" #http://blabla self.signin()
def model_load(detection_model_path, json_path, cls_model_path,): detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath(detection_model_path) detector.setJsonPath(json_path) detector.loadModel() model = tf.keras.models.load_model(cls_model_path) return detector, model
def main(): if (len(sys.argv) < 2): print("Usage: " + sys.argv[0] + " <model_dir> [image_file] [threshold]") exit(-1) model_dir = sys.argv[1] if (len(sys.argv) > 2): image_name = sys.argv[2] else: print("Enter image or directory name: ") image_name = input() dest_dir = model_dir threshold = 0.75 if (len(sys.argv) > 3): threshold = sys.argv[3] detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath(os.path.join(model_dir, "model_berry.h5")) detector.setJsonPath(os.path.join(model_dir, "detection_config.json")) print("Loading model....") detector.loadModel() print("Model loaded, ready to detect me some berries!") if os.path.isdir(image_name): #it is a directory so iterate over all the images image_dir = image_name for file_name in os.listdir(image_dir): image_base_name, ext = os.path.splitext(file_name) if ext.lower() == '.jpg' or ext.lower() == '.png' or ext.lower( ) == '.jpeg': yolov3_detect_objects_and_show_image( detector, os.path.join(image_dir, file_name), dest_dir) else: print("Skipping " + file_name) else: while len(image_name ) > 0 and image_name != 'no' and image_name != 'exit': yolov3_detect_objects_and_show_image(detector, image_name, dest_dir) print("Enter new image name (no or exit to quit): ") image_name = input() print("Done!")
class api: def __init__(self): self.detector = CustomObjectDetection() self.detector.setModelTypeAsYOLOv3() self.detector.setModelPath("detection_model-ex-046--loss-8.848.h5") self.detector.setJsonPath("detection1_config.json") self.detector.loadModel() self.username="******" self.password="******" self.data={ "kadi" : f"{self.username}", "sifre" : f"{self.password}" } self.baseurl="***" #http://blabla self.signin() def signin(self): self.s=requests.session() self.r=self.s.post(f"{self.baseurl}/api/giris",json=self.data) if self.r.status_code==200: self.getimageList() elif self.r.status_code==400: print("Kullanıcı adı veya parola geçersiz") else: print(self.r.status_code+"*???*"+self.r.content) def getimageList(self): self.jsonReq=self.s.get(f"{self.baseurl}/api/frame_listesi") with open("frame_list.txt","w") as fp: fp.write(self.jsonReq.text) print("json indi") self.sendimageData() def sendimageData(self): json_file = open('frame_list.txt') data = json.load(json_file) for do in data: a={"frame_id":do['frame_id'],"objeler":[]} img=imageio.imread(f"http://{do['frame_link']}") detections = self.detector.detectObjectsFromImage(input_type="array",input_image=img,output_type="array",thread_safe=True) for detection in detections[1]: a["objeler"].append({"tur":detection["name"],"x1":detection["box_points"][0],"y1":detection["box_points"][1],"x2":detection["box_points"][2],"y2":detection["box_points"][3]}) self.true=self.s.post(f"{self.baseurl}/api/cevap_gonder",json=a) print(f"[+] http://{do['frame_link']} "+str(self.true.status_code)) a["objeler"].clear() print("Tüm resimler okundu") self.logout() def logout(self): self.s.get(f"{self.baseurl}/api/cikis")
def load_yolo(modelfile="yolo.h5", confjson=None): yolo = Detection.ObjectDetection() if confjson is None else CustomObjectDetection() yolo.setModelTypeAsYOLOv3() yolo.setModelPath(modelfile) if confjson is not None: yolo.setJsonPath(confjson) yolo.loadModel() return yolo
def load_model(self, user, model_path=None, update_db=False): """ Load a specific model and its parameters to be used Args: user (str): registered user which the model belongs model_path (str): full path of the model file to be loaded (If None, model will be fetch according with db models table) update_db (bool): True if the loaded model, according with the argument model_path, should update the registered model in db models table Returns: object: loaded model """ if model_path: version = model_path.split('/')[-1].split('_')[0] model_id = model_path.split('_')[-1] self.model_path = model_path if update_db: self.select_model(user=user, version=version, model_id=model_id) else: self.get_model_info(user) model_path = os.path.join(config.DATA_PATH, user, 'models', f'{self.version}_{self.model_id}.h5') self.model_path = model_path model = CustomObjectDetection() model.setModelTypeAsYOLOv3() model.setModelPath(model_path) model.setJsonPath( os.path.join( config.DATA_PATH, user, model_path.replace('models', 'models/json').replace('.h5', '.json'))) model.loadModel() return model
def __init__(self): known_path = '/home/swc/spark-2.4.5-bin-hadoop2.7/CCTV-pyspark/images/' # directory path of know_faces image_format = 'jpg' known_list = os.listdir(known_path) self.known_faces = [] # Load & encode all images from known_path for f in known_list : if f.split('.')[-1] != image_format : continue known_img = face_recognition.load_image_file(known_path+f) known_img_encoding = face_recognition.face_encodings(known_img)[0] self.known_faces.append(known_img_encoding) self.execution_path = "/home/swc/spark-2.4.5-bin-hadoop2.7/CCTV-pyspark/" self.detector = CustomObjectDetection() self.detector.setModelTypeAsYOLOv3() # self.detector.setModelPath(detection_model_path=os.path.join(self.execution_path, "detection_model-ex-33--loss-4.97.h5")) # self.detector.setJsonPath(configuration_json=os.path.join(self.execution_path, "detection_config.json")) self.detector.setModelPath(detection_model_path=os.path.join("/home/swc/spark-2.4.5-bin-hadoop2.7/CCTV-pyspark/", "detection_model-ex-33--loss-4.97.h5")) self.detector.setJsonPath(configuration_json=os.path.join("/home/swc/spark-2.4.5-bin-hadoop2.7/CCTV-pyspark/", "detection_config.json")) self.detector.loadModel()
class FindShips(): PNG_PATH = "data/images_png/" TXT_PATH = "data/info_txt/" LEARN_PATH = "data/learn/" OUT_PATH = "data/out_processed_file/" def __init__(self): execution_path = os.getcwd() self.detector = CustomObjectDetection() self.detector.setModelTypeAsYOLOv3() self.detector.setModelPath("detection_model-ex-044--loss-0022.165.h5") self.detector.setJsonPath("detection_config.json") self.detector.loadModel() def searchImages(self, nameFile): ships = [] outfile = nameFile.split('.')[0] + 'processed.png' detections = self.detector.detectObjectsFromImage( input_image=self.LEARN_PATH + nameFile, output_image_path=self.OUT_PATH + outfile, minimum_percentage_probability=50) print("save: " + outfile) outfileTxt = nameFile.split('.')[0] + 'corners.txt' f = open(self.TXT_PATH + outfileTxt, "r") moveX = float(f.readline()) moveY = float(f.readline()) f.close() counter = 0 for detection in detections: x1, y1, x2, y2 = detection["box_points"] x = (x2 + x1) / 2 y = (y2 + y1) / 2 x += moveX y += moveY ships.append((x, y)) counter += 1 return ships
class items(): def __init__(self, detectorModel, setJson): self.detector = CustomObjectDetection() self.detector.setModelPath(detectorModel) self.detector.setJsonPath(setJson) self.detector.loadModel() def items_draw(self, frame): detected_image, detections = self.detector.detectObjectsFromImage(input_image=frame,input_type="array",output_type="array") for detection in detections: print(detection["name"], " : ", detection["percentage_probability"]) (x1,y1,x2,y2) = detection["box_points"] print("x1: ", x1," - y1: ", y1," - x2: ", x2," - y2: ", y2) cv2.rectangle(frame,(x1,y1),(x2,y2),(0,0,255),2) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, detection["name"],(x1 + 6, y1 - 6), font, 1.0, (255,255,255), 1)
class Process: def __init__(self): known_path = '/home/swc/spark-2.4.5-bin-hadoop2.7/CCTV-pyspark/images/' # directory path of know_faces image_format = 'jpg' known_list = os.listdir(known_path) self.known_faces = [] # Load & encode all images from known_path for f in known_list : if f.split('.')[-1] != image_format : continue known_img = face_recognition.load_image_file(known_path+f) known_img_encoding = face_recognition.face_encodings(known_img)[0] self.known_faces.append(known_img_encoding) self.execution_path = "/home/swc/spark-2.4.5-bin-hadoop2.7/CCTV-pyspark/" self.detector = CustomObjectDetection() self.detector.setModelTypeAsYOLOv3() # self.detector.setModelPath(detection_model_path=os.path.join(self.execution_path, "detection_model-ex-33--loss-4.97.h5")) # self.detector.setJsonPath(configuration_json=os.path.join(self.execution_path, "detection_config.json")) self.detector.setModelPath(detection_model_path=os.path.join("/home/swc/spark-2.4.5-bin-hadoop2.7/CCTV-pyspark/", "detection_model-ex-33--loss-4.97.h5")) self.detector.setJsonPath(configuration_json=os.path.join("/home/swc/spark-2.4.5-bin-hadoop2.7/CCTV-pyspark/", "detection_config.json")) self.detector.loadModel() def ProcessImage(self, data): encoded_image = data #base64 to image(uint8) decoding img64_decode = base64.b64decode(encoded_image) im_arr = np.frombuffer(img64_decode, dtype=np.uint8) decoded_img = cv2.imdecode(im_arr, flags=cv2.IMREAD_COLOR) face = self.FaceRecognition(decoded_img) #True면 침입자 fire = self.FireDetection(decoded_img) #True면 화재발생 result= {"unknown_person" : face, "fire_broken" : fire} print(result) return result def FaceRecognition(self, decoded_img): #encoding frame try : unknown_face_encoding = face_recognition.face_encodings(decoded_img)[0] # results is an array of True/False telling if the unknown face matched anyone in the known_faces array # 아는 얼굴이면 False, 모르는 얼굴이면 True results = face_recognition.compare_faces(self.known_faces, unknown_face_encoding) return not True in results except IndexError: # print("얼굴없음") return False def FireDetection(self, decoded_img): detections = self.detector.detectObjectsFromImage(input_image=decoded_img, input_type="array", output_image_path=os.path.join(self.execution_path, "fire_detected.jpg"), minimum_percentage_probability=40) if len(detections) == 0 : fire_broken = False else : fire_broken = True return fire_broken '''
def simple_valid(model_path, json_path): parmas = sys.argv if len(parmas) <= 1: print('请输入要检测的类型,获取边界位置(box)或者判断目标是否存在(exist)') return if parmas[1] == 'exist' and len(parmas) <= 2: print('请输入目标label') return detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath(os.path.join(execution_path, model_path)) detector.setJsonPath(os.path.join(execution_path, json_path)) detector.loadModel() detections = detector.detectObjectsFromImage( input_image=os.path.join(execution_path, parmas[2]), output_image_path=os.path.join(execution_path, parmas[3])) if parmas[1] == 'box': info = [{ 'name': eachObject["name"], 'percent': str(eachObject["percentage_probability"]), 'box': eachObject["box_points"] } for eachObject in detections] json_info = json.dumps(info) print(json_info) elif parmas[1] == 'exist': exist = False for eachObject in detections: if eachObject["name"] == parmas[2]: exist = True break print(exist)
from imageai.Detection.Custom import CustomObjectDetection detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath("bestdetection_model-ex-012--loss-0006.868.h5") detector.setJsonPath("best1.json") detector.loadModel() detections, extracted_objects_array = detector.detectObjectsFromImage( input_image="image-003.png", output_image_path="1.png", extract_detected_objects=True) for detection, object_path in zip(detections, extracted_objects_array): print(object_path) print(detection["name"], " : ", detection["percentage_probability"], " : ", detection["box_points"]) print("---------------")
from imageai.Detection.Custom import CustomObjectDetection import os import cv2 import numpy execution_path = os.getcwd() detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath(os.path.join(execution_path, "./fire.h5")) detector.setJsonPath( configuration_json=os.path.join(execution_path, "detection_config.json")) detector.loadModel() cap = cv2.VideoCapture(0) while (True): ret, frame = cap.read() detected_image_array, detections = detector.detectObjectsFromImage( output_type="array", input_type="array", input_image=frame) for eachObject in detections: print(eachObject["name"], " : ", eachObject["percentage_probability"], " : ", eachObject["box_points"]) #adjust camera/hose depending on box_points(?) cv2.imshow('detection', detected_image_array) if cv2.waitKey(1) & 0xFF == ord('q'):
from imageai.Detection.Custom import CustomObjectDetection detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath("wheels-yolov3.h5") detector.setJsonPath("wheelchair_dataset/json/detection_config.json") detector.loadModel() detections = detector.detectObjectsFromImage( input_image="wheelchair_dataset/validation/images/wheelchair_00742.jpg", output_image_path="result.jpg") for detection in detections: print(detection["name"], " : ", detection["percentage_probability"], " : ", detection["box_points"])
from imageai.Detection.Custom import CustomObjectDetection detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath("models/hololens-ex-60--loss-2.76.h5") # path to weights detector.setJsonPath("detection_config.json") detector.loadModel() detections = detector.detectObjectsFromImage( input_image="inputs/holo3.jpg", output_image_path="outputs/holo3-detected.jpg") for detection in detections: print(detection["name"], " : ", detection["percentage_probability"], " : ", detection["box_points"])
import cv2 import numpy as np # import tensorflow as tf import keras import os from imageai.Detection.Custom import CustomObjectDetection execution_path = os.getcwd() detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath( os.path.join( execution_path, "data/camembert/models/detection_model-ex-001--loss-0045.783.h5")) detector.setJsonPath( os.path.join(execution_path, "data/camembert/json/detection_config.json")) detector.loadModel() detections = detector.detectObjectsFromImage( input_image=os.path.join(execution_path, "images/téléchargement.jpeg"), output_image_path=os.path.join(execution_path, "results/camembert2_result.jpeg")) for eachObject in detections: print(eachObject["name"], " : ", eachObject["percentage_probability"]) # cap = cv2.VideoCapture(0) # if cap.isOpened():
closestPlayerTeam = 'team1' if ('ball' in coordinates): ballX = coordinates['ball'][0]['x1'] ballY = coordinates['ball'][0]['y1'] for teamNumber in coordinates: if (teamNumber == 'team1') or (teamNumber == 'team2'): for playerIndex in coordinates[teamNumber]: playerX = coordinates[teamNumber][playerIndex]['x2'] playerY = coordinates[teamNumber][playerIndex]['y2'] if ((playerX-ballX)**2+(playerY-ballY)**2 < minDistance): minDistance = (playerX-ballX)**2+(playerY-ballY)**2 closestPlayer = coordinates[teamNumber][playerIndex] closestPlayerTeam = teamNumber return closestPlayerTeam detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath("detection_model-ex-112--loss-0006.162.h5") detector.setJsonPath("detection_config.json") detector.loadModel() #Read the video frame by frame while success: success,image = vidcap.read() count += 1 print(image.shape) coordinates = {} number_team1_players = 0 number_team2_players = 0 number_ball = 0
from imageai.Detection.Custom import CustomObjectDetection from imageai.Detection.Custom import DetectionModelTrainer import imageai import os import cv2 os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true" detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath( "models/containerHealth/models/detection_model-ex-041--loss-0006.173.h5") detector.setJsonPath("models/containerHealth/json/detection_config.json") detector.loadModel() def get_area(a): x1, y1, x2, y2 = a["box_points"] area = abs(x2 - x1) * (y2 - y1) return area def get_health(image): detections = detector.detectObjectsFromImage(input_image=image, input_type="array", output_type="array") area = 0 total_area = 0 probs = [] dic = dict.fromkeys(["ratio", "confidence", "image"])
import os import cv2 from flask import Flask, request, jsonify from werkzeug.utils import secure_filename from imageai.Detection.Custom import CustomObjectDetection app = Flask(__name__) detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath('model.h5') detector.setJsonPath('detection_config.json') detector.loadModel() @app.route('/health', methods=['GET']) def health(): return 'OK' @app.route('/', methods=['POST']) def analyze_file(): f = request.files['file'] filename = 'uploads/' + secure_filename(f.filename) output_filename = 'outputs/' + secure_filename(f.filename) f.save(filename) img = cv2.imread(filename) height, width, _ = img.shape detections = detector.detectObjectsFromImage( input_image=filename, output_image_path=output_filename) os.remove(filename)
def path(image): img = image detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath("detection_model.h5") detector.setJsonPath("detection_config.json") detector.loadModel() detector.detectObjectsFromImage(input_image=img, output_image_path="mask-detected.jpg", display_percentage_probability=False)
valid_files = [ os.path.join(dirpath, filename) for filename in os.listdir(dirpath) ] # filter out directories, no-extension, and wrong extension files valid_files = [f for f in valid_files if '.' in f and \ f.rsplit('.',1)[-1] in valid_extensions and os.path.isfile(f)] if not valid_files: raise ValueError("No valid images in %s" % dirpath) return max(valid_files, key=os.path.getmtime) execution_path = os.path.dirname(os.path.abspath(__file__)) detector = CustomObjectDetection() detector.setModelTypeAsYOLOv3() detector.setModelPath(detection_model_path=execution_path + "/yolov3/models/detection_model-ex-009--loss-8.843.h5") detector.setJsonPath(configuration_json=execution_path + "/yolov3/json/detection_config.json") detector.loadModel() latest_image = get_latest_image(os.getenv("IMAGE_PATH")) save_predictions_path = os.getenv("OUTPUT_PATH") output_image_path = save_predictions_path + "/" + os.path.basename( latest_image) detections = detector.detectObjectsFromImage( latest_image, minimum_percentage_probability=60,