visual.py 11.4 KB
Newer Older
J
Jethong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
import os
import numpy as np
import cv2
import time


def visualize_e2e_result(im_fn, poly_list, seq_strs, src_im):
    """
    """
    result_path = './out'
    im_basename = os.path.basename(im_fn)
    im_prefix = im_basename[:im_basename.rfind('.')]
    vis_det_img = src_im.copy()
    valid_set = 'partvgg'
    gt_dir = "/Users/hongyongjie/Downloads/part_vgg_synth/train"
    text_path = os.path.join(gt_dir, im_prefix + '.txt')
    fid = open(text_path, 'r')
    lines = [line.strip() for line in fid.readlines()]
    for line in lines:
        if valid_set == 'partvgg':
            tokens = line.strip().split('\t')[0].split(',')
            # tokens = line.strip().split(',')
            coords = tokens[:]
            coords = list(map(float, coords))
            gt_poly = np.array(coords).reshape(1, 4, 2)
        elif valid_set == 'totaltext':
            tokens = line.strip().split('\t')[0].split(',')
            coords = tokens[:]
            coords_len = len(coords) / 2
            coords = list(map(float, coords))
            gt_poly = np.array(coords).reshape(1, coords_len, 2)
        cv2.polylines(
            vis_det_img,
            np.array(gt_poly).astype(np.int32),
            isClosed=True,
            color=(255, 0, 0),
            thickness=2)

    for detected_poly, recognized_str in zip(poly_list, seq_strs):
        cv2.polylines(
            vis_det_img,
            np.array(detected_poly[np.newaxis, ...]).astype(np.int32),
            isClosed=True,
            color=(0, 0, 255),
            thickness=2)
        cv2.putText(
            vis_det_img,
            recognized_str,
            org=(int(detected_poly[0, 0]), int(detected_poly[0, 1])),
            fontFace=cv2.FONT_HERSHEY_COMPLEX,
            fontScale=0.7,
            color=(0, 255, 0),
            thickness=1)

    if not os.path.exists(result_path):
        os.makedirs(result_path)
    cv2.imwrite("{}/{}_detection.jpg".format(result_path, im_prefix),
                vis_det_img)


def visualization_output(src_image,
                         f_tcl,
                         f_chars,
                         output_dir,
                         image_prefix=None):
    """
    """
    # restore BGR image, CHW -> HWC
    im_mean = [0.485, 0.456, 0.406]
    im_std = [0.229, 0.224, 0.225]

    im_mean = np.array(im_mean).reshape((3, 1, 1))
    im_std = np.array(im_std).reshape((3, 1, 1))
    src_image *= im_std
    src_image += im_mean
    src_image = src_image.transpose([1, 2, 0])
    src_image = src_image[:, :, ::-1] * 255  # BGR -> RGB
    H, W, _ = src_image.shape

    file_prefix = image_prefix if image_prefix is not None else str(
        int(time.time() * 1000))
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # visualization f_tcl
    tcl_file_name = os.path.join(output_dir, file_prefix + '_0_tcl.jpg')
    vis_tcl_img = src_image.copy()
    f_tcl_resized = cv2.resize(f_tcl, dsize=(W, H))
    vis_tcl_img[:, :, 1] = f_tcl_resized * 255
    cv2.imwrite(tcl_file_name, vis_tcl_img)

    # visualization char maps
    vis_char_img = src_image.copy()
    # CHW -> HWC
    char_file_name = os.path.join(output_dir, file_prefix + '_1_chars.jpg')
    f_chars = np.argmax(f_chars, axis=2)[:, :, np.newaxis].astype('float32')
    f_chars[f_chars < 95] = 1.0
    f_chars[f_chars == 95] = 0.0
    f_chars_resized = cv2.resize(f_chars, dsize=(W, H))
    vis_char_img[:, :, 1] = f_chars_resized * 255
    cv2.imwrite(char_file_name, vis_char_img)


def visualize_point_result(im_fn, point_list, point_pair_list, src_im, gt_dir,
                           result_path):
    """
    """
    im_basename = os.path.basename(im_fn)
    im_prefix = im_basename[:im_basename.rfind('.')]
    vis_det_img = src_im.copy()

    # draw gt bbox on the image.
    text_path = os.path.join(gt_dir, im_prefix + '.txt')
    fid = open(text_path, 'r')
    lines = [line.strip() for line in fid.readlines()]
    for line in lines:
        tokens = line.strip().split('\t')
        coords = tokens[0].split(',')
        coords_len = len(coords)
        coords = list(map(float, coords))
        gt_poly = np.array(coords).reshape(1, coords_len / 2, 2)
        cv2.polylines(
            vis_det_img,
            np.array(gt_poly).astype(np.int32),
            isClosed=True,
            color=(255, 255, 255),
            thickness=1)

    for point, point_pair in zip(point_list, point_pair_list):
        cv2.line(
            vis_det_img,
            tuple(point_pair[0]),
            tuple(point_pair[1]), (0, 255, 255),
            thickness=1)
        cv2.circle(vis_det_img, tuple(point), 2, (0, 0, 255))
        cv2.circle(vis_det_img, tuple(point_pair[0]), 2, (255, 0, 0))
        cv2.circle(vis_det_img, tuple(point_pair[1]), 2, (0, 255, 0))

    if not os.path.exists(result_path):
        os.makedirs(result_path)
    cv2.imwrite("{}/{}_border_points.jpg".format(result_path, im_prefix),
                vis_det_img)


def resize_image(im, max_side_len=512):
    """
    resize image to a size multiple of max_stride which is required by the network
    :param im: the resized image
    :param max_side_len: limit of max image size to avoid out of memory in gpu
    :return: the resized image and the resize ratio
    """
    h, w, _ = im.shape

    resize_w = w
    resize_h = h

    # Fix the longer side
    if resize_h > resize_w:
        ratio = float(max_side_len) / resize_h
    else:
        ratio = float(max_side_len) / resize_w

    resize_h = int(resize_h * ratio)
    resize_w = int(resize_w * ratio)

    max_stride = 128
    resize_h = (resize_h + max_stride - 1) // max_stride * max_stride
    resize_w = (resize_w + max_stride - 1) // max_stride * max_stride
    im = cv2.resize(im, (int(resize_w), int(resize_h)))
    ratio_h = resize_h / float(h)
    ratio_w = resize_w / float(w)

    return im, (ratio_h, ratio_w)


def resize_image_min(im, max_side_len=512):
    """
    """
    print('--> Using resize_image_min')
    h, w, _ = im.shape

    resize_w = w
    resize_h = h

    # Fix the longer side
    if resize_h < resize_w:
        ratio = float(max_side_len) / resize_h
    else:
        ratio = float(max_side_len) / resize_w

    resize_h = int(resize_h * ratio)
    resize_w = int(resize_w * ratio)

    max_stride = 128
    resize_h = (resize_h + max_stride - 1) // max_stride * max_stride
    resize_w = (resize_w + max_stride - 1) // max_stride * max_stride
    im = cv2.resize(im, (int(resize_w), int(resize_h)))
    ratio_h = resize_h / float(h)
    ratio_w = resize_w / float(w)
    return im, (ratio_h, ratio_w)


def resize_image_for_totaltext(im, max_side_len=512):
    """
    """
    h, w, _ = im.shape

    resize_w = w
    resize_h = h
    ratio = 1.25
    if h * ratio > max_side_len:
        ratio = float(max_side_len) / resize_h
        # Fix the longer side
        # if resize_h > resize_w:
        #    ratio = float(max_side_len) / resize_h
        # else:
        #    ratio = float(max_side_len) / resize_w
    ###
    resize_h = int(resize_h * ratio)
    resize_w = int(resize_w * ratio)

    max_stride = 128
    resize_h = (resize_h + max_stride - 1) // max_stride * max_stride
    resize_w = (resize_w + max_stride - 1) // max_stride * max_stride
    im = cv2.resize(im, (int(resize_w), int(resize_h)))
    ratio_h = resize_h / float(h)
    ratio_w = resize_w / float(w)
    return im, (ratio_h, ratio_w)


def point_pair2poly(point_pair_list):
    """
    Transfer vertical point_pairs into poly point in clockwise.
    """
    pair_length_list = []
    for point_pair in point_pair_list:
        pair_length = np.linalg.norm(point_pair[0] - point_pair[1])
        pair_length_list.append(pair_length)
    pair_length_list = np.array(pair_length_list)
    pair_info = (pair_length_list.max(), pair_length_list.min(),
                 pair_length_list.mean())

    # constract poly
    point_num = len(point_pair_list) * 2
    point_list = [0] * point_num
    for idx, point_pair in enumerate(point_pair_list):
        point_list[idx] = point_pair[0]
        point_list[point_num - 1 - idx] = point_pair[1]
    return np.array(point_list).reshape(-1, 2), pair_info


def shrink_quad_along_width(quad, begin_width_ratio=0., end_width_ratio=1.):
    """
    Generate shrink_quad_along_width.
    """
    ratio_pair = np.array(
        [[begin_width_ratio], [end_width_ratio]], dtype=np.float32)
    p0_1 = quad[0] + (quad[1] - quad[0]) * ratio_pair
    p3_2 = quad[3] + (quad[2] - quad[3]) * ratio_pair
    return np.array([p0_1[0], p0_1[1], p3_2[1], p3_2[0]])


def expand_poly_along_width(poly, shrink_ratio_of_width=0.3):
    """
    expand poly along width.
    """
    point_num = poly.shape[0]
    left_quad = np.array(
        [poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32)
    left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \
                 (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6)
    left_quad_expand = shrink_quad_along_width(left_quad, left_ratio, 1.0)
    right_quad = np.array(
        [
            poly[point_num // 2 - 2], poly[point_num // 2 - 1],
            poly[point_num // 2], poly[point_num // 2 + 1]
        ],
        dtype=np.float32)
    right_ratio = 1.0 + \
                  shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \
                  (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6)
    right_quad_expand = shrink_quad_along_width(right_quad, 0.0, right_ratio)
    poly[0] = left_quad_expand[0]
    poly[-1] = left_quad_expand[-1]
    poly[point_num // 2 - 1] = right_quad_expand[1]
    poly[point_num // 2] = right_quad_expand[2]
    return poly


def norm2(x, axis=None):
    if axis:
        return np.sqrt(np.sum(x**2, axis=axis))
    return np.sqrt(np.sum(x**2))


def cos(p1, p2):
    return (p1 * p2).sum() / (norm2(p1) * norm2(p2))


def generate_direction_info(image_fn,
                            H,
                            W,
                            ratio_h,
                            ratio_w,
                            max_length=640,
                            out_scale=4,
                            gt_dir=None):
    """
    """
    im_basename = os.path.basename(image_fn)
    im_prefix = im_basename[:im_basename.rfind('.')]
    instance_direction_map = np.zeros(shape=[H // out_scale, W // out_scale, 3])

    if gt_dir is None:
        gt_dir = '/home/vis/huangzuming/data/SYNTH_DATA/part_vgg_synth_icdar/processed/val/poly'

    # get gt label map
    text_path = os.path.join(gt_dir, im_prefix + '.txt')
    fid = open(text_path, 'r')
    lines = [line.strip() for line in fid.readlines()]
    for label_idx, line in enumerate(lines, start=1):
        coords, txt = line.strip().split('\t')
        if txt == '###':
            continue
        tokens = coords.strip().split(',')
        coords = list(map(float, tokens))
        poly = np.array(coords).reshape(4, 2) * np.array(
            [ratio_w, ratio_h]).reshape(1, 2) / out_scale
        mid_idx = poly.shape[0] // 2
        direct_vector = (
            (poly[mid_idx] + poly[mid_idx - 1]) - (poly[0] + poly[-1])) / 2.0

        direct_vector /= len(txt)
        # l2_distance = norm2(direct_vector)
        # avg_char_distance = l2_distance / len(txt)
        avg_char_distance = 1.0

        direct_label = (direct_vector[0], direct_vector[1], avg_char_distance)
        cv2.fillPoly(instance_direction_map,
                     poly.round().astype(np.int32)[np.newaxis, :, :],
                     direct_label)
    instance_direction_map = instance_direction_map.transpose([2, 0, 1])
    return instance_direction_map[:2, ...]