ImageFeed.es6 10.5 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 84 85 86
            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
     * @param shape
     */
    allReshapeToRGB(imageData, opt, scaleSize) {
W
wangqun 已提交
87
        //const {sw, sh} = scaleSize;
W
wangqun 已提交
88 89
        const [b, c, h, w] = opt.targetShape;
        let data = imageData.data || imageData;
W
wangqun 已提交
90
        // mean和std是介于0-1之间的
W
wangqun 已提交
91
        let mean = opt.mean;
W
wangqun 已提交
92
        let std = opt.std;
W
wangqun 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        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 + k;
W
wangqun 已提交
108 109 110 111
                    result[offset] = data[a] / 255;
                    result[offset] -= mean[k];
                    result[offset] /= std[k];
                    offset++;
W
wangqun 已提交
112 113 114
                }
            }
        }
W
wangqun 已提交
115
        
W
wangqun 已提交
116 117 118 119 120 121 122 123 124 125
        return result;
    };

    /**
     * 根据scale缩放图像
     * @param image
     * @param params
     * @return {Object} 缩放后的尺寸
     */
    reSize(image, params) {
W
wangqun 已提交
126
        console.log('execute resize!!');
W
wangqun 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        // 原始图片宽高
        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);
        }
        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 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
    /**
     * 根据scale缩放图像并且缩放成目标尺寸并居中
     */
    resizeAndFitTargetSize(image, params){
        console.log('execute resizeAndFitTargetSize!!');
        // 原始图片宽高
        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 已提交
167

W
wangqun 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181
        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 已提交
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

    /**
     * 缩放成目标尺寸并居中
     */
    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);
        }
        // console.log(x, y, sw, sh);
        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 已提交
244 245
    getImageData(pixels, x, y, scaleSize) {

W
wangqun 已提交
246 247 248
        const {sw, sh} = scaleSize;
        // 复制画布上指定矩形的像素数据
        let vals = this.fromPixels2DContext
W
wangqun 已提交
249
            .getImageData(x, y, sw, sh);
W
wangqun 已提交
250 251 252
        // crop图像
        // const width = pixels.width;
        // const height = pixels.height;
W
wangqun 已提交
253

W
wangqun 已提交
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
        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) {
            this.pixelWidth = pixels.naturalWidth || pixels.width;
            this.pixelHeight = pixels.naturalHeight || pixels.height;
W
wangqun 已提交
283 284 285 286 287 288
            if (opt.scale && opt.targetSize){ // Moblienet的情况
                data = this.resizeAndFitTargetSize(pixels, opt);
                data2 = this.fromPixels2DContext2.getImageData(0, 0, this.pixelWidth, this.pixelHeight);
            }
            else if (opt.scale) { // 兼容以前的,如果有scale就是短边缩放到scale模式

W
wangqun 已提交
289
                scaleSize = this.reSize(pixels, opt);
W
wangqun 已提交
290 291 292
                console.dir(scaleSize);
                console.dir(pixels);
                data = this.getImageData(opt, 0, 0, scaleSize);
W
wangqun 已提交
293 294
                data2 = this.fromPixels2DContext2.getImageData(0, 0, this.pixelWidth, this.pixelHeight);
            }
W
wangqun 已提交
295 296
            else if (opt.targetSize) { // 如果有targetSize,就是装在目标宽高里的模式 TinyYolo的情况

W
wangqun 已提交
297
                scaleSize = this.fitToTargetSize(pixels, opt);
W
wangqun 已提交
298
                data = this.getImageData(opt, 0, 0, scaleSize);
W
wangqun 已提交
299 300 301 302
                data2 = this.fromPixels2DContext2.getImageData(0, 0, this.pixelWidth, this.pixelHeight);
            }
        }

W
wangqun 已提交
303

W
wangqun 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
        if (opt.gray) {
            data = grayscale(data);
        }

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

        if (opt.targetShape) {
            data = this.allReshapeToRGB(data, opt, scaleSize);
        }
        return [{data: data, shape: opt.shape || opt.targetShape, name: 'image', canvas: data2}];
    }
}
/* eslint-enable */