nonlocal_reader.py 12.6 KB
Newer Older
D
dengkaipeng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#  Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
import os
import random
import time
import multiprocessing
import numpy as np
import cv2
import logging

from .reader_utils import DataReader

logger = logging.getLogger(__name__)


class NonlocalReader(DataReader):
    """
    Data reader for kinetics dataset, which read mp4 file and decode into numpy.
    This is for nonlocal neural network model.
          cfg:  num_classes
                num_reader_threads
                image_mean
                image_std
                batch_size
S
SunGaofeng 已提交
37
                filelist
38 39 40 41 42 43 44 45
                crop_size
                sample_rate
                video_length
                jitter_scales
                Test only cfg: num_test_clips
                               use_multi_crop
    """

46
    def __init__(self, name, mode, cfg):
47
        self.name = name
48
        self.mode = mode
49 50 51 52
        self.cfg = cfg

    def create_reader(self):
        cfg = self.cfg
53 54
        mode = self.mode
        num_reader_threads = cfg[mode.upper()]['num_reader_threads']
55 56 57
        assert num_reader_threads >=1, \
                "number of reader threads({}) should be a positive integer".format(num_reader_threads)
        if num_reader_threads == 1:
58 59 60 61 62
            reader_func = make_reader
        else:
            reader_func = make_multi_reader

        dataset_args = {}
63 64
        dataset_args['image_mean'] = cfg.MODEL.image_mean
        dataset_args['image_std'] = cfg.MODEL.image_std
65 66 67 68 69
        dataset_args['crop_size'] = cfg[mode.upper()]['crop_size']
        dataset_args['sample_rate'] = cfg[mode.upper()]['sample_rate']
        dataset_args['video_length'] = cfg[mode.upper()]['video_length']
        dataset_args['min_size'] = cfg[mode.upper()]['jitter_scales'][0]
        dataset_args['max_size'] = cfg[mode.upper()]['jitter_scales'][1]
70
        dataset_args['num_reader_threads'] = num_reader_threads
S
SunGaofeng 已提交
71
        filelist = cfg[mode.upper()]['filelist']
72
        batch_size = cfg[mode.upper()]['batch_size']
73

74
        if self.mode == 'train':
75
            sample_times = 1
76 77
            return reader_func(filelist, batch_size, sample_times, True, True,
                               **dataset_args)
78
        elif self.mode == 'valid':
79
            sample_times = 1
80 81
            return reader_func(filelist, batch_size, sample_times, False, False,
                               **dataset_args)
82
        elif self.mode == 'test':
83 84
            sample_times = cfg['TEST']['num_test_clips']
            if cfg['TEST']['use_multi_crop'] == 1:
85
                sample_times = int(sample_times / 3)
86
            if cfg['TEST']['use_multi_crop'] == 2:
87
                sample_times = int(sample_times / 6)
88 89
            return reader_func(filelist, batch_size, sample_times, False, False,
                               **dataset_args)
90 91
        else:
            logger.info('Not implemented')
S
SunGaofeng 已提交
92
            raise NotImplementedError
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
def video_fast_get_frame(video_path,
                         sampling_rate=1,
                         length=64,
                         start_frm=-1,
                         sample_times=1):
    cap = cv2.VideoCapture(video_path)
    frame_cnt = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    sampledFrames = []

    video_output = np.ndarray(shape=[length, height, width, 3], dtype=np.uint8)

    use_start_frm = start_frm
    if start_frm < 0:
        if (frame_cnt - length * sampling_rate > 0):
            use_start_frm = random.randint(0,
                                           frame_cnt - length * sampling_rate)
        else:
            use_start_frm = 0
    else:
        frame_gaps = float(frame_cnt) / float(sample_times)
        use_start_frm = int(frame_gaps * start_frm) % frame_cnt

    for i in range(frame_cnt):
        ret, frame = cap.read()
        # maybe first frame is empty
        if ret == False:
            continue
        img = frame[:, :, ::-1]
        sampledFrames.append(img)

    for idx in range(length):
        i = use_start_frm + idx * sampling_rate
        i = i % len(sampledFrames)
        video_output[idx] = sampledFrames[i]

    cap.release()
    return video_output


137 138 139 140 141 142 143 144 145 146 147 148
def apply_resize(rgbdata, min_size, max_size):
    length, height, width, channel = rgbdata.shape
    ratio = 1.0
    # generate random scale between [min_size, max_size]
    if min_size == max_size:
        side_length = min_size
    else:
        side_length = np.random.randint(min_size, max_size)
    if height > width:
        ratio = float(side_length) / float(width)
    else:
        ratio = float(side_length) / float(height)
S
SunGaofeng 已提交
149 150
    out_height = int(round(height * ratio))
    out_width = int(round(width * ratio))
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
    outdata = np.zeros(
        (length, out_height, out_width, channel), dtype=rgbdata.dtype)
    for i in range(length):
        outdata[i] = cv2.resize(rgbdata[i], (out_width, out_height))
    return outdata


def crop_mirror_transform(rgbdata,
                          mean,
                          std,
                          cropsize=224,
                          use_mirror=True,
                          center_crop=False,
                          spatial_pos=-1):
    channel, length, height, width = rgbdata.shape
    assert height >= cropsize, "crop size should not be larger than video height"
    assert width >= cropsize, "crop size should not be larger than video width"
    # crop to specific scale
    if center_crop:
        h_off = int((height - cropsize) / 2)
        w_off = int((width - cropsize) / 2)
        if spatial_pos >= 0:
            now_pos = spatial_pos % 3
            if h_off > 0:
                h_off = h_off * now_pos
            else:
                w_off = w_off * now_pos
    else:
        h_off = np.random.randint(0, height - cropsize)
        w_off = np.random.randint(0, width - cropsize)
    outdata = np.zeros(
        (channel, length, cropsize, cropsize), dtype=rgbdata.dtype)
    outdata[:, :, :, :] = rgbdata[:, :, h_off:h_off + cropsize, w_off:w_off +
                                  cropsize]
    # apply mirror
    mirror_indicator = (np.random.rand() > 0.5)
    mirror_me = use_mirror and mirror_indicator
    if spatial_pos > 0:
        mirror_me = (int(spatial_pos / 3) > 0)
    if mirror_me:
        outdata = outdata[:, :, :, ::-1]
    # substract mean and divide std
    outdata = outdata.astype(np.float32)
    outdata = (outdata - mean) / std
    return outdata


def make_reader(filelist, batch_size, sample_times, is_training, shuffle,
                **dataset_args):
S
SunGaofeng 已提交
200 201 202
    def reader():
        fl = open(filelist).readlines()
        fl = [line.strip() for line in fl if line.strip() != '']
203

S
SunGaofeng 已提交
204 205
        if shuffle:
            random.shuffle(fl)
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

        batch_out = []
        for line in fl:
            # start_time = time.time()
            line_items = line.split(' ')
            fn = line_items[0]
            label = int(line_items[1])
            if len(line_items) > 2:
                start_frm = int(line_items[2])
                spatial_pos = int(line_items[3])
                in_sample_times = sample_times
            else:
                start_frm = -1
                spatial_pos = -1
                in_sample_times = 1
            label = np.array([label]).astype(np.int64)
            # 1, get rgb data for fixed length of frames
            try:
224
                rgbdata = video_fast_get_frame(fn, \
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
                             sampling_rate = dataset_args['sample_rate'], length = dataset_args['video_length'], \
                             start_frm = start_frm, sample_times = in_sample_times)
            except:
                logger.info('Error when loading {}, just skip this file'.format(
                    fn))
                continue
            # add prepocessing
            # 2, reszie to randomly scale between [min_size, max_size] when training, or cgf.TEST.SCALE when inference
            min_size = dataset_args['min_size']
            max_size = dataset_args['max_size']
            rgbdata = apply_resize(rgbdata, min_size, max_size)
            # transform [length, height, width, channel] to [channel, length, height, width]
            rgbdata = np.transpose(rgbdata, [3, 0, 1, 2])

            # 3 crop, mirror and transform
            rgbdata = crop_mirror_transform(rgbdata, mean = dataset_args['image_mean'], \
                             std = dataset_args['image_std'], cropsize = dataset_args['crop_size'], \
                             use_mirror = is_training, center_crop = (not is_training), \
                             spatial_pos = spatial_pos)

            batch_out.append((rgbdata, label))
            if len(batch_out) == batch_size:
                yield batch_out
                batch_out = []

    return reader


def make_multi_reader(filelist, batch_size, sample_times, is_training, shuffle,
                      **dataset_args):
    def read_into_queue(flq, queue):
        batch_out = []
        for line in flq:
            line_items = line.split(' ')
            fn = line_items[0]
            label = int(line_items[1])
            if len(line_items) > 2:
                start_frm = int(line_items[2])
                spatial_pos = int(line_items[3])
                in_sample_times = sample_times
            else:
                start_frm = -1
                spatial_pos = -1
                in_sample_times = 1
            label = np.array([label]).astype(np.int64)
            # 1, get rgb data for fixed length of frames
            try:
272
                rgbdata = video_fast_get_frame(fn, \
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
                             sampling_rate = dataset_args['sample_rate'], length = dataset_args['video_length'], \
                             start_frm = start_frm, sample_times = in_sample_times)
            except:
                logger.info('Error when loading {}, just skip this file'.format(
                    fn))
                continue
            # add prepocessing
            # 2, reszie to randomly scale between [min_size, max_size] when training, or cgf.TEST.SCALE when inference
            min_size = dataset_args['min_size']
            max_size = dataset_args['max_size']
            rgbdata = apply_resize(rgbdata, min_size, max_size)
            # transform [length, height, width, channel] to [channel, length, height, width]
            rgbdata = np.transpose(rgbdata, [3, 0, 1, 2])

            # 3 crop, mirror and transform
            rgbdata = crop_mirror_transform(rgbdata, mean = dataset_args['image_mean'], \
                             std = dataset_args['image_std'], cropsize = dataset_args['crop_size'], \
                             use_mirror = is_training, center_crop = (not is_training), \
                             spatial_pos = spatial_pos)

            batch_out.append((rgbdata, label))
            if len(batch_out) == batch_size:
                queue.put(batch_out)
                batch_out = []
        queue.put(None)

    def queue_reader():
S
SunGaofeng 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
        # split file list and shuffle
        fl = open(filelist).readlines()
        fl = [line.strip() for line in fl if line.strip() != '']

        if shuffle:
            random.shuffle(fl)

        n = dataset_args['num_reader_threads']
        queue_size = 20
        reader_lists = [None] * n
        file_num = int(len(fl) // n)
        for i in range(n):
            if i < len(reader_lists) - 1:
                tmp_list = fl[i * file_num:(i + 1) * file_num]
            else:
                tmp_list = fl[i * file_num:]
            reader_lists[i] = tmp_list

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
        queue = multiprocessing.Queue(queue_size)
        p_list = [None] * len(reader_lists)
        # for reader_list in reader_lists:
        for i in range(len(reader_lists)):
            reader_list = reader_lists[i]
            p_list[i] = multiprocessing.Process(
                target=read_into_queue, args=(reader_list, queue))
            p_list[i].start()
        reader_num = len(reader_lists)
        finish_num = 0
        while finish_num < reader_num:
            sample = queue.get()
            if sample is None:
                finish_num += 1
            else:
                yield sample
        for i in range(len(p_list)):
            p_list[i].terminate()
            p_list[i].join()

    return queue_reader