UNPKG

17.4 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright 2019 Google LLC. All Rights Reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 * =============================================================================
17 */
18var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19 return new (P || (P = Promise))(function (resolve, reject) {
20 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
23 step((generator = generator.apply(thisArg, _arguments || [])).next());
24 });
25};
26var __generator = (this && this.__generator) || function (thisArg, body) {
27 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29 function verb(n) { return function (v) { return step([n, v]); }; }
30 function step(op) {
31 if (f) throw new TypeError("Generator is already executing.");
32 while (_) try {
33 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
34 if (y = 0, t) op = [op[0] & 2, t.value];
35 switch (op[0]) {
36 case 0: case 1: t = op; break;
37 case 4: _.label++; return { value: op[1], done: false };
38 case 5: _.label++; y = op[1]; op = [0]; continue;
39 case 7: op = _.ops.pop(); _.trys.pop(); continue;
40 default:
41 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45 if (t[2]) _.ops.pop();
46 _.trys.pop(); continue;
47 }
48 op = body.call(thisArg, _);
49 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51 }
52};
53Object.defineProperty(exports, "__esModule", { value: true });
54var tfjs_1 = require("@tensorflow/tfjs");
55var nodejs_kernel_backend_1 = require("./nodejs_kernel_backend");
56var ImageType;
57(function (ImageType) {
58 ImageType["JPEG"] = "jpeg";
59 ImageType["PNG"] = "png";
60 ImageType["GIF"] = "gif";
61 ImageType["BMP"] = "BMP";
62})(ImageType = exports.ImageType || (exports.ImageType = {}));
63/**
64 * Decode a JPEG-encoded image to a 3D Tensor of dtype `int32`.
65 *
66 * @param contents The JPEG-encoded image in an Uint8Array.
67 * @param channels An optional int. Defaults to 0. Accepted values are
68 * 0: use the number of channels in the JPEG-encoded image.
69 * 1: output a grayscale image.
70 * 3: output an RGB image.
71 * @param ratio An optional int. Defaults to 1. Downscaling ratio. It is used
72 * when image is type Jpeg.
73 * @param fancyUpscaling An optional bool. Defaults to True. If true use a
74 * slower but nicer upscaling of the chroma planes. It is used when image is
75 * type Jpeg.
76 * @param tryRecoverTruncated An optional bool. Defaults to False. If true try
77 * to recover an image from truncated input. It is used when image is type
78 * Jpeg.
79 * @param acceptableFraction An optional float. Defaults to 1. The minimum
80 * required fraction of lines before a truncated input is accepted. It is
81 * used when image is type Jpeg.
82 * @param dctMethod An optional string. Defaults to "". string specifying a hint
83 * about the algorithm used for decompression. Defaults to "" which maps to
84 * a system-specific default. Currently valid values are ["INTEGER_FAST",
85 * "INTEGER_ACCURATE"]. The hint may be ignored (e.g., the internal jpeg
86 * library changes to a version that does not have that specific option.) It
87 * is used when image is type Jpeg.
88 * @returns A 3D Tensor of dtype `int32` with shape [height, width, 1/3].
89 *
90 * @doc {heading: 'Operations', subheading: 'Images', namespace: 'node'}
91 */
92function decodeJpeg(contents, channels, ratio, fancyUpscaling, tryRecoverTruncated, acceptableFraction, dctMethod) {
93 if (channels === void 0) { channels = 0; }
94 if (ratio === void 0) { ratio = 1; }
95 if (fancyUpscaling === void 0) { fancyUpscaling = true; }
96 if (tryRecoverTruncated === void 0) { tryRecoverTruncated = false; }
97 if (acceptableFraction === void 0) { acceptableFraction = 1; }
98 if (dctMethod === void 0) { dctMethod = ''; }
99 nodejs_kernel_backend_1.ensureTensorflowBackend();
100 return tfjs_1.tidy(function () {
101 return nodejs_kernel_backend_1.nodeBackend()
102 .decodeJpeg(contents, channels, ratio, fancyUpscaling, tryRecoverTruncated, acceptableFraction, dctMethod)
103 .toInt();
104 });
105}
106exports.decodeJpeg = decodeJpeg;
107/**
108 * Decode a PNG-encoded image to a 3D Tensor of dtype `int32`.
109 *
110 * @param contents The PNG-encoded image in an Uint8Array.
111 * @param channels An optional int. Defaults to 0. Accepted values are
112 * 0: use the number of channels in the PNG-encoded image.
113 * 1: output a grayscale image.
114 * 3: output an RGB image.
115 * 4: output an RGBA image.
116 * @param dtype The data type of the result. Only `int32` is supported at this
117 * time.
118 * @returns A 3D Tensor of dtype `int32` with shape [height, width, 1/3/4].
119 *
120 * @doc {heading: 'Operations', subheading: 'Images', namespace: 'node'}
121 */
122function decodePng(contents, channels, dtype) {
123 if (channels === void 0) { channels = 0; }
124 if (dtype === void 0) { dtype = 'int32'; }
125 tfjs_1.util.assert(dtype === 'int32', function () { return 'decodeImage could only return Tensor of type `int32` for now.'; });
126 nodejs_kernel_backend_1.ensureTensorflowBackend();
127 return tfjs_1.tidy(function () {
128 return nodejs_kernel_backend_1.nodeBackend().decodePng(contents, channels).toInt();
129 });
130}
131exports.decodePng = decodePng;
132/**
133 * Decode the first frame of a BMP-encoded image to a 3D Tensor of dtype
134 * `int32`.
135 *
136 * @param contents The BMP-encoded image in an Uint8Array.
137 * @param channels An optional int. Defaults to 0. Accepted values are
138 * 0: use the number of channels in the BMP-encoded image.
139 * 3: output an RGB image.
140 * 4: output an RGBA image.
141 * @returns A 3D Tensor of dtype `int32` with shape [height, width, 3/4].
142 *
143 * @doc {heading: 'Operations', subheading: 'Images', namespace: 'node'}
144 */
145function decodeBmp(contents, channels) {
146 if (channels === void 0) { channels = 0; }
147 nodejs_kernel_backend_1.ensureTensorflowBackend();
148 return tfjs_1.tidy(function () {
149 return nodejs_kernel_backend_1.nodeBackend().decodeBmp(contents, channels).toInt();
150 });
151}
152exports.decodeBmp = decodeBmp;
153/**
154 * Decode the frame(s) of a GIF-encoded image to a 4D Tensor of dtype `int32`.
155 *
156 * @param contents The GIF-encoded image in an Uint8Array.
157 * @returns A 4D Tensor of dtype `int32` with shape [num_frames, height, width,
158 * 3]. RGB channel order.
159 *
160 * @doc {heading: 'Operations', subheading: 'Images', namespace: 'node'}
161 */
162function decodeGif(contents) {
163 nodejs_kernel_backend_1.ensureTensorflowBackend();
164 return tfjs_1.tidy(function () {
165 return nodejs_kernel_backend_1.nodeBackend().decodeGif(contents).toInt();
166 });
167}
168exports.decodeGif = decodeGif;
169/**
170 * Given the encoded bytes of an image, it returns a 3D or 4D tensor of the
171 * decoded image. Supports BMP, GIF, JPEG and PNG formats.
172 *
173 * @param content The encoded image in an Uint8Array.
174 * @param channels An optional int. Defaults to 0, use the number of channels in
175 * the image. Number of color channels for the decoded image. It is used
176 * when image is type Png, Bmp, or Jpeg.
177 * @param dtype The data type of the result. Only `int32` is supported at this
178 * time.
179 * @param expandAnimations A boolean which controls the shape of the returned
180 * op's output. If True, the returned op will produce a 3-D tensor for PNG,
181 * JPEG, and BMP files; and a 4-D tensor for all GIFs, whether animated or
182 * not. If, False, the returned op will produce a 3-D tensor for all file
183 * types and will truncate animated GIFs to the first frame.
184 * @returns A Tensor with dtype `int32` and a 3- or 4-dimensional shape,
185 * depending on the file type. For gif file the returned Tensor shape is
186 * [num_frames, height, width, 3], and for jpeg/png/bmp the returned Tensor
187 * shape is [height, width, channels]
188 *
189 * @doc {heading: 'Operations', subheading: 'Images', namespace: 'node'}
190 */
191function decodeImage(content, channels, dtype, expandAnimations) {
192 if (channels === void 0) { channels = 0; }
193 if (dtype === void 0) { dtype = 'int32'; }
194 if (expandAnimations === void 0) { expandAnimations = true; }
195 tfjs_1.util.assert(dtype === 'int32', function () { return 'decodeImage could only return Tensor of type `int32` for now.'; });
196 var imageType = getImageType(content);
197 // The return tensor has dtype uint8, which is not supported in
198 // TensorFlow.js, casting it to int32 which is the default dtype for image
199 // tensor. If the image is BMP, JPEG or PNG type, expanding the tensors
200 // shape so it becomes Tensor4D, which is the default tensor shape for image
201 // ([batch,imageHeight,imageWidth, depth]).
202 switch (imageType) {
203 case ImageType.JPEG:
204 return decodeJpeg(content, channels);
205 case ImageType.PNG:
206 return decodePng(content, channels);
207 case ImageType.GIF:
208 // If not to expand animations, take first frame of the gif and return
209 // as a 3D tensor.
210 return tfjs_1.tidy(function () {
211 var img = decodeGif(content);
212 return expandAnimations ? img : img.slice(0, 1).squeeze([0]);
213 });
214 case ImageType.BMP:
215 return decodeBmp(content, channels);
216 default:
217 return null;
218 }
219}
220exports.decodeImage = decodeImage;
221/**
222 * Encodes an image tensor to JPEG.
223 *
224 * @param image A 3-D uint8 Tensor of shape [height, width, channels].
225 * @param format An optional string from: "", "grayscale", "rgb".
226 * Defaults to "". Per pixel image format.
227 * - '': Use a default format based on the number of channels in the image.
228 * - grayscale: Output a grayscale JPEG image. The channels dimension of
229 * image must be 1.
230 * - rgb: Output an RGB JPEG image. The channels dimension of image must
231 * be 3.
232 * @param quality An optional int. Defaults to 95. Quality of the compression
233 * from 0 to 100 (higher is better and slower).
234 * @param progressive An optional bool. Defaults to False. If True, create a
235 * JPEG that loads progressively (coarse to fine).
236 * @param optimizeSize An optional bool. Defaults to False. If True, spend
237 * CPU/RAM to reduce size with no quality change.
238 * @param chromaDownsampling An optional bool. Defaults to True.
239 * See http://en.wikipedia.org/wiki/Chroma_subsampling.
240 * @param densityUnit An optional string from: "in", "cm". Defaults to "in".
241 * Unit used to specify x_density and y_density: pixels per inch ('in') or
242 * centimeter ('cm').
243 * @param xDensity An optional int. Defaults to 300. Horizontal pixels per
244 * density unit.
245 * @param yDensity An optional int. Defaults to 300. Vertical pixels per
246 * density unit.
247 * @param xmpMetadata An optional string. Defaults to "". If not empty, embed
248 * this XMP metadata in the image header.
249 * @returns The JPEG encoded data as an Uint8Array.
250 *
251 * @doc {heading: 'Operations', subheading: 'Images', namespace: 'node'}
252 */
253function encodeJpeg(image, format, quality, progressive, optimizeSize, chromaDownsampling, densityUnit, xDensity, yDensity, xmpMetadata) {
254 if (format === void 0) { format = ''; }
255 if (quality === void 0) { quality = 95; }
256 if (progressive === void 0) { progressive = false; }
257 if (optimizeSize === void 0) { optimizeSize = false; }
258 if (chromaDownsampling === void 0) { chromaDownsampling = true; }
259 if (densityUnit === void 0) { densityUnit = 'in'; }
260 if (xDensity === void 0) { xDensity = 300; }
261 if (yDensity === void 0) { yDensity = 300; }
262 if (xmpMetadata === void 0) { xmpMetadata = ''; }
263 return __awaiter(this, void 0, void 0, function () {
264 var backendEncodeImage;
265 return __generator(this, function (_a) {
266 nodejs_kernel_backend_1.ensureTensorflowBackend();
267 backendEncodeImage = function (imageData) {
268 return nodejs_kernel_backend_1.nodeBackend().encodeJpeg(imageData, image.shape, format, quality, progressive, optimizeSize, chromaDownsampling, densityUnit, xDensity, yDensity, xmpMetadata);
269 };
270 return [2 /*return*/, encodeImage(image, backendEncodeImage)];
271 });
272 });
273}
274exports.encodeJpeg = encodeJpeg;
275/**
276 * Encodes an image tensor to PNG.
277 *
278 * @param image A 3-D uint8 Tensor of shape [height, width, channels].
279 * @param compression An optional int. Defaults to 1. Compression level.
280 * @returns The PNG encoded data as an Uint8Array.
281 *
282 * @doc {heading: 'Operations', subheading: 'Images', namespace: 'node'}
283 */
284function encodePng(image, compression) {
285 if (compression === void 0) { compression = 1; }
286 return __awaiter(this, void 0, void 0, function () {
287 var backendEncodeImage;
288 return __generator(this, function (_a) {
289 nodejs_kernel_backend_1.ensureTensorflowBackend();
290 backendEncodeImage = function (imageData) {
291 return nodejs_kernel_backend_1.nodeBackend().encodePng(imageData, image.shape, compression);
292 };
293 return [2 /*return*/, encodeImage(image, backendEncodeImage)];
294 });
295 });
296}
297exports.encodePng = encodePng;
298function encodeImage(image, backendEncodeImage) {
299 return __awaiter(this, void 0, void 0, function () {
300 var encodedDataTensor, _a, _b, encodedPngData;
301 return __generator(this, function (_c) {
302 switch (_c.label) {
303 case 0:
304 _a = backendEncodeImage;
305 _b = Uint8Array.bind;
306 return [4 /*yield*/, image.data()];
307 case 1:
308 encodedDataTensor = _a.apply(void 0, [new (_b.apply(Uint8Array, [void 0, _c.sent()]))()]);
309 // tslint:disable-next-line:no-any
310 return [4 /*yield*/, encodedDataTensor.data()];
311 case 2:
312 encodedPngData = (
313 // tslint:disable-next-line:no-any
314 _c.sent())[0];
315 encodedDataTensor.dispose();
316 return [2 /*return*/, encodedPngData];
317 }
318 });
319 });
320}
321/**
322 * Helper function to get image type based on starting bytes of the image file.
323 */
324function getImageType(content) {
325 // Classify the contents of a file based on starting bytes (aka magic number:
326 // https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files)
327 // This aligns with TensorFlow Core code:
328 // https://github.com/tensorflow/tensorflow/blob/4213d5c1bd921f8d5b7b2dc4bbf1eea78d0b5258/tensorflow/core/kernels/decode_image_op.cc#L44
329 if (content.length > 3 && content[0] === 255 && content[1] === 216 &&
330 content[2] === 255) {
331 // JPEG byte chunk starts with `ff d8 ff`
332 return ImageType.JPEG;
333 }
334 else if (content.length > 4 && content[0] === 71 && content[1] === 73 &&
335 content[2] === 70 && content[3] === 56) {
336 // GIF byte chunk starts with `47 49 46 38`
337 return ImageType.GIF;
338 }
339 else if (content.length > 8 && content[0] === 137 && content[1] === 80 &&
340 content[2] === 78 && content[3] === 71 && content[4] === 13 &&
341 content[5] === 10 && content[6] === 26 && content[7] === 10) {
342 // PNG byte chunk starts with `\211 P N G \r \n \032 \n (89 50 4E 47 0D 0A
343 // 1A 0A)`
344 return ImageType.PNG;
345 }
346 else if (content.length > 3 && content[0] === 66 && content[1] === 77) {
347 // BMP byte chunk starts with `42 4d`
348 return ImageType.BMP;
349 }
350 else {
351 throw new Error('Expected image (BMP, JPEG, PNG, or GIF), but got unsupported ' +
352 'image type');
353 }
354}
355exports.getImageType = getImageType;