ImageFeed.es6 11.8 KB
Newer Older
W
wangqun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* eslint-disable */
/**
 * @file image,feed 获取图像相关输入
 * @author wangqun@baidu.com
 */
export default class imageFeed {
    constructor() {
        this.fromPixels2DContext = document.createElement('canvas').getContext('2d');
        this.fromPixels2DContext2 = document.createElement('canvas').getContext('2d');
        this.defaultWidth = 224;
        this.defaultHeight = 224;
        this.minPixels = 225;
        this.pixels = '';
        this.defaultParams = {
            gapFillWith: '#000',
W
wangqun 已提交
16
            mean: [0, 0, 0],
W
wangqun 已提交
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
            std: [1, 1, 1]
        };
    };

    /**
     * 处理图像方法
     * @param inputs
     */
    process(inputs) {
        const input = inputs.input;
        const mode = inputs.mode;
        const channel = inputs.channel;
        const rotate = inputs.rotate;
        const params = {
            ...this.defaultParams,
            ...inputs.params
        };
        let output = [];
        if (!this.result) {
            const [b, c, h, w] = params.targetShape;
            // 计算确定targetShape所需Float32Array占用空间
            this.result = new Float32Array(h * w * c);
        }
        output = this.fromPixels(input, params);
        return output;
    };

    /**
     * crop图像&重新设定图片tensor形状
     * @param shape
     */
    reshape(imageData, opt, scaleSize) {
        const {sw, sh} = scaleSize;
        const {width, height} = opt;
        const hPadding = Math.ceil((sw - width) / 2);
        const vPadding = Math.ceil((sh - height) / 2);

        let data = imageData.data;
        // channel RGB
        let red = [];
        let green = [];
        let blue = [];
        // 平均数
        let mean = opt.mean;
        // 标准差
        let std = opt.std;
        // 考虑channel因素获取数据
        for (let i = 0; i < data.length; i += 4) {
W
wangqun 已提交
65 66
            // img_mean 0.485, 0.456, 0.406
            //img_std 0.229, 0.224, 0.225
W
wangqun 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
            let index = i / 4;
            let vIndex = Math.floor(index / sw);
            let hIndex = index - (vIndex * sw) - 1;
            if (hIndex >= hPadding && hIndex < (hPadding + width) &&
                vIndex >= vPadding && vIndex < (vPadding + height)) {
                red.push(((data[i] / 255) - mean[0]) / std[0]); // red
                green.push(((data[i + 1] / 255) - mean[1]) / std[1]); // green
                blue.push(((data[i + 2] / 255) - mean[2]) / std[2]); // blue
            }
        }
        // 转成 GPU 加速 NCHW 格式
        let tmp = green.concat(blue);
        return red.concat(tmp);
    };

    /**
     * 全部转rgb * H * W
84 85 86 87 88 89
     * @param imageData 数据
     * @param opt 参数
     * @param opt.mean 均值
     * @param opt.std 方差
     * @param opt.targetShape 输出shape
     * @param opt.normalizeType 0:将数据映射为0~1, 1:映射为-1~1之间
W
wangqun 已提交
90
     */
91 92
    allReshapeToRGB(imageData, opt) {

W
wangqun 已提交
93
        // mean和std是介于0-1之间的
94 95 96 97
        let {mean, std, normalizeType = 0, targetShape} = opt;
        const [b, c, h, w] = targetShape;
        let data = imageData.data || imageData;

W
wangqun 已提交
98 99
        let result = this.result;
        let offset = 0;
100 101 102 103 104 105 106

        if (!result) {
            const [b, c, h, w] = targetShape;
            // 计算确定targetShape所需Float32Array占用空间
            result = new Float32Array(h * w * c);
         }

W
wangqun 已提交
107 108 109 110 111 112 113
        // h w c
        for (let i = 0; i < h; ++i) {
            let iw = i * w;
            for (let j = 0; j < w; ++j) {
                let iwj = iw + j;
                for (let k = 0; k < c; ++k) {
                    let a = iwj * 4 + k;
114
                    result[offset] = normalizeType === 0 ? data[a] / 255 : (data[a] - 128 ) / 128;
W
wangqun 已提交
115 116 117
                    result[offset] -= mean[k];
                    result[offset] /= std[k];
                    offset++;
W
wangqun 已提交
118 119 120
                }
            }
        }
121

W
wangqun 已提交
122 123 124
        return result;
    };

W
wangqun 已提交
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
/**
     * 全部转bgr * H * W
     * @param shape
     */
    allReshapeToBGR(imageData, opt, scaleSize) {
        //const {sw, sh} = scaleSize;
        const [b, c, h, w] = opt.targetShape;
        let data = imageData.data || imageData;
        // mean和std是介于0-1之间的
        let mean = opt.mean;
        let std = opt.std;
        let dataLength = data.length;
        // let result = new Float32Array(dataLength * 3);
        let result = this.result;
        // let offsetR = 0;
        // let offsetG = dataLength / 4;
        // let offsetB = dataLength / 2;
        let offset = 0;
        let size = h * w;
        // h w c
        for (let i = 0; i < h; ++i) {
            let iw = i * w;
            for (let j = 0; j < w; ++j) {
                let iwj = iw + j;
                for (let k = 0; k < c; ++k) {
                    let a = iwj * 4 + (2-k);
                    result[offset] = data[a];
                    result[offset] -= mean[2-k];
                    result[offset] /= std[2-k];
                    //result[offset] = 0.5;
                    offset++;
                }
            }
        }
        return result;
    };


W
wangqun 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    /**
     * 根据scale缩放图像
     * @param image
     * @param params
     * @return {Object} 缩放后的尺寸
     */
    reSize(image, params) {
        // 原始图片宽高
        const width = this.pixelWidth;
        const height = this.pixelHeight;
        // 缩放后的宽高
        let sw = width;
        let sh = height;
        // 最小边缩放到scale
        if (width < height) {
            sw = params.scale;
            sh = Math.round(sw * height / width);
        } else {
            sh = params.scale;
            sw = Math.round(sh * width / height);
        }
W
wangqun 已提交
184 185
        sw = params.scale;
        sh = params.scale;
W
wangqun 已提交
186 187 188 189 190 191 192
        this.fromPixels2DContext.canvas.width = sw;
        this.fromPixels2DContext.canvas.height = sh;
        this.fromPixels2DContext.drawImage(
            image, 0, 0, sw, sh);
        this.setInputCanvas(image);
        return {sw, sh};
    };
W
wangqun 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    /**
     * 根据scale缩放图像并且缩放成目标尺寸并居中
     */
    resizeAndFitTargetSize(image, params){
        // 原始图片宽高
        const width = this.pixelWidth;
        const height = this.pixelHeight;
        // 缩放后的宽高
        let sw = width;
        let sh = height;
        // 最小边缩放到scale
        if (width < height) {
            sw = params.scale;
            sh = Math.round(sw * height / width);
        } else {
            sh = params.scale;
            sw = Math.round(sh * width / height);
        }
W
wangqun 已提交
211

W
wangqun 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225
        this.fromPixels2DContext.canvas.width = sw;
        this.fromPixels2DContext.canvas.height = sh;
        const targetWidth = params.targetSize.width;
        const targetHeight = params.targetSize.height;
        this.fromPixels2DContext.drawImage(
            image, 0, 0, sw, sh);
        let x = (sw - targetWidth)/2;
        let y = (sh - targetHeight)/2;
        sw = targetWidth;
        sh = targetHeight;
        let data = this.getImageData(params, x, y, {sw, sh});
        this.setInputCanvas(image);
        return data;
}
W
wangqun 已提交
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

    /**
     * 缩放成目标尺寸并居中
     */
    fitToTargetSize(image, params, center) {
        // 目标尺寸
        const targetWidth = params.targetSize.width;
        const targetHeight = params.targetSize.height;
        this.fromPixels2DContext.canvas.width = targetWidth;
        this.fromPixels2DContext.canvas.height = targetHeight;
        this.fromPixels2DContext.fillStyle = params.gapFillWith;
        this.fromPixels2DContext.fillRect(0, 0, targetHeight, targetWidth);
        // 缩放后的宽高
        let sw = targetWidth;
        let sh = targetHeight;
        let x = 0;
        let y = 0;
        // target的长宽比大些 就把原图的高变成target那么高
        if (targetWidth / targetHeight * this.pixelHeight / this.pixelWidth >= 1) {
            sw = Math.round(sh * this.pixelWidth / this.pixelHeight);
            x = Math.floor((targetWidth - sw) / 2);
        }
        // target的长宽比小些 就把原图的宽变成target那么宽
        else {
            sh = Math.round(sw * this.pixelHeight / this.pixelWidth);
            y = Math.floor((targetHeight - sh) / 2);
        }
        if (center) {
            this.fromPixels2DContext.drawImage(
                image, x, y, sw, sh);
        }
        else {
            this.fromPixels2DContext.drawImage(
                image, 0, 0, sw, sh);
            // currentPic = this.fromPixels2DContext.canvas.toDataURL();
        }
        this.setInputCanvas(image);
        // window.currentPic = this.fromPixels2DContext.canvas;// test only, demele me
        // document.getElementById('p-c').appendChild(this.fromPixels2DContext.canvas);// test only, demele me
        return {sw: targetWidth, sh: targetHeight};
    }

    /**
     * 设置原始video画布
     * @param image 原始video
     */
    setInputCanvas(image) {
        // 原始图片宽高
        const width = this.pixelWidth;
        const height = this.pixelHeight;
        // 画布设置
        this.fromPixels2DContext2.canvas.width = width;
        this.fromPixels2DContext2.canvas.height = height;
        this.fromPixels2DContext2.drawImage(image, 0, 0, width, height);
    }

    /**
     * 获取图像内容
     * @param pixels
     * @returns {Uint8ClampedArray}
     */
W
wangqun 已提交
287 288
    getImageData(pixels, x, y, scaleSize) {

W
wangqun 已提交
289 290 291
        const {sw, sh} = scaleSize;
        // 复制画布上指定矩形的像素数据
        let vals = this.fromPixels2DContext
W
wangqun 已提交
292
            .getImageData(x, y, sw, sh);
W
wangqun 已提交
293 294 295
        // crop图像
        // const width = pixels.width;
        // const height = pixels.height;
W
wangqun 已提交
296

W
wangqun 已提交
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
        return vals;
    };

    /**
     * 计算灰度图
     * @param imageData
     * @returns {*}
     */
    grayscale (imageData) {
        let data = imageData.data;

        for (let i = 0; i < data.length; i += 4) {
            // 3 channel 灰度处理无空间压缩
            let avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
            data[i] = avg; // red
            data[i + 1] = avg; // green
            data[i + 2] = avg; // blue
        }
        return data;
    };

    fromPixels(pixels, opt) {
        let data;
        // 原始video画布数据
        let data2;
        let scaleSize;
        if (pixels instanceof HTMLImageElement || pixels instanceof HTMLVideoElement) {
324 325
            this.pixelWidth = pixels.naturalWidth || pixels.videoWidth ||  pixels.width;
            this.pixelHeight = pixels.naturalHeight || pixels.videoWidth ||  pixels.height;
W
wangqun 已提交
326 327 328 329
            if (opt.scale && opt.targetSize){ // Moblienet的情况
                data = this.resizeAndFitTargetSize(pixels, opt);
                data2 = this.fromPixels2DContext2.getImageData(0, 0, this.pixelWidth, this.pixelHeight);
            }
330
            else if (opt.scale) { // 直接resize到targetShape Humanseg的情况
W
wangqun 已提交
331
                scaleSize = this.reSize(pixels, opt);
W
wangqun 已提交
332
                data = this.getImageData(opt, 0, 0, scaleSize);
W
wangqun 已提交
333 334
                data2 = this.fromPixels2DContext2.getImageData(0, 0, this.pixelWidth, this.pixelHeight);
            }
W
wangqun 已提交
335
            else if (opt.targetSize) { // 如果有targetSize,就是装在目标宽高里的模式 TinyYolo的情况
W
wangqun 已提交
336
                scaleSize = this.fitToTargetSize(pixels, opt);
W
wangqun 已提交
337
                data = this.getImageData(opt, 0, 0, scaleSize);
W
wangqun 已提交
338 339 340 341 342 343 344 345 346 347 348 349
                data2 = this.fromPixels2DContext2.getImageData(0, 0, this.pixelWidth, this.pixelHeight);
            }
        }

        if (opt.gray) {
            data = grayscale(data);
        }

        if (opt.reShape) {
            data = this.reshape(data, opt, scaleSize);
        }

W
wangqun 已提交
350 351 352 353
        if (opt.bgr) {
            data = this.allReshapeToBGR(data, opt, scaleSize);
        }
        else if (opt.targetShape) {
W
wangqun 已提交
354 355
            data = this.allReshapeToRGB(data, opt, scaleSize);
        }
356

W
wangqun 已提交
357 358 359 360
        return [{data: data, shape: opt.shape || opt.targetShape, name: 'image', canvas: data2}];
    }
}
/* eslint-enable */