def main(arg): """ main """ # 初始化资源相关语句 acl_resource = AclResource() acl_resource.init() # 初始化推理的类 classify = Classify(MODEL_PATH) ret = classify.init() utils.check_ret("Classify init ", ret) # 得到测试样本及其类标签 print(f"================正在加载测试集数据================") all_test_data, test_label = load_data(DATA_PATH) print(f"================测试集数据加载完毕================") # print(list(test_label).count(0)) # 类标签为0的测试集样本数量 # 调制分类推理,依次预测每一个信号的调制类型 print(f"=====================开始推理=====================") for now_num in range(arg.start_num, arg.end_num): initial_result = classify.inference(all_test_data[now_num, :, :, :]) result = initial_result[0] # 每一类的可能性大小(定性) # print(result) result = result.flatten() # x.argsort(),将x中的元素从小到大排列,返回其对应的索引 pre_index = result.argsort()[-1] # 可能性最大的类别的索引 final_result = modulation_type[pre_index] # 预测标签,即预测的测试样本的调制类型 true_label = modulation_type[test_label[now_num]] print( f"================编号为{now_num}的信号的预测的调制类型为:{final_result},实际的调制类型为:{true_label}================" ) with open("./result_modulation_type.csv", 'a', newline='') as t2: writer_train2 = csv.writer(t2) writer_train2.writerow([now_num, final_result, true_label])
def main(): if (len(sys.argv) != 2): print("The App arg is invalid") exit(1) acl_resource = AclResource() acl_resource.init() model = Model(MODEL_PATH) dvpp = Dvpp(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, "../outputs")): os.mkdir(os.path.join(SRC_PATH, "../outputs")) image_info = construct_image_info() for image_file in images_list: image = AclImage(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")
def main(): """ main """ if (len(sys.argv) != 2): print("The App arg is invalid") exit(1) acl_resource = AclResource() acl_resource.init() model = Model(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, "../outputs")): os.mkdir(os.path.join(SRC_PATH, "../outputs")) 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")
def main(): """ Program execution """ if not os.path.exists(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) acl_resource = AclResource() # acl intialize acl_resource.init() model = Model(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')
def main(): """ Program execution with picture directory parameters """ if (len(sys.argv) != 2): print("The App arg is invalid") exit(1) acl_resource = AclResource() acl_resource.init() model = Model(MODEL_PATH) dvpp = Dvpp(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('../outputs'): os.mkdir('../outputs') image_info = construct_image_info() for image_file in images_list: #read picture image = AclImage(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)
def main(): acl_resource = AclResource() acl_resource.init() mnist = input_data.read_data_sets('MNIST_data/', one_hot=True) #load model model = Model(model_path) images = mnist.test.images labels = mnist.test.labels total = len(images) correct = 0.0 start = time.time() for i in range(len(images)): result = model.execute([images[i]]) label = labels[i] if np.argmax(result[0])==np.argmax(label): correct+=1.0 if i%1000==0: print(f'infer {i+1} pics...') end = time.time() print(f'infer finished, acc is {correct/total}, use time {(end-start)*1000}ms')
def main(): """main""" #acl init if (len(sys.argv) != 2): print("The App arg is invalid") exit(1) acl_resource = AclResource() acl_resource.init() model = Model(MODEL_PATH) dvpp = Dvpp(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, "../outputs")): os.mkdir(os.path.join(SRC_PATH, "../outputs")) #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")
def main(): if not os.path.exists(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) #ACL resource initialization acl_resource = AclResource() acl_resource.init() #load model model = Model(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) #data, orig = preprocess(bgr_img) #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")
def main(): if not os.path.exists(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) #ACL resource initialization acl_resource = AclResource() acl_resource.init() #load model model = Model(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")
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 const.IMG_EXT ] acl_resource = AclResource() acl_resource.init() edge_detection = EdgeDetection(MODEL_PATH, MODEL_WIDTH, MODEL_HEIGHT) ret = edge_detection.init() utils.check_ret("edge_detection 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.basename(image_file) print('====' + image_name + '====') # read image im = Image.open(image_file) if len(im.split()) != 3: print('warning: "{}" is not a color image and will be ignored'. format(image_file)) continue # Preprocess the picture resized_image = edge_detection.pre_process(im) # Inferencecd result = edge_detection.inference([ resized_image, ]) # # Post-processing edge_detection.post_process(result, image_name)
def main(): """main""" #Initialize acl acl_resource = AclResource() acl_resource.init() #Create a detection network instance, currently using the vgg_ssd network. # When the detection network is replaced, instantiate a new network here detect = VggSsd(acl_resource, MODEL_WIDTH, MODEL_HEIGHT) #Load offline model model = Model(MODEL_PATH) #Connect to the presenter server according to the configuration, # and end the execution of the application if the connection fails chan = presenteragent.presenter_channel.open_channel(FACE_DETEC_CONF) if chan is None: print("Open presenter channel failed") return #Open the CARAMER0 camera on the development board cap = Camera(0) while True: #Read a picture from the camera image = cap.read() if image is None: print("Get memory from camera failed") break #The detection network processes images into model input data model_input = detect.pre_process(image) if model_input is None: print("Pre process image failed") break #Send data to offline model inference result = model.execute(model_input) #Detecting network analysis inference output 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)
def main(): # check param if (len(sys.argv) != 2): 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 = AclResource() acl_resource.init() # instantiation Cartoonization object cartoonization = Cartoonization(MODEL_PATH, MODEL_WIDTH, MODEL_HEIGHT) # init ret = cartoonization.init() utils.check_ret("Cartoonization.init ", ret) # create dir to save result if not os.path.isdir('../outputs'): os.mkdir('../outputs') for image_file in images_list: # read image image = AclImage(image_file) # preprocess crop_and_paste_image = cartoonization.pre_process(image) print("[Sample] pre process end") # inference result = cartoonization.inference([ crop_and_paste_image, ]) # postprocess cartoonization.post_process(result, image_file, image)
def main(): """ main """ image_dir = os.path.join(currentPath, "data") if not os.path.exists(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) acl_resource = AclResource() acl_resource.init() classify = Classify(MODEL_PATH, MODEL_WIDTH, MODEL_HEIGHT) ret = classify.init() utils.check_ret("Classify 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: print('=== ' + os.path.basename(image_file) + '===') # read image image = AclImage(image_file) # Preprocess the picture resized_image = classify.pre_process(image) # Inferencecd result = classify.inference([ resized_image, ]) # # Post-processing classify.post_process(result, image_file)
def main(opt): acl_resource = AclResource() acl_resource.init() mot_model = Model('../model/dlav0.om') # Create output dir if not exist; default outputs result_root = opt.output_root if opt.output_root != '' else '.' mkdir_if_missing(result_root) video_name = os.path.basename(opt.input_video).replace(' ', '_').split('.')[0] # setup dataloader, use LoadVideo or LoadImages dataloader = LoadVideo(opt.input_video, (1088, 608)) # result_filename = os.path.join(result_root, 'results.txt') frame_rate = dataloader.frame_rate # dir for output images; default: outputs/'VideoFileName' save_dir = os.path.join(result_root, video_name) if save_dir and os.path.exists(save_dir) and opt.rm_prev: shutil.rmtree(save_dir) mkdir_if_missing(save_dir) # initialize tracker tracker = JDETracker(opt, mot_model, frame_rate=frame_rate) 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: 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] > opt.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(save_dir, '{:05d}.jpg'.format(frame_id)), online_im)
def main(): if (len(sys.argv) != 2): print("Please input video path") exit(1) #ACL resource initialization acl_resource = AclResource() acl_resource.init() #load model model = Model(MODEL_PATH) #open video video_path = sys.argv[1] print("open video ", video_path) cap = cv.VideoCapture(video_path) fps = cap.get(cv.CAP_PROP_FPS) Width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH)) Height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT)) lf.set_img_size((Width, Height)) #create output directory if not os.path.exists(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) output_Video = os.path.basename(video_path) output_Video = os.path.join(OUTPUT_DIR, output_Video) fourcc = cv.VideoWriter_fourcc(*'mp4v') # DIVX, XVID, MJPG, X264, WMV1, WMV2 outVideo = cv.VideoWriter(output_Video, fourcc, fps, (Width, Height)) # Read until video is completed while (cap.isOpened()): ret, frame = cap.read() if ret == True: #preprocess data, orig = preprocess(frame) #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(frame) 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) outVideo.write(frame_with_lane) # Break the loop else: break cap.release() outVideo.release() print("Execute end")
def main(): """main""" if (len(sys.argv) != 2): print("The App arg is invalid") exit(1) acl_resource = AclResource() acl_resource.init() model = Model(MODEL_PATH) dvpp = Dvpp(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 save inference results if not os.path.isdir('./outputs'): os.mkdir('./outputs') # Create a directory to save the intermediate results of the large image detection if not os.path.isdir('./bigpic'): os.mkdir('./bigpic') # Create a directory to save the results of the big picture cropping inference outCrop = os.path.join('./bigpic', 'output') if not os.path.isdir(outCrop): os.mkdir(outCrop) # Create a directory, save the large and cropped pictures cropImg = os.path.join('./bigpic', 'cropimg') if not os.path.isdir(cropImg): os.mkdir(cropImg) image_info = construct_image_info() for image_file in images_list: imagename = get_file_name(image_file) tempfile = os.path.splitext(imagename)[0] imgdic = {} imgdic['name'] = imagename obj_res = [] img = cv2.imread(image_file, -1) (width, height, depth) = img.shape if width > 1000 and height > 1000: # Create a directory to save the divided pictures of each big picture crop_target = os.path.join(cropImg, tempfile) if not os.path.isdir(crop_target): os.mkdir(crop_target) # Create a directory to save the inference results of each large image out_target = os.path.join(outCrop, tempfile) if not os.path.isdir(out_target): os.mkdir(out_target) # Large image clipping function crop_picture(image_file, crop_target) cropimg_list = [ os.path.join(crop_target, imgs) for imgs in os.listdir(crop_target) if os.path.splitext(imgs)[1] in const.IMG_EXT ] # After the execution of the crop function is over, # the small picture after the big picture crop should be saved in a folder crop_target for cropimg_file in cropimg_list: print("the crop filename is :\t", cropimg_file) image = AclImage(cropimg_file) resized_image = pre_process(image, dvpp) result = model.execute([resized_image, image_info]) resdic = post_process_big(result, image, cropimg_file, out_target) obj_res.extend(resdic) imgdic['object_result'] = obj_res merge_picture(out_target, tempfile) # Read in the picture, if the picture size is less than 1000x1000, # it will be read in and processed normally else: print("detect the small picture") image = AclImage(image_file) resized_image = pre_process(image, dvpp) print("pre process end") result = model.execute([resized_image, image_info]) resdic = post_process(result, image, image_file) obj_res.extend(resdic) imgdic['object_result'] = obj_res
print("result = ", inference_result) print("preprocess cost:", t2 - t1) print("forward cost:", t3 - t2) print("post process cost:", t4 - t3) print("FPS:", 1 / (t4 - t1)) print("*" * 40) return inference_result else: return dict() if __name__ == "__main__": # acl resource init acl_resource = AclResource() acl_resource.init() # load om model yolov3_model = Model(MODEL_PATH) # send the multicast message multicast_group = (LOCAL_IP_ADDRESS, PORT) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) connections = {} try: # Send data to the multicast group print('sending "%s"' % 'EtherSensePing' + str(multicast_group)) sent = sock.sendto('EtherSensePing'.encode(), multicast_group) # defer waiting for a response using Asyncore