Esempio n. 1
0
def create_label_file(root_dir,
                      verbose=False,
                      dst_h=h_for_train,
                      dst_w=w_for_train):
    """
    create a corresponding label file using opencv subpixel
    for all the image files in root_dir

    :param root_dir:
    :return:
    """
    exts_allowed = ('JPEG', 'jpg')
    root_pre = None
    MAX_IMG_SHOWN = 10
    count = 0
    for root, dirs, files in os.walk(root_dir):
        if root != root_pre:
            root_pre = root
            print('marking files in directory:', root)
        for img_file_name in files:
            is_img = False
            img_file_ext = img_file_name.split('.')[-1]
            for ext in exts_allowed:
                is_img = is_img or img_file_ext == ext
            if is_img:
                count += 1
                file_name_prefix = '.'.join(img_file_name.split('.')[:-1])
                txt_file_name = '.'.join([file_name_prefix, 'txt'])
                img_file_path = os.path.join(root, img_file_name)
                txt_file_path = os.path.join(root, txt_file_name)

                if verbose and count <= MAX_IMG_SHOWN:
                    my_imshow(img)

                img = cv2.imread(img_file_path)
                resized_img = np.array(
                    Image.fromarray(img).resize((dst_w, dst_h)))
                centroids = cv_harris(resized_img, thres=harris_thres)

                img = cv2.imread(img_file_path)
                img_h, img_w = img.shape[:2]
                centroids_for_subpix = centroids.copy()
                centroids_for_subpix[:, 0] *= (img_w / dst_w)
                centroids_for_subpix[:, 1] *= (img_h / dst_h)
                corners = cv_subpixel(img, centroids=centroids_for_subpix)
                corners[:, 0] *= (dst_w / img_w)
                corners[:, 1] *= (dst_h / img_h)

                res = np.hstack((corners, centroids))
                with open(txt_file_path, 'w') as f:
                    for corner_x, corner_y, centoird_x, centroid_y in res:
                        f.write(str(corner_x))
                        f.write('\t')
                        f.write(str(corner_y))
                        f.write('\t')
                        f.write(str(centoird_x))
                        f.write('\t')
                        f.write(str(centroid_y))
                        f.write('\n')
Esempio n. 2
0
 def __init__(self, img, win_size=20, pars=None, verbose=False):
     self.pars = {'common': dict(canny_thres1=50, canny_thres2=200, canny_apertureSize=3, harris_thres=0.1),
                  '+': dict(max_dist=40, rho_thres=1, theta_thres=5 * PI / 180, parallel_dist=10,
                            hough_thres=int(1.5 * win_size), noise_thres=10, merge_thres=3.0)}
     try:
         if pars is not None:
             for outer_key in pars:
                 if outer_key not in self.pars:
                     print("Unacceptable parameter {}".format(outer_key))
                     raise IndexError
                 for inner_key in pars[outer_key]:
                     if inner_key not in self.pars[outer_key]:
                         print("Unacceptable parameter {}-{}".format(outer_key, inner_key))
                         raise IndexError
                     self.pars[outer_key][inner_key] = pars[outer_key][inner_key]
     except IndexError as e:
         traceback.print_exc()
         raise e
     self.img = img
     self.win_size = win_size
     self.img_edged = cv2.Canny(img, self.pars['common']['canny_thres1'],
                                self.pars['common']['canny_thres2'],
                                self.pars['common']['canny_apertureSize'])  # edge the img once
     self.verbose = verbose
     self.centroids = cv_subpixel(img, harris_thres)
     self.proc_idx = None
     self.proc_centroid = None
     if verbose:
         self.target_window = dict(left=200, right=300, top=200, bottom=300)
         cache_num = 0
         while os.path.exists(os.path.join('.', 'cache' + str(cache_num))):
             cache_num += 1
         cache_dir = os.path.join('.', 'cache' + str(cache_num))
         os.makedirs(cache_dir)
         self.cache_dir = cache_dir
         my_imshow(self.img_edged, title='img-edged')
     else:
         self.cache_dir = None
Esempio n. 3
0
    cv_time = 0.0
    for i, sample in enumerate(dataset):
        img = sample['img']
        corners = sample['corners']

        time_start = time.time()  # time in second
        my_corners = my_subpixel(img,
                                 model,
                                 win_size,
                                 harris_thres=harris_thres,
                                 use_cuda=use_cuda)
        time_end = time.time()
        my_time += (time_end - time_start)

        time_start = time.time()  # time in second
        cv_corners = cv_subpixel(img, harris_thres=harris_thres)
        time_end = time.time()
        cv_time += (time_end - time_start)

        my_dist = evaluate_dist(test_corners=my_corners, ref_corners=corners)
        my_dist_sum += my_dist
        cv_dist = evaluate_dist(test_corners=cv_corners, ref_corners=corners)
        cv_dist_sum += cv_dist
        num_corners += len(corners)
        if i % 100 == 0:
            print('%d images processed' % i)
    my_dist_mean = my_dist_sum / num_corners
    cv_dist_mean = cv_dist_sum / num_corners

    print('-' * 40)
    print('my subpixel:')
Esempio n. 4
0
                        union.union(ii, jj)
        components = union.components()
        comp_set = []
        for component in components:
            set_t = np.array(ver_set)[list(component)]
            comp_set.append(set_t.mean(axis=0))
        return np.array(comp_set).reshape(-1, 2)


if __name__ == "__main__":
    thickness = 2
    file_name = 'cross.jpg'
    img = cv2.imread(os.path.join(data_dir, file_name))
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    centroids = cv_subpixel(img, 0.1)
    all_centroids = draw_marker(img, centroids, thickness=thickness)
    my_imshow(all_centroids, title='all centroids')
    print('centroids:')
    print(centroids)

    thickness = 10
    finder = MarkerFinder(img, win_size=20, verbose=False)
    corners = finder.find_corners()
    print('corners:')
    print(corners)
    img_drawn = img
    img_drawn = draw_marker(img_drawn, corners['+'], thickness=thickness, color=np.array((255, 0, 0)))
    # # img_drawn = draw_marker(img_drawn, corners[1], thickness=thickness, color=np.array((0, 255, 0)))
    # # img_drawn = draw_marker(img_drawn, corners[2], thickness=thickness, color=np.array((0, 0, 255)))
    # # img_drawn = draw_marker(img_drawn, corners[3], thickness=thickness, color=np.array((255, 0, 255)))
    groundtruth_corners = []
    with open(txt_path, 'r') as f:
        for line in f:
            corner_x, corner_y, centroid_x, centroid_y = line.split()
            groundtruth_corners.append((float(corner_x), float(corner_y)))
    my_imshow(ori_img, show_in_func=True)
    save_dir = "results"
    plt.savefig(osp.join(save_dir, "ori_img.png"))
    img = draw_marker(ori_img,
                      groundtruth_corners,
                      thickness=1,
                      color=np.array([255, 0, 255]))
    print(len(groundtruth_corners))
    print(groundtruth_corners)

    corners_cv_sub = cv_subpixel(ori_img, harris_thres=harris_thres)
    img_cvsub = draw_marker(img,
                            corners_cv_sub,
                            thickness,
                            color=np.array([0, 0, 255]))
    print(len(corners_cv_sub))
    print('cv_subpix')
    print(corners_cv_sub)
    my_imshow(img_cvsub, title='cv subpixel', show_in_func=True)
    plt.savefig(osp.join(save_dir, "cv-subpixel.png"))

    corners_harris = cv_harris(ori_img, thres=harris_thres)
    img_cvharris = draw_marker(img,
                               corners_harris,
                               thickness,
                               color=np.array([255, 0, 0]))