Esempio n. 1
0
def main():
    if (len(sys.argv) != 2):
        print("The App arg is invalid")
        exit(1)

    acl_resource = AclLiteResource()
    acl_resource.init()
    model = AclLiteModel(MODEL_PATH)
    dvpp = AclLiteImageProc(acl_resource)

    image_dir = sys.argv[1]
    images_list = [
        os.path.join(image_dir, img) for img in os.listdir(image_dir)
        if os.path.splitext(img)[1] in const.IMG_EXT
    ]

    #Create a directory to store the inference results
    if not os.path.isdir(os.path.join(SRC_PATH, "../out")):
        os.mkdir(os.path.join(SRC_PATH, "../out"))

    image_info = construct_image_info()
    for image_file in images_list:
        image = AclLiteImage(image_file)
        resized_image = pre_process(image, dvpp)
        print("pre process end")

        result = model.execute([
            resized_image,
        ])
        post_process(result, image_file)

        print("process " + image_file + " end")
Esempio n. 2
0
def main():
    """
    Program execution with picture directory parameters
    """
    if (len(sys.argv) != 2):
        print("The App arg is invalid, eg: python3.6 classify.py ../data/")
        exit(1)
    acl_resource = AclLiteResource()
    acl_resource.init()
    #Instantiation classification detection, incoming om model path, model input width and height parameters
    classify = Classify(MODEL_PATH, MODEL_WIDTH, MODEL_HEIGHT)

    #Get the picture storage directory from the parameters, and infer picture by picture
    image_dir = sys.argv[1]
    images_list = [
        os.path.join(image_dir, img) for img in os.listdir(image_dir)
        if os.path.splitext(img)[1] in IMG_EXT
    ]

    #Create a directory and save the infer results
    if not os.path.isdir(os.path.join(SRC_PATH, "../out")):
        os.mkdir(os.path.join(SRC_PATH, "../out"))

    for image_file in images_list:
        #preprocess image
        resized_image = classify.pre_process(image_file)
        print("pre process end")
        #inference
        result = classify.inference(resized_image)
        #post process
        classify.post_process(result, image_file)
Esempio n. 3
0
def main():
    """
    acl resource initialization
    """
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)
    #ACL resource initialization
    acl_resource = AclLiteResource()
    acl_resource.init()

    model = AclLiteModel(model_path)
    images_list = [
        os.path.join(INPUT_DIR, img) for img in os.listdir(INPUT_DIR)
        if os.path.splitext(img)[1] in IMG_EXT
    ]

    for pic in images_list:
        print("pic: ", pic)

        bgr_img = cv.imread(pic).astype(np.float32)
        data = preprocess(bgr_img)

        result_list = model.execute([data])

        postprocess(result_list, pic, bgr_img)

    print("Execute end")
Esempio n. 4
0
def main():
    """
    acl resource initialization
    """
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)
    #ACL resource initialization
    acl_resource = AclLiteResource()
    acl_resource.init()

    model = AclLiteModel(model_path)
    images_list = [
        os.path.join(INPUT_DIR, img) for img in os.listdir(INPUT_DIR)
        if os.path.splitext(img)[1] in IMG_EXT
    ]

    for pic in images_list:

        orig_shape, orig_l, l_data = preprocess(pic)
        result_list = model.execute([
            l_data,
        ])
        postprocess(result_list, pic, orig_shape, orig_l)
        break
    print("Execute end")
Esempio n. 5
0
def main():
    """
    main
    """
    if (len(sys.argv) != 2):
        print("The App arg is invalid")
        exit(1)

    acl_resource = AclLiteResource()
    acl_resource.init()

    crowdcount = CrowdCount(MODEL_PATH, MODEL_WIDTH, MODEL_HEIGHT)
    ret = crowdcount.init()

    if not os.path.isdir(os.path.join(SRC_PATH, "../out")):
        os.mkdir(os.path.join(SRC_PATH, "../out"))

    image_dir = sys.argv[1]
    images_list = [
        os.path.join(image_dir, img) for img in os.listdir(image_dir)
        if os.path.splitext(img)[1] in constants.IMG_EXT
    ]

    for image_file in images_list:
        image = AclLiteImage(image_file)
        crop_and_paste_image = crowdcount.pre_process(image)
        print("pre process end")
        result = crowdcount.inference([crop_and_paste_image])
        result_img_encode = crowdcount.post_process(crop_and_paste_image,
                                                    result, image_file)
    return result_img_encode
Esempio n. 6
0
def main():
    """
    Program execution
    """
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)

    acl_resource = AclLiteResource()  # acl intialize
    acl_resource.init()

    model = AclLiteModel(model_path)  # load model

    src_dir = os.listdir(INPUT_DIR)
    for pic in src_dir:
        if not pic.lower().endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg',
                                     '.pbm', '.pgm', '.ppm', '.tif', '.tiff')):
            print('it is not a picture, %s, ignore this file and continue,' %
                  pic)
            continue
        pic_path = os.path.join(INPUT_DIR, pic)
        RGB_image, o_h, o_w = pre_process(pic_path)  # preprocess

        start_time = time.time()
        result_list = model.execute([
            RGB_image,
        ])  # inferring
        end_time = time.time()
        print('pic:{}'.format(pic))
        print('pic_size:{}x{}'.format(o_h, o_w))
        print('time:{}ms'.format(int((end_time - start_time) * 1000)))
        print('\n')
        post_process(result_list, pic, o_h, o_w)  # postprocess
    print('task over')
Esempio n. 7
0
def main():
    """main"""
    #acl init
    if (len(sys.argv) != 2):
        print("The App arg is invalid")
        exit(1)
    acl_resource = AclLiteResource()
    acl_resource.init()
    model = AclLiteModel(MODEL_PATH)
    dvpp = AclLiteImageProc(acl_resource)

    #From the parameters of the picture storage directory, reasoning by a picture
    image_dir = sys.argv[1]
    images_list = [os.path.join(image_dir, img)
                   for img in os.listdir(image_dir)
                   if os.path.splitext(img)[1] in const.IMG_EXT]

    if not os.path.isdir(os.path.join(SRC_PATH, "../out")):
        os.mkdir(os.path.join(SRC_PATH, "../out"))

    #infer picture
    for pic in images_list:
        #get pic data
        orig_shape, l_data = preprocess(pic)
        #inference
        result_list = model.execute([l_data])    
        #postprocess
        postprocess(result_list, pic, orig_shape, pic)
    print("Execute end")
Esempio n. 8
0
def main(model_path, frames_input_src, output_dir):
    """main"""
    #initialize acl runtime 
    acl_resource = AclLiteResource()
    acl_resource.init()
    
    ## Prepare Model ##
    # parameters for model path and model inputs
    model_parameters = {
        'model_dir': model_path,
        'width': 368, # model input width      
        'height': 368, # model input height
    }
    # perpare model instance: init (loading model from file to memory)
    # model_processor: preprocessing + model inference + postprocessing
    model_processor = ModelProcessor(acl_resource, model_parameters)

    ## Get Input ##
    # Read the image input using OpenCV
    img_original = cv2.imread(frames_input_src)

    ## Model Prediction ##
    # model_processor.predict: processing + model inference + postprocessing
    # canvas: the picture overlayed with human body joints and limbs
    canvas = model_processor.predict(img_original)

    # Save the detected results
    cv2.imwrite(os.path.join(output_dir, "test_output.jpg"), canvas)
Esempio n. 9
0
def preandinfer(image_queue, images_list):
    acl_start = time.time()
    #print('Start preandinfer ')
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)
    acl_resource = AclLiteResource()
    acl_resource.init()
    dvpp_ = AclLiteImageProc()
    model = AclLiteModel(model_path)
    print('------------------------------acl processing time',
          time.time() - acl_start)
    for pic in images_list:
        image = AclLiteImage(pic)
        image_dvpp = image.copy_to_dvpp()
        yuv_image = dvpp_.jpegd(image_dvpp)
        resized_image = dvpp_.resize(yuv_image, MODEL_WIDTH, MODEL_HEIGHT)
        result_list = model.execute([
            resized_image,
        ])
        data = ProcData(result_list, pic, OUTPUT_DIR)
        image_queue.put(data)
    post_num = 6
    while (post_num):
        post_num -= 1
        data = "Post process thread exit"
        image_queue.put(data)
    print('End preandinfer')
    print('------------------------------preandinfer time',
          time.time() - acl_start)
Esempio n. 10
0
def main():
    """
    acl resource initialization
    """
    
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)
     #ACL resource initialization
    acl_resource = AclLiteResource()
    acl_resource.init()
    dvpp_ = AclLiteImageProc()
    model = AclLiteModel(model_path)
    images_list = [os.path.join(INPUT_DIR, img)
                   for img in os.listdir(INPUT_DIR)
                   if os.path.splitext(img)[1] in IMG_EXT]
    
    print(images_list)
    
    start = time.time()
    for pic in images_list:
        image = AclLiteImage(pic)       

        l_data = preprocess(image, dvpp_)
        result_list = inference(model, [l_data,])
        postprocess(result_list, pic, OUTPUT_DIR)
Esempio n. 11
0
def main():
    """
    main
    """
    if (len(sys.argv) != 2):
        print("The App arg is invalid")
        exit(1)

    acl_resource = AclLiteResource()
    acl_resource.init()
    model = AclLiteModel(MODEL_PATH)

    data_dir = sys.argv[1]
    data_list = [
        os.path.join(data_dir, testdata) for testdata in os.listdir(data_dir)
        if os.path.splitext(testdata)[1] in ['.bin']
    ]

    #Create a directory to store the inference results
    if not os.path.isdir(os.path.join(SRC_PATH, "../out")):
        os.mkdir(os.path.join(SRC_PATH, "../out"))

    for data_file in data_list:
        data_raw = np.fromfile(data_file, dtype=np.float32)
        input_data = data_raw.reshape(16, MODEL_WIDTH, MODEL_HEIGHT, 3).copy()
        result = model.execute([
            input_data,
        ])
        post_process(result, data_file)

    print("process  end")
Esempio n. 12
0
def main():
    """
    Program execution with picture directory parameters
    """
    if (len(sys.argv) != 2):
        print("The App arg is invalid")
        exit(1)

    acl_resource = AclLiteResource()
    acl_resource.init()
    model = AclLiteModel(MODEL_PATH)
    dvpp = AclLiteImageProc(acl_resource)

    #From the parameters of the picture storage directory, reasoning by a picture
    image_dir = sys.argv[1]
    images_list = [
        os.path.join(image_dir, img) for img in os.listdir(image_dir)
        if os.path.splitext(img)[1] in const.IMG_EXT
    ]
    #Create a directory to store the inference results
    if not os.path.isdir('../out'):
        os.mkdir('../out')

    image_info = construct_image_info()

    for image_file in images_list:
        #read picture
        image = AclLiteImage(image_file)
        #preprocess image
        resized_image = pre_process(image, dvpp)
        print("pre process end")
        #reason pictures
        result = model.execute([resized_image, image_info])
        #process resresults
        post_process(result, image, image_file)
Esempio n. 13
0
def main():
    """
    Function description:
        Main function
    """
    acl_resource = AclLiteResource()
    acl_resource.init()

    detector = Yolov3(acl_resource, MODEL_PATH, MODEL_WIDTH, MODEL_HEIGHT)

    video_decoders, postprocessor = create_threads(detector)
    if video_decoders is None:
        log_error("Please check the configuration in %s is valid" %
                  (COCO_DETEC_CONF))
        return

    while True:
        all_process_fin = True
        for decoder in video_decoders:
            ret, data = decoder.get_data()
            if ret == False:
                continue
            if data:
                detect_results = detector.execute(data)
                postprocessor.process(data, detect_results)

            all_process_fin = False
        if all_process_fin:
            log_info("all video decoder finish")
            break

    postprocessor.exit()

    log_info("sample execute end")
Esempio n. 14
0
def main():
    acl_resource = AclLiteResource()
    acl_resource.init()
    server = TcpServer()
    perception = ChessStatusPerception(MODEL_PATH)
    perception.Init()
    while True:
        print("Waiting for client connection...")
        conn, addr = server.s.accept()
        while True:
            print("Waiting for receive message...")
            length = server.recvall(conn, 16)  # get the length of img file
            if length is None:
                conn.close()
                break
            stringData = server.recvall(
                conn, int(length))  # according to the length, get the img file
            data = np.frombuffer(stringData, np.uint8)
            decimg = cv2.imdecode(data,
                                  cv2.IMREAD_COLOR)  # decode data to image
            print("Received Image Shape: ", decimg.shape)

            chessStatus, chessStatus_real = perception.Process(decimg)
            # ideal chess coordinate
            chessStatusStr = '#'.join([str(item) for item in chessStatus])
            # real chess coordinate
            chessStatus_realStr = '#'.join(
                [str(item) for item in chessStatus_real])
            sendmsg = chessStatusStr + "&" + chessStatus_realStr

            print("Send Message: ", sendmsg)
            conn.sendall(sendmsg.encode())
Esempio n. 15
0
def main():
    # check param
    if (len(sys.argv) != 3):
        print("The App arg is invalid")
        exit(1)
    # get all pictures
    image_dir = sys.argv[1]

    images_list = [
        os.path.join(image_dir, img) for img in os.listdir(image_dir)
        if os.path.splitext(img)[1] in const.IMG_EXT
    ]

    acl_resource = AclLiteResource()
    acl_resource.init()

    # instantiation Cartoonization object
    cartoonization = Cartoonization(MODEL_PATH, MODEL_WIDTH, MODEL_HEIGHT)
    ret = cartoonization.init()
    utils.check_ret("Cartoonization.init ", ret)

    # create dir to save result
    if not os.path.isdir('../out'):
        os.mkdir('../out')

    for image_file in images_list:
        # preprocess
        image = AclLiteImage(image_file)
        test_img = cartoonization.pre_process(image)
        # inference
        y_pred = cartoonization.inference([
            test_img,
        ])
        # postprocess
        cartoonization.post_process(y_pred, image_file)
Esempio n. 16
0
def main(image_dirs, masks_dirs):    
    
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)

    #acl  init
    acl_resource = AclLiteResource()
    acl_resource.init()
    stream, ret = acl.rt.create_stream()
    check_ret("acl.rt.create_stream", ret)
    #load model
    model = AclLiteModel(MODEL_PATH)
    
    paths_img, paths_mask = get_imgs_masks_file_list(image_dirs, masks_dirs)
    for i in range(len(paths_img)):
        print('==========')        
        raw_img, raw_mask = readimages(paths_img[i], paths_mask[i])
        print("file: % s, shape= % s" % (paths_img[i], raw_img.shape))

        (img_large, mask_large, img_512, mask_512) = pre_process(raw_img, raw_mask)        
        inpainted_512, attention, mask_512_new  = inference(model,[img_512, mask_512,])                

        # post-processing
        res_raw_size = post_process(raw_img, img_large, \
            mask_large, inpainted_512[0], img_512, mask_512_new[0], attention[0], stream)
        filename = os.path.join(OUTPUT_DIR, 'outpaint_' + os.path.basename(paths_img[i]))
        cv2.imwrite(filename, res_raw_size)
        
    print("Execute end")
Esempio n. 17
0
def test(args):
    # Step 1: initialize ACL and ACL runtime
    acl_resource = AclLiteResource()

    # 1.2: one line of code, call the 'init' function of the AclLiteResource object, to initilize ACL and ACL runtime
    acl_resource.init()

    # Step 2: Load models
    mot_model = AclLiteModel('../model/mot_v2.om')

    dataloader = loader.LoadImages(args.test_img)

    # initialize tracker
    tracker = JDETracker(args, mot_model, frame_rate=30)
    timer = Timer()
    results = []

    # img:  h w c; 608 1088 3
    # img0: c h w; 3 608 1088
    for frame_id, (path, img, img0) in enumerate(dataloader):
        if frame_id % 20 == 0 and frame_id != 0:
            print('Processing frame {} ({:.2f} fps)'.format(
                frame_id, 1. / max(1e-5, timer.average_time)))

        # run tracking, start tracking timer
        timer.tic()

        # list of Tracklet; see multitracker.STrack
        online_targets = tracker.update(np.array([img]), img0)

        # prepare for drawing, get all bbox and id
        online_tlwhs = []
        online_ids = []
        for t in online_targets:
            tlwh = t.tlwh
            tid = t.track_id
            vertical = tlwh[2] / tlwh[3] > 1.6
            if tlwh[2] * tlwh[3] > args.min_box_area and not vertical:
                online_tlwhs.append(tlwh)
                online_ids.append(tid)
        timer.toc()

        # draw bbox and id
        online_im = vis.plot_tracking(img0,
                                      online_tlwhs,
                                      online_ids,
                                      frame_id=frame_id,
                                      fps=1. / timer.average_time)
        cv2.imwrite(os.path.join('../data', 'test_output.jpg'), online_im)

    # verify if result is expected
    result = image_contrast('../data/test_output.jpg', args.verify_img)
    print(result)
    if (result > 420 or result < 0):
        print("Similarity Test Fail!")
        sys.exit(1)
    else:
        print("Similarity Test Pass!")
        sys.exit(0)
Esempio n. 18
0
def main(model_path):
    """main"""
    ## Initialization ##
    #initialize acl runtime
    acl_resource = AclLiteResource()
    acl_resource.init()

    ## Prepare Model ##
    # parameters for model path and model inputs
    model_parameters = {
        'model_dir': model_path,
        'width': 368,  # model input width      
        'height': 368,  # model input height
    }
    # perpare model instance: init (loading model from file to memory)
    # model_processor: preprocessing + model inference + postprocessing
    model_processor = ModelProcessor(acl_resource, model_parameters)

    ## Get Input ##
    # Initialize Camera
    cap = CameraCapture(camera_id=0, fps=10)

    ## Set Output ##
    # open the presenter channel

    chan = presenter_channel.open_channel(BODYPOSE_CONF)
    if chan is None:
        print("Open presenter channel failed")
        return

    while True:
        ## Read one frame from Camera ##
        img_original = cap.read()
        if not img_original:
            print('Error: Camera read failed')
            break
        # Camera Input (YUV) to RGB Image
        img_original = img_original.byte_data_to_np_array()
        img_original = YUVtoRGB(img_original)
        # img_original = cv2.flip(img_original, 1)

        ## Model Prediction ##
        # model_processor.predict: processing + model inference + postprocessing
        # canvas: the picture overlayed with human body joints and limbs
        canvas = model_processor.predict(img_original)

        ## Present Result ##
        # convert to jpeg image for presenter server display
        _, jpeg_image = cv2.imencode('.jpg', canvas)
        # construct AclLiteImage object for presenter server
        jpeg_image = AclLiteImage(jpeg_image, img_original.shape[0],
                                  img_original.shape[1], jpeg_image.size)
        # send to presenter server
        chan.send_detection_data(img_original.shape[0], img_original.shape[1],
                                 jpeg_image, [])

    # release the resources
    cap.release()
Esempio n. 19
0
def main():
    """
    Program execution with picture directory parameters
    """
    if (len(sys.argv) != 2):
        print("The App arg is invalid")
        exit(1)

    acl_resource = AclLiteResource()
    acl_resource.init()
    #Instance classification detection, pass into the OM model storage path, model input width and height parameters
    classify = Classify(acl_resource, MODEL_PATH, MODEL_WIDTH, MODEL_HEIGHT)
    
    #From the parameters of the picture storage directory, reasoning by a picture
    image_dir = sys.argv[1]
    images_list = [os.path.join(image_dir, img)
                   for img in os.listdir(image_dir)
                   if os.path.splitext(img)[1] in IMG_EXT]
    
    #Create a directory to store the inference results
    if not os.path.isdir('../out'):
        os.mkdir('../out')

    resized_image_list = []
    batch_image_files = []
    num = 0
    batch_amount = len(images_list) // BATCH
    left =  len(images_list) % BATCH

    for image_file in images_list:
        num += 1
        #Read the pictures
        image = AclLiteImage(image_file)
        image_dvpp = image.copy_to_dvpp()
        #preprocess image
        resized_image = classify.pre_process(image_dvpp)
        print("pre process end")

        batch_image_files.append(image_file) 
        resized_image_list.append(resized_image)
        if batch_amount > 0:
            #Each set of BATCH pictures, reasoning and post-processing
            if num == BATCH:
                #Reasoning pictures
                result = classify.inference(resized_image_list, BATCH)
                #process inference results
                classify.post_process(result, batch_image_files, BATCH)
                batch_amount -= 1
                num = 0
                batch_image_files = []
                resized_image_list = []
        else:
            #remaining images are inferred and post-processed
            if num == left:
                #Reasoning pictures
                result = classify.inference(resized_image_list, BATCH)
                #The inference results are processed
                classify.post_process(result, batch_image_files, left)
Esempio n. 20
0
def main():
    """
    acl resource initialization
    """
    acl_resource = AclLiteResource()
    acl_resource.init()
    #load model
    model = AclLiteModel(model_path)
    chan = presenter_channel.open_channel(COLORIZATION_CONF)
    if chan is None:
        print("Open presenter channel failed")
        return

    lenofUrl = len(sys.argv)

    if lenofUrl <= 1:
        print("[ERROR] Please input mp4/Rtsp URL")
        exit()
    elif lenofUrl >= 3:
        print("[ERROR] param input Error")
        exit()
    URL = sys.argv[1]
    URL1 = re.match('rtsp://', URL)
    URL2 = re.search('.mp4', URL)

    if URL1 is None and URL2 is None:
        print("[ERROR] should input correct URL")
        exit()

    cap = cv.VideoCapture(URL)
    #Gets the total frames
    frames_num = cap.get(7)
    currentFrames = 0

    while True:
        #read image
        ret, frame = cap.read()
        if ret is not True:
            print("read None image, break")
            break

        if currentFrames == frames_num - 1:
            currentFrames = 0
            cap.set(1, 0)

        currentFrames += 1
        #Gets the L channel value
        orig_shape, orig_l, l_data = preprocess(frame)
        result_list = model.execute([
            l_data,
        ])
        result_jpeg = postprocess(result_list, orig_shape, orig_l)
        chan.send_image(orig_shape[0], orig_shape[1], result_jpeg)
Esempio n. 21
0
def main():
    acl_resource = AclLiteResource()
    acl_resource.init()

    detect = VggSsd(acl_resource, MODEL_WIDTH, MODEL_HEIGHT)
    model = AclLiteModel(MODEL_PATH)
    chan = presenter_channel.open_channel(MASK_DETEC_CONF)
    if chan is None:
        print("Open presenter channel failed")
        return

    lenofUrl = len(sys.argv)
    if lenofUrl <= 1:
        print("[ERROR] Please input h264/Rtsp URL")
        exit()
    elif lenofUrl >= 3:
        print("[ERROR] param input Error")
        exit()
    URL = sys.argv[1]
    URL1 = re.match('rtsp://', URL)
    URL2 = re.search('.h264', URL)

    if URL1 is None and URL2 is None:
        print("[ERROR] should input correct URL")
        exit()
    cap = video.VideoCapture(URL)

    while True:
        # Read a frame
        ret, image = cap.read()
        if (ret != 0) or (image is None):
            print("read None image, break")
            break
        #pre process
        model_input = detect.pre_process(image)
        if model_input is None:
            print("Pre process image failed")
            break
        # inference
        result = model.execute(model_input)
        if result is None:
            print("execute mode failed")
            break
        # post process
        jpeg_image, detection_list = detect.post_process(result, image)
        if jpeg_image is None:
            print("The jpeg image for present is None")
            break
        chan.send_detection_data(CAMERA_FRAME_WIDTH, CAMERA_FRAME_HEIGHT,
                                 jpeg_image, detection_list)
Esempio n. 22
0
def test_200dk():
    """
    Test the output of ChessStatusPerception module.
    """
    acl_resource = AclLiteResource()
    acl_resource.init()
    perception = ChessStatusPerception(MODEL_PATH)
    perception.Init()

    # load input
    print("input_dir = ", INPUT_DIR)
    img = os.path.join(INPUT_DIR, "test.jpg")
    image = cv2.imread(img)
    # execute the chessboard status perception function
    chessStatus, chessStatus_real = perception.Process(image)

    return chessStatus
Esempio n. 23
0
def main():
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)
    #ACL resource initialization
    acl_resource = AclLiteResource()
    acl_resource.init()
    #load model
    model = AclLiteModel(MODEL_PATH)
    images_list = [os.path.join(INPUT_DIR, img)
                   for img in os.listdir(INPUT_DIR)
                   if os.path.splitext(img)[1] in const.IMG_EXT]
    #Read images from the data directory one by one for reasoning
    for pic in images_list:
        #read image
        bgr_img = cv.imread(pic)
        #preprocess
        data, orig = preprocess(pic)
        #Send into model inference
        result_list = model.execute([data,])
        #Process inference results
        result_return = post_process(result_list, orig)
        print("result = ", result_return)
        #Process lane line
        frame_with_lane = preprocess_frame(bgr_img)
        distance = np.zeros(shape=(len(result_return['detection_classes']), 1))

        for i in range(len(result_return['detection_classes'])):
            box = result_return['detection_boxes'][i]
            class_name = result_return['detection_classes'][i]
            confidence = result_return['detection_scores'][i]
            distance[i] = calculate_position(bbox=box, transform_matrix=perspective_transform,
                        warped_size=WARPED_SIZE, pix_per_meter=pixels_per_meter)
            label_dis = '{} {:.2f}m'.format('dis:', distance[i][0])
            cv.putText(frame_with_lane, label_dis, (int(box[1]) + 10, int(box[2]) + 15), 
                        cv.FONT_ITALIC, 0.6, colors[i % 6], 1)

            cv.rectangle(frame_with_lane, (int(box[1]), int(box[0])), (int(box[3]), int(box[2])), colors[i % 6])
            p3 = (max(int(box[1]), 15), max(int(box[0]), 15))
            out_label = class_name
            cv.putText(frame_with_lane, out_label, p3, cv.FONT_ITALIC, 0.6, colors[i % 6], 1)

        output_file = os.path.join(OUTPUT_DIR, "out_" + os.path.basename(pic))
        print("output:%s" % output_file)
        cv.imwrite(output_file, frame_with_lane)
    print("Execute end")
Esempio n. 24
0
def main():
    """
    main
    """
    image_dir = os.path.join(currentPath, "data")

    images_list = [
        os.path.join(image_dir, img) for img in os.listdir(image_dir)
        if os.path.splitext(img)[1] in constants.IMG_EXT
    ]

    acl_resource = AclLiteResource()
    acl_resource.init()

    hpa = Hpa(MODEL_PATH, MODEL_WIDTH, MODEL_HEIGHT)
    ret = hpa.init()
    utils.check_ret("hpa init ", ret)

    # Create a directory to save inference results
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)

    for image_file in images_list:
        image_name = os.path.join(image_dir, os.path.basename(image_file))
        print('====' + image_name + '====')

        # read image
        im = Image.open(image_name)
        if len(im.split()) != 3:
            print('warning: "{}" is not a color image and will be ignored'.
                  format(image_name))
            continue

        # Preprocess the picture
        resized_image = hpa.pre_process(im)

        # Inferencecd
        result = hpa.inference([
            resized_image,
        ])

        # # Post-processing
        hpa.post_process(result, image_name)
Esempio n. 25
0
def main():
    """
    main
    """
    image_dir = os.path.join(currentPath, "data")

    if not os.path.exists(OUT_DIR):
        os.mkdir(OUT_DIR)
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)
    if not os.path.exists(MASK_DIR):
        os.mkdir(MASK_DIR)

    acl_resource = AclLiteResource()
    acl_resource.init()

    seg = Seg(MODEL_PATH, MODEL_WIDTH, MODEL_HEIGHT)
    ret = seg.init()
    utils.check_ret("seg.init ", ret)

    images_list = [
        os.path.join(image_dir, img) for img in os.listdir(image_dir)
        if os.path.splitext(img)[1] in const.IMG_EXT
    ]

    for image_file in images_list:
        image_name = os.path.basename(image_file)
        if image_name != 'background.jpg':
            print('====' + image_name + '====')
            # read image
            image = AclLiteImage(image_file)
            # Preprocess the picture
            resized_image = seg.pre_process(image)
            # Inference
            result = seg.inference([
                resized_image,
            ])
            # Post-processing
            mask = seg.post_process(result, image_name)
            # Fusion of segmented portrait and background image
            background_replace(os.path.join(image_dir, 'background.jpg'), \
                                        image_file, os.path.join(MASK_DIR, image_name))
Esempio n. 26
0
def main():
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)
    #ACL resource initialization
    acl_resource = AclLiteResource()
    acl_resource.init()
    #load model
    model = AclLiteModel(MODEL_PATH)
    images_list = [
        os.path.join(INPUT_DIR, img) for img in os.listdir(INPUT_DIR)
        if os.path.splitext(img)[1] in const.IMG_EXT
    ]
    #Read images from the data directory one by one for reasoning
    for pic in images_list:
        #read image
        bgr_img = cv.imread(pic)
        #preprocess
        data, orig = preprocess(pic)
        #Send into model inference
        result_list = model.execute([
            data,
        ])
        #Process inference results
        result_return = post_process(result_list, orig)
        print("result = ", result_return)

        for i in range(len(result_return['detection_classes'])):
            box = result_return['detection_boxes'][i]
            class_name = result_return['detection_classes'][i]
            confidence = result_return['detection_scores'][i]
            cv.rectangle(bgr_img, (int(box[1]), int(box[0])),
                         (int(box[3]), int(box[2])), colors[i % 6])
            p3 = (max(int(box[1]), 15), max(int(box[0]), 15))
            out_label = class_name
            cv.putText(bgr_img, out_label, p3, cv.FONT_ITALIC, 0.6,
                       colors[i % 6], 1)

        output_file = os.path.join(OUTPUT_DIR, "out_" + os.path.basename(pic))
        print("output:%s" % output_file)
        cv.imwrite(output_file, bgr_img)

    print("Execute end")
Esempio n. 27
0
def main():
    """
    acl resource initialization
    """
    acl_resource = AclLiteResource()
    acl_resource.init()
    
    model = AclLiteModel(model_path)

    with codecs.open(dict_path, 'r', 'utf-8') as reader:
        for line in reader:
            token = line.strip()
            token_dict[token] = len(token_dict) 

    with open(sample_path, "r") as f:
        text = f.read() 

    with open(label_path, "r", encoding="utf-8") as f:
        label_dict = json.loads(f.read())
               
    X1, X2 = preprocess(text)
    X1 = np.ascontiguousarray(X1, dtype='float32')
    X2 = np.ascontiguousarray(X2, dtype='float32')

    X1 = np.expand_dims(X1, 0)
    X2 = np.expand_dims(X2, 0)
    s_time = time.time()
    
    result_list = model.execute([X1, X2])
    e_time = time.time()    
    print(result_list)   
    y = postprocess(result_list)

    if not os.path.exists(output_dir):
        os.mkdir(output_dir)
    save_to_file(output_dir + 'prediction_label.txt', label_dict[str(y)])
    print("Original text: %s" % text)
    print("Prediction label: %s" % label_dict[str(y)])
    print("Cost time:", e_time - s_time)
    print("Execute end")
Esempio n. 28
0
def main():
    """
    Program execution with picture directory parameters
    """
    if (len(sys.argv) != 3):
        print("The App arg is invalid. The style you can choose: \
                xingkong/tangguo/bijiasuo/worksoldiers.eg: python3 main.py ../data xingkong"
              )
        exit(1)

    style_type = sys.argv[2]
    if style_type == "tangguo":
        model_path = '../model/tangguo_fp32_nchw_no_aipp.om'
    elif style_type == "bijiasuo":
        model_path = '../model/bijiasuo_fp32_nchw_no_aipp.om'
    elif style_type == "worksoldiers":
        model_path = '../model/work_soldiers_fp32_nchw_no_aipp.om'
    elif style_type == "xingkong":
        model_path = '../model/xingkong1_fp32_nchw_no_aipp.om'

    acl_resource = AclLiteResource()
    acl_resource.init()
    model = AclLiteModel(model_path)

    image_dir = sys.argv[1]
    images_list = [
        os.path.join(image_dir, img) for img in os.listdir(image_dir)
        if os.path.splitext(img)[1] in const.IMG_EXT
    ]
    if not os.path.isdir('../out'):
        os.mkdir('../out')

    for image_file in images_list:
        orig_shape, rgb_data = pre_process(image_file)
        print("pre process end")
        result_list = model.execute([rgb_data])
        print("Execute end")
        post_process(result_list, orig_shape, image_file)
        print("postprocess end")
Esempio n. 29
0
def main():
    """main"""
    #acl init
    if (len(sys.argv) != 3):
        print("The App arg is invalid")
        exit(1)
    acl_resource = AclLiteResource()
    acl_resource.init()
    model = AclLiteModel(MODEL_PATH)
    #x=296
    #y=330
    #x=410
    #y=664
    coordinate = [-1, -1]

    #From the parameters of the picture storage directory, reasoning by a picture
    coordinate = [int(sys.argv[1]), int(sys.argv[2])]

    if not os.path.exists(DATA_PATH):
        os.mkdir(DATA_PATH)

    if not os.path.exists(MASK_PATH):
        os.mkdir(MASK_PATH)

    if not os.path.exists(OUTPUT_PATH):
        os.mkdir(OUTPUT_PATH)

    images_list = [os.path.join(DATA_PATH, img)
                   for img in os.listdir(DATA_PATH)
                   if os.path.splitext(img)[1] in const.IMG_EXT]
    #infer picture
    for pic in images_list:
        #get pic data
        orig_shape, l_data, im_info = preprocess(pic)
        #inference
        result_list = model.execute([l_data, im_info])
        #postprocess
        postprocess(result_list, pic, coordinate, OUTPUT_PATH)
    print("Execute end")
Esempio n. 30
0
def main():
    """
    main
    """
    #create output directory
    if not os.path.exists(OUTPUT_DIR):
        os.mkdir(OUTPUT_DIR)

    #acl init
    acl_resource = AclLiteResource()
    acl_resource.init()

    #load model
    model = AclLiteModel(MODEL_PATH)
    src_dir = os.listdir(INPUT_DIR)
    #infer picture
    for pic in src_dir:
        if not pic.lower().endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg',
                                     '.pbm', '.pgm', '.ppm', '.tif', '.tiff')):
            print('it is not a picture, %s, ignore this file and continue,' %
                  pic)
            continue

        #read picture
        pic_path = os.path.join(INPUT_DIR, pic)
        bgr_img = cv2.imread(pic_path)

        #get pic data
        orig_shape, test_img = preprocess(bgr_img)

        #inference
        result_list = model.execute([
            test_img,
        ])

        #postprocess
        postprocess(result_list, pic)