File: js_style_transfer.html

package info (click to toggle)
opencv 4.6.0%2Bdfsg-12
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 276,172 kB
  • sloc: cpp: 1,079,020; xml: 682,526; python: 43,885; lisp: 30,943; java: 25,642; ansic: 7,968; javascript: 5,956; objc: 2,039; sh: 1,017; cs: 601; perl: 494; makefile: 179
file content (228 lines) | stat: -rw-r--r-- 7,890 bytes parent folder | download | duplicates (3)
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
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Style Transfer Example</title>
    <link href="js_example_style.css" rel="stylesheet" type="text/css" />
</head>

<body>
<h2>Style Transfer Example</h2>
<p>
    This tutorial shows you how to write an style transfer example with OpenCV.js.<br>
    To try the example you should click the <b>modelFile</b> button(and <b>configFile</b> button if needed) to upload inference model.
    You can find the model URLs and parameters in the <a href="#appendix">model info</a> section.
    Then You should change the parameters in the first code snippet according to the uploaded model.
    Finally click <b>Try it</b> button to see the result. You can choose any other images.<br>
</p>

<div class="control"><button id="tryIt" disabled>Try it</button></div>
<div>
    <table cellpadding="0" cellspacing="0" width="0" border="0">
        <tr>
            <td>
                <canvas id="canvasInput" width="400" height="400"></canvas>
            </td>
            <td>
                <canvas id="canvasOutput" style="visibility: hidden;" width="400" height="400"></canvas>
            </td>
        </tr>
        <tr>
            <td>
                <div class="caption">
                    canvasInput <input type="file" id="fileInput" name="file" accept="image/*">
                </div>
            </td>
            <td>
                <p id='status' align="left"></p>
            </td>
        </tr>
        <tr>
            <td>
                <div class="caption">
                    modelFile <input type="file" id="modelFile" name="file">
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <div class="caption">
                    configFile <input type="file" id="configFile">
                </div>
            </td>
        </tr>
    </table>
</div>

<div>
    <p class="err" id="errorMessage"></p>
</div>

<div>
    <h3>Help function</h3>
    <p>1.The parameters for model inference which you can modify to investigate more models.</p>
    <textarea class="code" rows="5" cols="100" id="codeEditor" spellcheck="false"></textarea>
    <p>2.Main loop in which will read the image from canvas and do inference once.</p>
    <textarea class="code" rows="15" cols="100" id="codeEditor1" spellcheck="false"></textarea>
    <p>3.Get blob from image as input for net, and standardize it with <b>mean</b> and <b>std</b>.</p>
    <textarea class="code" rows="17" cols="100" id="codeEditor2" spellcheck="false"></textarea>
    <p>4.Fetch model file and save to emscripten file system once click the input button.</p>
    <textarea class="code" rows="17" cols="100" id="codeEditor3" spellcheck="false"></textarea>
    <p>5.The post-processing, including scaling and reordering.</p>
    <textarea class="code" rows="21" cols="100" id="codeEditor4" spellcheck="false"></textarea>
</div>

<div id="appendix">
    <h2>Model Info:</h2>
</div>

<script src="utils.js" type="text/javascript"></script>
<script src="js_dnn_example_helper.js" type="text/javascript"></script>

<script id="codeSnippet" type="text/code-snippet">
inputSize = [224, 224];
mean = [104, 117, 123];
std = 1;
swapRB = false;
</script>

<script id="codeSnippet1" type="text/code-snippet">
main = async function() {
    const input = getBlobFromImage(inputSize, mean, std, swapRB, 'canvasInput');
    let net = cv.readNet(configPath, modelPath);
    net.setInput(input);
    const start = performance.now();
    const result = net.forward();
    const time  = performance.now()-start;
    const output = postProcess(result);

    updateResult(output, time);
    input.delete();
    net.delete();
    result.delete();
}
</script>

<script id="codeSnippet4" type="text/code-snippet">
postProcess = function(result) {
    const resultData = result.data32F;
    const C = result.matSize[1];
    const H = result.matSize[2];
    const W = result.matSize[3];
    const mean = [104, 117, 123];

    let normData = [];
    for (let h = 0; h < H; ++h) {
        for (let w = 0; w < W; ++w) {
            for (let c = 0; c < C; ++c) {
                normData.push(resultData[c*H*W + h*W + w] + mean[c]);
            }
            normData.push(255);
        }
    }

    let output = new cv.matFromArray(H, W, cv.CV_8UC4, normData);
    return output;
}
</script>

<script type="text/javascript">
    let jsonUrl = "js_style_transfer_model_info.json";
    drawInfoTable(jsonUrl, 'appendix');

    let utils = new Utils('errorMessage');
    utils.loadCode('codeSnippet', 'codeEditor');
    utils.loadCode('codeSnippet1', 'codeEditor1');

    let getBlobFromImageCode = 'getBlobFromImage = ' + getBlobFromImage.toString();
    document.getElementById('codeEditor2').value = getBlobFromImageCode;
    let loadModelCode = 'loadModel = ' + loadModel.toString();
    document.getElementById('codeEditor3').value = loadModelCode;

    utils.loadCode('codeSnippet4', 'codeEditor4');

    let canvas = document.getElementById('canvasInput');
    let ctx = canvas.getContext('2d');
    let img = new Image();
    img.crossOrigin = 'anonymous';
    img.src = 'lena.png';
    img.onload = function() {
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    };

    let tryIt = document.getElementById('tryIt');
    tryIt.addEventListener('click', () => {
        initStatus();
        document.getElementById('status').innerHTML = 'Running function main()...';
        utils.executeCode('codeEditor');
        utils.executeCode('codeEditor1');
        if (modelPath === "") {
            document.getElementById('status').innerHTML = 'Runing failed.';
            utils.printError('Please upload model file by clicking the button first.');
        } else {
            setTimeout(main, 1);
        }
    });

    let fileInput = document.getElementById('fileInput');
    fileInput.addEventListener('change', (e) => {
        initStatus();
        loadImageToCanvas(e, 'canvasInput');
    });

    let configPath = "";
    let configFile = document.getElementById('configFile');
    configFile.addEventListener('change', async (e) => {
        initStatus();
        configPath = await loadModel(e);
        document.getElementById('status').innerHTML = `The config file '${configPath}' is created successfully.`;
    });

    let modelPath = "";
    let modelFile = document.getElementById('modelFile');
    modelFile.addEventListener('change', async (e) => {
        initStatus();
        modelPath = await loadModel(e);
        document.getElementById('status').innerHTML = `The model file '${modelPath}' is created successfully.`;
        configPath = "";
        configFile.value = "";
    });

    utils.loadOpenCv(() => {
        tryIt.removeAttribute('disabled');
    });

    var main = async function() {};
    var postProcess = function(result) {};

    utils.executeCode('codeEditor1');
    utils.executeCode('codeEditor2');
    utils.executeCode('codeEditor3');
    utils.executeCode('codeEditor4');

    function updateResult(output, time) {
        try{
            let canvasOutput = document.getElementById('canvasOutput');
            canvasOutput.style.visibility = "visible";
            let resized = new cv.Mat(canvasOutput.width, canvasOutput.height, cv.CV_8UC4);
            cv.resize(output, resized, new cv.Size(canvasOutput.width, canvasOutput.height));
            cv.imshow('canvasOutput', resized);
            document.getElementById('status').innerHTML = `<b>Model:</b> ${modelPath}<br>
                                                           <b>Inference time:</b> ${time.toFixed(2)} ms`;
        } catch(e) {
            console.log(e);
        }
    }

    function initStatus() {
        document.getElementById('status').innerHTML = '';
        document.getElementById('canvasOutput').style.visibility = "hidden";
        utils.clearError();
    }

</script>

</body>

</html>