@huggingface/transformers 3.0.2 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -4
- package/dist/ort-wasm-simd-threaded.jsep.wasm +0 -0
- package/dist/transformers.cjs +16655 -13040
- package/dist/transformers.cjs.map +1 -1
- package/dist/transformers.js +17095 -13468
- package/dist/transformers.js.map +1 -1
- package/dist/transformers.min.cjs +244 -52
- package/dist/transformers.min.cjs.map +1 -1
- package/dist/transformers.min.js +235 -43
- package/dist/transformers.min.js.map +1 -1
- package/dist/transformers.min.mjs +246 -54
- package/dist/transformers.min.mjs.map +1 -1
- package/dist/transformers.mjs +16818 -13202
- package/dist/transformers.mjs.map +1 -1
- package/package.json +4 -4
- package/src/base/feature_extraction_utils.js +54 -0
- package/src/base/image_processors_utils.js +1089 -0
- package/src/base/processing_utils.js +145 -0
- package/src/configs.js +15 -4
- package/src/env.js +6 -6
- package/src/generation/configuration_utils.js +7 -0
- package/src/generation/logits_process.js +22 -16
- package/src/generation/streamers.js +7 -2
- package/src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js +90 -0
- package/src/models/auto/feature_extraction_auto.js +41 -0
- package/src/models/auto/image_processing_auto.js +29 -0
- package/src/models/auto/processing_auto.js +100 -0
- package/src/models/beit/image_processing_beit.js +5 -0
- package/src/models/bit/image_processing_bit.js +5 -0
- package/src/models/chinese_clip/image_processing_chinese_clip.js +5 -0
- package/src/models/clap/feature_extraction_clap.js +159 -0
- package/src/models/clip/image_processing_clip.js +6 -0
- package/src/models/convnext/image_processing_convnext.js +45 -0
- package/src/models/deit/image_processing_deit.js +6 -0
- package/src/models/detr/image_processing_detr.js +52 -0
- package/src/models/donut/image_processing_donut.js +31 -0
- package/src/models/dpt/image_processing_dpt.js +6 -0
- package/src/models/efficientnet/image_processing_efficientnet.js +13 -0
- package/src/models/feature_extractors.js +12 -0
- package/src/models/florence2/processing_florence2.js +128 -0
- package/src/models/glpn/image_processing_glpn.js +5 -0
- package/src/models/idefics3/image_processing_idefics3.js +219 -0
- package/src/models/idefics3/processing_idefics3.js +136 -0
- package/src/models/image_processors.js +37 -0
- package/src/models/janus/image_processing_janus.js +26 -0
- package/src/models/janus/processing_janus.js +123 -0
- package/src/models/jina_clip/image_processing_jina_clip.js +26 -0
- package/src/models/jina_clip/processing_jina_clip.js +24 -0
- package/src/models/llava_onevision/image_processing_llava_onevision.js +5 -0
- package/src/models/mask2former/image_processing_mask2former.js +5 -0
- package/src/models/maskformer/image_processing_maskformer.js +18 -0
- package/src/models/mgp_str/processing_mgp_str.js +170 -0
- package/src/models/mobilenet_v1/image_processing_mobilenet_v1.js +7 -0
- package/src/models/mobilenet_v2/image_processing_mobilenet_v2.js +7 -0
- package/src/models/mobilenet_v3/image_processing_mobilenet_v3.js +7 -0
- package/src/models/mobilenet_v4/image_processing_mobilenet_v4.js +7 -0
- package/src/models/mobilevit/image_processing_mobilevit.js +6 -0
- package/src/models/nougat/image_processing_nougat.js +5 -0
- package/src/models/owlv2/image_processing_owlv2.js +5 -0
- package/src/models/owlvit/image_processing_owlvit.js +12 -0
- package/src/models/owlvit/processing_owlvit.js +7 -0
- package/src/models/processors.js +12 -0
- package/src/models/pvt/image_processing_pvt.js +5 -0
- package/src/models/pyannote/feature_extraction_pyannote.js +28 -0
- package/src/models/pyannote/processing_pyannote.js +71 -0
- package/src/models/qwen2_vl/image_processing_qwen2_vl.js +52 -0
- package/src/models/qwen2_vl/processing_qwen2_vl.js +52 -0
- package/src/models/rt_detr/image_processing_rt_detr.js +12 -0
- package/src/models/sam/image_processing_sam.js +242 -0
- package/src/models/sam/processing_sam.js +20 -0
- package/src/models/sapiens/image_processing_sapiens.js +13 -0
- package/src/models/seamless_m4t/feature_extraction_seamless_m4t.js +180 -0
- package/src/models/segformer/image_processing_segformer.js +13 -0
- package/src/models/siglip/image_processing_siglip.js +5 -0
- package/src/models/speecht5/feature_extraction_speecht5.js +4 -0
- package/src/models/speecht5/processing_speecht5.js +17 -0
- package/src/models/swin2sr/image_processing_swin2sr.js +24 -0
- package/src/models/vit/image_processing_vit.js +7 -0
- package/src/models/vitmatte/image_processing_vitmatte.js +50 -0
- package/src/models/vitpose/image_processing_vitpose.js +89 -0
- package/src/models/wav2vec2/feature_extraction_wav2vec2.js +44 -0
- package/src/models/wav2vec2/processing_wav2vec2.js +15 -0
- package/src/models/wespeaker/feature_extraction_wespeaker.js +100 -0
- package/src/models/whisper/feature_extraction_whisper.js +84 -0
- package/src/models/whisper/processing_whisper.js +21 -0
- package/src/models/yolos/image_processing_yolos.js +12 -0
- package/src/models.js +755 -34
- package/src/pipelines.js +8 -8
- package/src/tokenizers.js +5 -0
- package/src/transformers.js +15 -2
- package/src/utils/constants.js +8 -1
- package/src/utils/core.js +51 -9
- package/src/utils/dtypes.js +2 -1
- package/src/utils/hub.js +2 -1
- package/src/utils/image.js +87 -33
- package/src/utils/tensor.js +39 -2
- package/types/base/feature_extraction_utils.d.ts +41 -0
- package/types/base/feature_extraction_utils.d.ts.map +1 -0
- package/types/base/image_processors_utils.d.ts +323 -0
- package/types/base/image_processors_utils.d.ts.map +1 -0
- package/types/base/processing_utils.d.ts +80 -0
- package/types/base/processing_utils.d.ts.map +1 -0
- package/types/configs.d.ts +5 -2
- package/types/configs.d.ts.map +1 -1
- package/types/env.d.ts +1 -1
- package/types/env.d.ts.map +1 -1
- package/types/generation/configuration_utils.d.ts +6 -0
- package/types/generation/configuration_utils.d.ts.map +1 -1
- package/types/generation/logits_process.d.ts +30 -20
- package/types/generation/logits_process.d.ts.map +1 -1
- package/types/generation/streamers.d.ts +13 -8
- package/types/generation/streamers.d.ts.map +1 -1
- package/types/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.d.ts +25 -0
- package/types/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.d.ts.map +1 -0
- package/types/models/auto/feature_extraction_auto.d.ts +5 -0
- package/types/models/auto/feature_extraction_auto.d.ts.map +1 -0
- package/types/models/auto/image_processing_auto.d.ts +5 -0
- package/types/models/auto/image_processing_auto.d.ts.map +1 -0
- package/types/models/auto/processing_auto.d.ts +35 -0
- package/types/models/auto/processing_auto.d.ts.map +1 -0
- package/types/models/beit/image_processing_beit.d.ts +4 -0
- package/types/models/beit/image_processing_beit.d.ts.map +1 -0
- package/types/models/bit/image_processing_bit.d.ts +4 -0
- package/types/models/bit/image_processing_bit.d.ts.map +1 -0
- package/types/models/chinese_clip/image_processing_chinese_clip.d.ts +4 -0
- package/types/models/chinese_clip/image_processing_chinese_clip.d.ts.map +1 -0
- package/types/models/clap/feature_extraction_clap.d.ts +57 -0
- package/types/models/clap/feature_extraction_clap.d.ts.map +1 -0
- package/types/models/clip/image_processing_clip.d.ts +6 -0
- package/types/models/clip/image_processing_clip.d.ts.map +1 -0
- package/types/models/convnext/image_processing_convnext.d.ts +12 -0
- package/types/models/convnext/image_processing_convnext.d.ts.map +1 -0
- package/types/models/deit/image_processing_deit.d.ts +6 -0
- package/types/models/deit/image_processing_deit.d.ts.map +1 -0
- package/types/models/detr/image_processing_detr.d.ts +42 -0
- package/types/models/detr/image_processing_detr.d.ts.map +1 -0
- package/types/models/donut/image_processing_donut.d.ts +7 -0
- package/types/models/donut/image_processing_donut.d.ts.map +1 -0
- package/types/models/dpt/image_processing_dpt.d.ts +6 -0
- package/types/models/dpt/image_processing_dpt.d.ts.map +1 -0
- package/types/models/efficientnet/image_processing_efficientnet.d.ts +6 -0
- package/types/models/efficientnet/image_processing_efficientnet.d.ts.map +1 -0
- package/types/models/feature_extractors.d.ts +10 -0
- package/types/models/feature_extractors.d.ts.map +1 -0
- package/types/models/florence2/processing_florence2.d.ts +39 -0
- package/types/models/florence2/processing_florence2.d.ts.map +1 -0
- package/types/models/glpn/image_processing_glpn.d.ts +4 -0
- package/types/models/glpn/image_processing_glpn.d.ts.map +1 -0
- package/types/models/idefics3/image_processing_idefics3.d.ts +40 -0
- package/types/models/idefics3/image_processing_idefics3.d.ts.map +1 -0
- package/types/models/idefics3/processing_idefics3.d.ts +19 -0
- package/types/models/idefics3/processing_idefics3.d.ts.map +1 -0
- package/types/models/image_processors.d.ts +37 -0
- package/types/models/image_processors.d.ts.map +1 -0
- package/types/models/janus/image_processing_janus.d.ts +7 -0
- package/types/models/janus/image_processing_janus.d.ts.map +1 -0
- package/types/models/janus/processing_janus.d.ts +77 -0
- package/types/models/janus/processing_janus.d.ts.map +1 -0
- package/types/models/jina_clip/image_processing_jina_clip.d.ts +5 -0
- package/types/models/jina_clip/image_processing_jina_clip.d.ts.map +1 -0
- package/types/models/jina_clip/processing_jina_clip.d.ts +9 -0
- package/types/models/jina_clip/processing_jina_clip.d.ts.map +1 -0
- package/types/models/llava_onevision/image_processing_llava_onevision.d.ts +4 -0
- package/types/models/llava_onevision/image_processing_llava_onevision.d.ts.map +1 -0
- package/types/models/mask2former/image_processing_mask2former.d.ts +4 -0
- package/types/models/mask2former/image_processing_mask2former.d.ts.map +1 -0
- package/types/models/maskformer/image_processing_maskformer.d.ts +22 -0
- package/types/models/maskformer/image_processing_maskformer.d.ts.map +1 -0
- package/types/models/mgp_str/processing_mgp_str.d.ts +64 -0
- package/types/models/mgp_str/processing_mgp_str.d.ts.map +1 -0
- package/types/models/mobilenet_v1/image_processing_mobilenet_v1.d.ts +6 -0
- package/types/models/mobilenet_v1/image_processing_mobilenet_v1.d.ts.map +1 -0
- package/types/models/mobilenet_v2/image_processing_mobilenet_v2.d.ts +6 -0
- package/types/models/mobilenet_v2/image_processing_mobilenet_v2.d.ts.map +1 -0
- package/types/models/mobilenet_v3/image_processing_mobilenet_v3.d.ts +6 -0
- package/types/models/mobilenet_v3/image_processing_mobilenet_v3.d.ts.map +1 -0
- package/types/models/mobilenet_v4/image_processing_mobilenet_v4.d.ts +6 -0
- package/types/models/mobilenet_v4/image_processing_mobilenet_v4.d.ts.map +1 -0
- package/types/models/mobilevit/image_processing_mobilevit.d.ts +6 -0
- package/types/models/mobilevit/image_processing_mobilevit.d.ts.map +1 -0
- package/types/models/nougat/image_processing_nougat.d.ts +4 -0
- package/types/models/nougat/image_processing_nougat.d.ts.map +1 -0
- package/types/models/owlv2/image_processing_owlv2.d.ts +4 -0
- package/types/models/owlv2/image_processing_owlv2.d.ts.map +1 -0
- package/types/models/owlvit/image_processing_owlvit.d.ts +10 -0
- package/types/models/owlvit/image_processing_owlvit.d.ts.map +1 -0
- package/types/models/owlvit/processing_owlvit.d.ts +8 -0
- package/types/models/owlvit/processing_owlvit.d.ts.map +1 -0
- package/types/models/processors.d.ts +13 -0
- package/types/models/processors.d.ts.map +1 -0
- package/types/models/pvt/image_processing_pvt.d.ts +4 -0
- package/types/models/pvt/image_processing_pvt.d.ts.map +1 -0
- package/types/models/pyannote/feature_extraction_pyannote.d.ts +13 -0
- package/types/models/pyannote/feature_extraction_pyannote.d.ts.map +1 -0
- package/types/models/pyannote/processing_pyannote.d.ts +30 -0
- package/types/models/pyannote/processing_pyannote.d.ts.map +1 -0
- package/types/models/qwen2_vl/image_processing_qwen2_vl.d.ts +11 -0
- package/types/models/qwen2_vl/image_processing_qwen2_vl.d.ts.map +1 -0
- package/types/models/qwen2_vl/processing_qwen2_vl.d.ts +17 -0
- package/types/models/qwen2_vl/processing_qwen2_vl.d.ts.map +1 -0
- package/types/models/rt_detr/image_processing_rt_detr.d.ts +8 -0
- package/types/models/rt_detr/image_processing_rt_detr.d.ts.map +1 -0
- package/types/models/sam/image_processing_sam.d.ts +103 -0
- package/types/models/sam/image_processing_sam.d.ts.map +1 -0
- package/types/models/sam/processing_sam.d.ts +9 -0
- package/types/models/sam/processing_sam.d.ts.map +1 -0
- package/types/models/seamless_m4t/feature_extraction_seamless_m4t.d.ts +34 -0
- package/types/models/seamless_m4t/feature_extraction_seamless_m4t.d.ts.map +1 -0
- package/types/models/segformer/image_processing_segformer.d.ts +10 -0
- package/types/models/segformer/image_processing_segformer.d.ts.map +1 -0
- package/types/models/siglip/image_processing_siglip.d.ts +4 -0
- package/types/models/siglip/image_processing_siglip.d.ts.map +1 -0
- package/types/models/speecht5/feature_extraction_speecht5.d.ts +4 -0
- package/types/models/speecht5/feature_extraction_speecht5.d.ts.map +1 -0
- package/types/models/speecht5/processing_speecht5.d.ts +14 -0
- package/types/models/speecht5/processing_speecht5.d.ts.map +1 -0
- package/types/models/swin2sr/image_processing_swin2sr.d.ts +5 -0
- package/types/models/swin2sr/image_processing_swin2sr.d.ts.map +1 -0
- package/types/models/vit/image_processing_vit.d.ts +6 -0
- package/types/models/vit/image_processing_vit.d.ts.map +1 -0
- package/types/models/vitmatte/image_processing_vitmatte.d.ts +12 -0
- package/types/models/vitmatte/image_processing_vitmatte.d.ts.map +1 -0
- package/types/models/vitpose/image_processing_vitpose.d.ts +26 -0
- package/types/models/vitpose/image_processing_vitpose.d.ts.map +1 -0
- package/types/models/wav2vec2/feature_extraction_wav2vec2.d.ts +19 -0
- package/types/models/wav2vec2/feature_extraction_wav2vec2.d.ts.map +1 -0
- package/types/models/wav2vec2/processing_wav2vec2.d.ts +12 -0
- package/types/models/wav2vec2/processing_wav2vec2.d.ts.map +1 -0
- package/types/models/wespeaker/feature_extraction_wespeaker.d.ts +23 -0
- package/types/models/wespeaker/feature_extraction_wespeaker.d.ts.map +1 -0
- package/types/models/whisper/feature_extraction_whisper.d.ts +21 -0
- package/types/models/whisper/feature_extraction_whisper.d.ts.map +1 -0
- package/types/models/whisper/processing_whisper.d.ts +17 -0
- package/types/models/whisper/processing_whisper.d.ts.map +1 -0
- package/types/models/yolos/image_processing_yolos.d.ts +10 -0
- package/types/models/yolos/image_processing_yolos.d.ts.map +1 -0
- package/types/models.d.ts +150 -0
- package/types/models.d.ts.map +1 -1
- package/types/pipelines.d.ts +2 -3
- package/types/pipelines.d.ts.map +1 -1
- package/types/tokenizers.d.ts +3 -0
- package/types/tokenizers.d.ts.map +1 -1
- package/types/transformers.d.ts +10 -1
- package/types/utils/constants.d.ts +6 -0
- package/types/utils/constants.d.ts.map +1 -1
- package/types/utils/core.d.ts +65 -3
- package/types/utils/core.d.ts.map +1 -1
- package/types/utils/dtypes.d.ts +3 -2
- package/types/utils/dtypes.d.ts.map +1 -1
- package/types/utils/hub.d.ts +1 -1
- package/types/utils/hub.d.ts.map +1 -1
- package/types/utils/image.d.ts +14 -2
- package/types/utils/image.d.ts.map +1 -1
- package/types/utils/tensor.d.ts +39 -4
- package/types/utils/tensor.d.ts.map +1 -1
- package/src/processors.js +0 -2655
- package/types/processors.d.ts +0 -924
- package/types/processors.d.ts.map +0 -1
|
@@ -0,0 +1,1089 @@
|
|
|
1
|
+
import { Callable } from "../utils/generic.js";
|
|
2
|
+
import { Tensor, interpolate, stack } from "../utils/tensor.js";
|
|
3
|
+
import { bankers_round, max, min, softmax } from "../utils/maths.js";
|
|
4
|
+
import { RawImage } from "../utils/image.js";
|
|
5
|
+
import { calculateReflectOffset } from "../utils/core.js";
|
|
6
|
+
import { getModelJSON } from "../utils/hub.js";
|
|
7
|
+
import { IMAGE_PROCESSOR_NAME } from '../utils/constants.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Named tuple to indicate the order we are using is (height x width),
|
|
11
|
+
* even though the Graphics' industry standard is (width x height).
|
|
12
|
+
* @typedef {[height: number, width: number]} HeightWidth
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @typedef {object} ImageProcessorResult
|
|
18
|
+
* @property {Tensor} pixel_values The pixel values of the batched preprocessed images.
|
|
19
|
+
* @property {HeightWidth[]} original_sizes Array of two-dimensional tuples like [[480, 640]].
|
|
20
|
+
* @property {HeightWidth[]} reshaped_input_sizes Array of two-dimensional tuples like [[1000, 1330]].
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Helper function to constrain a value to be a multiple of a number.
|
|
27
|
+
* @param {number} val The value to constrain.
|
|
28
|
+
* @param {number} multiple The number to constrain to.
|
|
29
|
+
* @param {number} [minVal=0] The minimum value to constrain to.
|
|
30
|
+
* @param {number} [maxVal=null] The maximum value to constrain to.
|
|
31
|
+
* @returns {number} The constrained value.
|
|
32
|
+
* @private
|
|
33
|
+
*/
|
|
34
|
+
function constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) {
|
|
35
|
+
const a = val / multiple;
|
|
36
|
+
let x = bankers_round(a) * multiple;
|
|
37
|
+
|
|
38
|
+
if (maxVal !== null && x > maxVal) {
|
|
39
|
+
x = Math.floor(a) * multiple;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (x < minVal) {
|
|
43
|
+
x = Math.ceil(a) * multiple;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return x;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Rounds the height and width down to the closest multiple of size_divisibility
|
|
51
|
+
* @param {[number, number]} size The size of the image
|
|
52
|
+
* @param {number} divisor The divisor to use.
|
|
53
|
+
* @returns {[number, number]} The rounded size.
|
|
54
|
+
*/
|
|
55
|
+
function enforce_size_divisibility([width, height], divisor) {
|
|
56
|
+
return [
|
|
57
|
+
Math.max(Math.floor(width / divisor), 1) * divisor,
|
|
58
|
+
Math.max(Math.floor(height / divisor), 1) * divisor
|
|
59
|
+
];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
// Helper functions
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Converts bounding boxes from center format to corners format.
|
|
67
|
+
*
|
|
68
|
+
* @param {number[]} arr The coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height)
|
|
69
|
+
* @returns {number[]} The coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y)
|
|
70
|
+
*/
|
|
71
|
+
function center_to_corners_format([centerX, centerY, width, height]) {
|
|
72
|
+
return [
|
|
73
|
+
centerX - width / 2,
|
|
74
|
+
centerY - height / 2,
|
|
75
|
+
centerX + width / 2,
|
|
76
|
+
centerY + height / 2
|
|
77
|
+
];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Post-processes the outputs of the model (for object detection).
|
|
82
|
+
* @param {Object} outputs The outputs of the model that must be post-processed
|
|
83
|
+
* @param {Tensor} outputs.logits The logits
|
|
84
|
+
* @param {Tensor} outputs.pred_boxes The predicted boxes.
|
|
85
|
+
* @param {number} [threshold=0.5] The threshold to use for the scores.
|
|
86
|
+
* @param {[number, number][]} [target_sizes=null] The sizes of the original images.
|
|
87
|
+
* @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.
|
|
88
|
+
* @return {Object[]} An array of objects containing the post-processed outputs.
|
|
89
|
+
*/
|
|
90
|
+
export function post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) {
|
|
91
|
+
const out_logits = outputs.logits;
|
|
92
|
+
const out_bbox = outputs.pred_boxes;
|
|
93
|
+
const [batch_size, num_boxes, num_classes] = out_logits.dims;
|
|
94
|
+
|
|
95
|
+
if (target_sizes !== null && target_sizes.length !== batch_size) {
|
|
96
|
+
throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
|
|
97
|
+
}
|
|
98
|
+
let toReturn = [];
|
|
99
|
+
for (let i = 0; i < batch_size; ++i) {
|
|
100
|
+
let target_size = target_sizes !== null ? target_sizes[i] : null;
|
|
101
|
+
let info = {
|
|
102
|
+
boxes: [],
|
|
103
|
+
classes: [],
|
|
104
|
+
scores: []
|
|
105
|
+
}
|
|
106
|
+
let logits = out_logits[i];
|
|
107
|
+
let bbox = out_bbox[i];
|
|
108
|
+
|
|
109
|
+
for (let j = 0; j < num_boxes; ++j) {
|
|
110
|
+
let logit = logits[j];
|
|
111
|
+
|
|
112
|
+
let indices = [];
|
|
113
|
+
let probs;
|
|
114
|
+
if (is_zero_shot) {
|
|
115
|
+
// Get indices of classes with high enough probability
|
|
116
|
+
probs = logit.sigmoid().data;
|
|
117
|
+
for (let k = 0; k < probs.length; ++k) {
|
|
118
|
+
if (probs[k] > threshold) {
|
|
119
|
+
indices.push(k);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
} else {
|
|
124
|
+
// Get most probable class
|
|
125
|
+
let maxIndex = max(logit.data)[1];
|
|
126
|
+
|
|
127
|
+
if (maxIndex === num_classes - 1) {
|
|
128
|
+
// This is the background class, skip it
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
// Compute softmax over classes
|
|
132
|
+
probs = softmax(logit.data);
|
|
133
|
+
|
|
134
|
+
if (probs[maxIndex] < threshold) {
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
indices.push(maxIndex);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
for (const index of indices) {
|
|
141
|
+
|
|
142
|
+
// Some class has a high enough probability
|
|
143
|
+
/** @type {number[]} */
|
|
144
|
+
let box = bbox[j].data;
|
|
145
|
+
|
|
146
|
+
// convert to [x0, y0, x1, y1] format
|
|
147
|
+
box = center_to_corners_format(box)
|
|
148
|
+
if (target_size !== null) {
|
|
149
|
+
box = box.map((x, i) => x * target_size[(i + 1) % 2])
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
info.boxes.push(box);
|
|
153
|
+
info.classes.push(index);
|
|
154
|
+
info.scores.push(probs[index]);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
toReturn.push(info);
|
|
158
|
+
}
|
|
159
|
+
return toReturn;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Post-processes the outputs of the model (for semantic segmentation).
|
|
165
|
+
* @param {*} outputs Raw outputs of the model.
|
|
166
|
+
* @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size
|
|
167
|
+
* (height, width) of each prediction. If unset, predictions will not be resized.
|
|
168
|
+
* @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps.
|
|
169
|
+
*/
|
|
170
|
+
export function post_process_semantic_segmentation(outputs, target_sizes = null) {
|
|
171
|
+
|
|
172
|
+
const logits = outputs.logits;
|
|
173
|
+
const batch_size = logits.dims[0];
|
|
174
|
+
|
|
175
|
+
if (target_sizes !== null && target_sizes.length !== batch_size) {
|
|
176
|
+
throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const toReturn = [];
|
|
180
|
+
for (let i = 0; i < batch_size; ++i) {
|
|
181
|
+
const target_size = target_sizes !== null ? target_sizes[i] : null;
|
|
182
|
+
|
|
183
|
+
let data = logits[i];
|
|
184
|
+
|
|
185
|
+
// 1. If target_size is not null, we need to resize the masks to the target size
|
|
186
|
+
if (target_size !== null) {
|
|
187
|
+
// resize the masks to the target size
|
|
188
|
+
data = interpolate(data, target_size, 'bilinear', false);
|
|
189
|
+
}
|
|
190
|
+
const [height, width] = target_size ?? data.dims.slice(-2);
|
|
191
|
+
|
|
192
|
+
const segmentation = new Tensor(
|
|
193
|
+
'int32',
|
|
194
|
+
new Int32Array(height * width),
|
|
195
|
+
[height, width]
|
|
196
|
+
);
|
|
197
|
+
|
|
198
|
+
// Buffer to store current largest value
|
|
199
|
+
const buffer = data[0].data;
|
|
200
|
+
const segmentation_data = segmentation.data;
|
|
201
|
+
for (let j = 1; j < data.dims[0]; ++j) {
|
|
202
|
+
const row = data[j].data;
|
|
203
|
+
for (let k = 0; k < row.length; ++k) {
|
|
204
|
+
if (row[k] > buffer[k]) {
|
|
205
|
+
buffer[k] = row[k];
|
|
206
|
+
segmentation_data[k] = j;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Store which objects have labels
|
|
212
|
+
// This is much more efficient that creating a set of the final values
|
|
213
|
+
const hasLabel = new Array(data.dims[0]);
|
|
214
|
+
for (let j = 0; j < segmentation_data.length; ++j) {
|
|
215
|
+
const index = segmentation_data[j];
|
|
216
|
+
hasLabel[index] = index;
|
|
217
|
+
}
|
|
218
|
+
/** @type {number[]} The unique list of labels that were detected */
|
|
219
|
+
const labels = hasLabel.filter(x => x !== undefined);
|
|
220
|
+
|
|
221
|
+
toReturn.push({ segmentation, labels });
|
|
222
|
+
}
|
|
223
|
+
return toReturn;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`.
|
|
229
|
+
* @param {Tensor} class_logits The class logits.
|
|
230
|
+
* @param {Tensor} mask_logits The mask logits.
|
|
231
|
+
* @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks.
|
|
232
|
+
* @param {number} num_labels The number of labels.
|
|
233
|
+
* @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels.
|
|
234
|
+
* @private
|
|
235
|
+
*/
|
|
236
|
+
function remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) {
|
|
237
|
+
|
|
238
|
+
const mask_probs_item = [];
|
|
239
|
+
const pred_scores_item = [];
|
|
240
|
+
const pred_labels_item = [];
|
|
241
|
+
|
|
242
|
+
for (let j = 0; j < class_logits.dims[0]; ++j) {
|
|
243
|
+
const cls = class_logits[j];
|
|
244
|
+
const mask = mask_logits[j];
|
|
245
|
+
|
|
246
|
+
const pred_label = max(cls.data)[1];
|
|
247
|
+
if (pred_label === num_labels) {
|
|
248
|
+
// Is the background, so we ignore it
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const scores = softmax(cls.data);
|
|
253
|
+
const pred_score = scores[pred_label];
|
|
254
|
+
if (pred_score > object_mask_threshold) {
|
|
255
|
+
mask_probs_item.push(mask);
|
|
256
|
+
pred_scores_item.push(pred_score);
|
|
257
|
+
pred_labels_item.push(pred_label);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return [mask_probs_item, pred_scores_item, pred_labels_item];
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Checks whether the segment is valid or not.
|
|
266
|
+
* @param {Int32Array} mask_labels Labels for each pixel in the mask.
|
|
267
|
+
* @param {Tensor[]} mask_probs Probabilities for each pixel in the masks.
|
|
268
|
+
* @param {number} k The class id of the segment.
|
|
269
|
+
* @param {number} mask_threshold The mask threshold.
|
|
270
|
+
* @param {number} overlap_mask_area_threshold The overlap mask area threshold.
|
|
271
|
+
* @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels.
|
|
272
|
+
* @private
|
|
273
|
+
*/
|
|
274
|
+
function check_segment_validity(
|
|
275
|
+
mask_labels,
|
|
276
|
+
mask_probs,
|
|
277
|
+
k,
|
|
278
|
+
mask_threshold = 0.5,
|
|
279
|
+
overlap_mask_area_threshold = 0.8
|
|
280
|
+
) {
|
|
281
|
+
// mask_k is a 1D array of indices, indicating where the mask is equal to k
|
|
282
|
+
const mask_k = [];
|
|
283
|
+
let mask_k_area = 0;
|
|
284
|
+
let original_area = 0;
|
|
285
|
+
|
|
286
|
+
const mask_probs_k_data = mask_probs[k].data;
|
|
287
|
+
|
|
288
|
+
// Compute the area of all the stuff in query k
|
|
289
|
+
for (let i = 0; i < mask_labels.length; ++i) {
|
|
290
|
+
if (mask_labels[i] === k) {
|
|
291
|
+
mask_k.push(i);
|
|
292
|
+
++mask_k_area;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
if (mask_probs_k_data[i] >= mask_threshold) {
|
|
296
|
+
++original_area;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
let mask_exists = mask_k_area > 0 && original_area > 0;
|
|
300
|
+
|
|
301
|
+
// Eliminate disconnected tiny segments
|
|
302
|
+
if (mask_exists) {
|
|
303
|
+
// Perform additional check
|
|
304
|
+
let area_ratio = mask_k_area / original_area;
|
|
305
|
+
mask_exists = area_ratio > overlap_mask_area_threshold;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
return [mask_exists, mask_k]
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Computes the segments.
|
|
313
|
+
* @param {Tensor[]} mask_probs The mask probabilities.
|
|
314
|
+
* @param {number[]} pred_scores The predicted scores.
|
|
315
|
+
* @param {number[]} pred_labels The predicted labels.
|
|
316
|
+
* @param {number} mask_threshold The mask threshold.
|
|
317
|
+
* @param {number} overlap_mask_area_threshold The overlap mask area threshold.
|
|
318
|
+
* @param {Set<number>} label_ids_to_fuse The label ids to fuse.
|
|
319
|
+
* @param {number[]} target_size The target size of the image.
|
|
320
|
+
* @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments.
|
|
321
|
+
* @private
|
|
322
|
+
*/
|
|
323
|
+
function compute_segments(
|
|
324
|
+
mask_probs,
|
|
325
|
+
pred_scores,
|
|
326
|
+
pred_labels,
|
|
327
|
+
mask_threshold,
|
|
328
|
+
overlap_mask_area_threshold,
|
|
329
|
+
label_ids_to_fuse = null,
|
|
330
|
+
target_size = null,
|
|
331
|
+
) {
|
|
332
|
+
const [height, width] = target_size ?? mask_probs[0].dims;
|
|
333
|
+
|
|
334
|
+
const segmentation = new Tensor(
|
|
335
|
+
'int32',
|
|
336
|
+
new Int32Array(height * width),
|
|
337
|
+
[height, width]
|
|
338
|
+
);
|
|
339
|
+
const segments = [];
|
|
340
|
+
|
|
341
|
+
// 1. If target_size is not null, we need to resize the masks to the target size
|
|
342
|
+
if (target_size !== null) {
|
|
343
|
+
// resize the masks to the target size
|
|
344
|
+
for (let i = 0; i < mask_probs.length; ++i) {
|
|
345
|
+
mask_probs[i] = interpolate(mask_probs[i], target_size, 'bilinear', false);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// 2. Weigh each mask by its prediction score
|
|
350
|
+
// NOTE: `mask_probs` is updated in-place
|
|
351
|
+
//
|
|
352
|
+
// Temporary storage for the best label/scores for each pixel ([height, width]):
|
|
353
|
+
const mask_labels = new Int32Array(mask_probs[0].data.length);
|
|
354
|
+
const bestScores = new Float32Array(mask_probs[0].data.length);
|
|
355
|
+
|
|
356
|
+
for (let i = 0; i < mask_probs.length; ++i) {
|
|
357
|
+
let score = pred_scores[i];
|
|
358
|
+
|
|
359
|
+
const mask_probs_i_data = mask_probs[i].data;
|
|
360
|
+
|
|
361
|
+
for (let j = 0; j < mask_probs_i_data.length; ++j) {
|
|
362
|
+
mask_probs_i_data[j] *= score
|
|
363
|
+
if (mask_probs_i_data[j] > bestScores[j]) {
|
|
364
|
+
mask_labels[j] = i;
|
|
365
|
+
bestScores[j] = mask_probs_i_data[j];
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
let current_segment_id = 0;
|
|
371
|
+
|
|
372
|
+
// let stuff_memory_list = {}
|
|
373
|
+
const segmentation_data = segmentation.data;
|
|
374
|
+
for (let k = 0; k < pred_labels.length; ++k) {
|
|
375
|
+
const pred_class = pred_labels[k];
|
|
376
|
+
|
|
377
|
+
// TODO add `should_fuse`
|
|
378
|
+
// let should_fuse = pred_class in label_ids_to_fuse
|
|
379
|
+
|
|
380
|
+
// Check if mask exists and large enough to be a segment
|
|
381
|
+
const [mask_exists, mask_k] = check_segment_validity(
|
|
382
|
+
mask_labels,
|
|
383
|
+
mask_probs,
|
|
384
|
+
k,
|
|
385
|
+
mask_threshold,
|
|
386
|
+
overlap_mask_area_threshold
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
if (!mask_exists) {
|
|
390
|
+
// Nothing to see here
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// TODO
|
|
395
|
+
// if (pred_class in stuff_memory_list) {
|
|
396
|
+
// current_segment_id = stuff_memory_list[pred_class]
|
|
397
|
+
// } else {
|
|
398
|
+
// current_segment_id += 1;
|
|
399
|
+
// }
|
|
400
|
+
++current_segment_id;
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
// Add current object segment to final segmentation map
|
|
404
|
+
for (const index of mask_k) {
|
|
405
|
+
segmentation_data[index] = current_segment_id;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
segments.push({
|
|
409
|
+
id: current_segment_id,
|
|
410
|
+
label_id: pred_class,
|
|
411
|
+
// was_fused: should_fuse, TODO
|
|
412
|
+
score: pred_scores[k],
|
|
413
|
+
})
|
|
414
|
+
|
|
415
|
+
// TODO
|
|
416
|
+
// if(should_fuse){
|
|
417
|
+
// stuff_memory_list[pred_class] = current_segment_id
|
|
418
|
+
// }
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
return [segmentation, segments];
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Rescales the image so that the following conditions are met:
|
|
426
|
+
*
|
|
427
|
+
* 1. Both dimensions (height and width) are divisible by 'factor'.
|
|
428
|
+
* 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
|
|
429
|
+
* 3. The aspect ratio of the image is maintained as closely as possible.
|
|
430
|
+
*
|
|
431
|
+
* @param {number} height The height of the image.
|
|
432
|
+
* @param {number} width The width of the image.
|
|
433
|
+
* @param {number} [factor=28] The factor to use for resizing.
|
|
434
|
+
* @param {number} [min_pixels=56*56] The minimum number of pixels.
|
|
435
|
+
* @param {number} [max_pixels=14*14*4*1280] The maximum number of pixels.
|
|
436
|
+
* @returns {[number, number]} The new height and width of the image.
|
|
437
|
+
* @throws {Error} If the height or width is smaller than the factor.
|
|
438
|
+
*/
|
|
439
|
+
function smart_resize(height, width, factor = 28, min_pixels = 56 * 56, max_pixels = 14 * 14 * 4 * 1280) {
|
|
440
|
+
|
|
441
|
+
if (height < factor || width < factor) {
|
|
442
|
+
throw new Error(`height:${height} or width:${width} must be larger than factor:${factor}`);
|
|
443
|
+
} else if (Math.max(height, width) / Math.min(height, width) > 200) {
|
|
444
|
+
throw new Error(
|
|
445
|
+
`absolute aspect ratio must be smaller than 200, got ${Math.max(height, width) / Math.min(height, width)}`
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
let h_bar = Math.round(height / factor) * factor;
|
|
450
|
+
let w_bar = Math.round(width / factor) * factor;
|
|
451
|
+
|
|
452
|
+
if (h_bar * w_bar > max_pixels) {
|
|
453
|
+
const beta = Math.sqrt((height * width) / max_pixels);
|
|
454
|
+
h_bar = Math.floor((height / beta) / factor) * factor;
|
|
455
|
+
w_bar = Math.floor((width / beta) / factor) * factor;
|
|
456
|
+
} else if (h_bar * w_bar < min_pixels) {
|
|
457
|
+
const beta = Math.sqrt(min_pixels / (height * width));
|
|
458
|
+
h_bar = Math.ceil((height * beta) / factor) * factor;
|
|
459
|
+
w_bar = Math.ceil((width * beta) / factor) * factor;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
return [h_bar, w_bar];
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Post-process the model output to generate the final panoptic segmentation.
|
|
468
|
+
* @param {*} outputs The model output to post process
|
|
469
|
+
* @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.
|
|
470
|
+
* @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.
|
|
471
|
+
* @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.
|
|
472
|
+
* @param {Set<number>} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together.
|
|
473
|
+
* @param {[number, number][]} [target_sizes=null] The target sizes to resize the masks to.
|
|
474
|
+
* @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}
|
|
475
|
+
*/
|
|
476
|
+
export function post_process_panoptic_segmentation(
|
|
477
|
+
outputs,
|
|
478
|
+
threshold = 0.5,
|
|
479
|
+
mask_threshold = 0.5,
|
|
480
|
+
overlap_mask_area_threshold = 0.8,
|
|
481
|
+
label_ids_to_fuse = null,
|
|
482
|
+
target_sizes = null,
|
|
483
|
+
) {
|
|
484
|
+
if (label_ids_to_fuse === null) {
|
|
485
|
+
console.warn("`label_ids_to_fuse` unset. No instance will be fused.")
|
|
486
|
+
label_ids_to_fuse = new Set();
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const class_queries_logits = outputs.class_queries_logits ?? outputs.logits; // [batch_size, num_queries, num_classes+1]
|
|
490
|
+
const masks_queries_logits = outputs.masks_queries_logits ?? outputs.pred_masks; // [batch_size, num_queries, height, width]
|
|
491
|
+
|
|
492
|
+
const mask_probs = masks_queries_logits.sigmoid() // [batch_size, num_queries, height, width]
|
|
493
|
+
|
|
494
|
+
let [batch_size, num_queries, num_labels] = class_queries_logits.dims;
|
|
495
|
+
num_labels -= 1; // Remove last class (background)
|
|
496
|
+
|
|
497
|
+
if (target_sizes !== null && target_sizes.length !== batch_size) {
|
|
498
|
+
throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
let toReturn = [];
|
|
502
|
+
for (let i = 0; i < batch_size; ++i) {
|
|
503
|
+
let target_size = target_sizes !== null ? target_sizes[i] : null;
|
|
504
|
+
|
|
505
|
+
let class_logits = class_queries_logits[i];
|
|
506
|
+
let mask_logits = mask_probs[i];
|
|
507
|
+
|
|
508
|
+
let [mask_probs_item, pred_scores_item, pred_labels_item] = remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels);
|
|
509
|
+
|
|
510
|
+
if (pred_labels_item.length === 0) {
|
|
511
|
+
// No mask found
|
|
512
|
+
let [height, width] = target_size ?? mask_logits.dims.slice(-2);
|
|
513
|
+
|
|
514
|
+
let segmentation = new Tensor(
|
|
515
|
+
'int32',
|
|
516
|
+
new Int32Array(height * width).fill(-1),
|
|
517
|
+
[height, width]
|
|
518
|
+
)
|
|
519
|
+
toReturn.push({
|
|
520
|
+
segmentation: segmentation,
|
|
521
|
+
segments_info: []
|
|
522
|
+
});
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
// Get segmentation map and segment information of batch item
|
|
528
|
+
let [segmentation, segments] = compute_segments(
|
|
529
|
+
mask_probs_item,
|
|
530
|
+
pred_scores_item,
|
|
531
|
+
pred_labels_item,
|
|
532
|
+
mask_threshold,
|
|
533
|
+
overlap_mask_area_threshold,
|
|
534
|
+
label_ids_to_fuse,
|
|
535
|
+
target_size,
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
toReturn.push({
|
|
539
|
+
segmentation: segmentation,
|
|
540
|
+
segments_info: segments
|
|
541
|
+
})
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
return toReturn;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Post-processes the outputs of the model (for instance segmentation).
|
|
550
|
+
* @param {*} outputs Raw outputs of the model.
|
|
551
|
+
* @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.
|
|
552
|
+
* @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size
|
|
553
|
+
* (height, width) of each prediction. If unset, predictions will not be resized.
|
|
554
|
+
* @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}
|
|
555
|
+
*/
|
|
556
|
+
export function post_process_instance_segmentation(outputs, threshold = 0.5, target_sizes = null) {
|
|
557
|
+
throw new Error('`post_process_instance_segmentation` is not yet implemented.');
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* @typedef {Object} ImageProcessorConfig A configuration object used to create an image processor.
|
|
563
|
+
* @property {function} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates.
|
|
564
|
+
* @property {number[]} [image_mean] The mean values for image normalization.
|
|
565
|
+
* @property {number[]} [image_std] The standard deviation values for image normalization.
|
|
566
|
+
* @property {boolean} [do_rescale] Whether to rescale the image pixel values to the [0,1] range.
|
|
567
|
+
* @property {number} [rescale_factor] The factor to use for rescaling the image pixel values.
|
|
568
|
+
* @property {boolean} [do_normalize] Whether to normalize the image pixel values.
|
|
569
|
+
* @property {boolean} [do_resize] Whether to resize the image.
|
|
570
|
+
* @property {number} [resample] What method to use for resampling.
|
|
571
|
+
* @property {number|Object} [size] The size to resize the image to.
|
|
572
|
+
* @property {number|Object} [image_size] The size to resize the image to (same as `size`).
|
|
573
|
+
* @property {boolean} [do_flip_channel_order=false] Whether to flip the color channels from RGB to BGR.
|
|
574
|
+
* Can be overridden by the `do_flip_channel_order` parameter in the `preprocess` method.
|
|
575
|
+
* @property {boolean} [do_center_crop] Whether to center crop the image to the specified `crop_size`.
|
|
576
|
+
* Can be overridden by `do_center_crop` in the `preprocess` method.
|
|
577
|
+
* @property {boolean} [do_thumbnail] Whether to resize the image using thumbnail method.
|
|
578
|
+
* @property {boolean} [keep_aspect_ratio] If `true`, the image is resized to the largest possible size such that the aspect ratio is preserved.
|
|
579
|
+
* Can be overidden by `keep_aspect_ratio` in `preprocess`.
|
|
580
|
+
* @property {number} [ensure_multiple_of] If `do_resize` is `true`, the image is resized to a size that is a multiple of this value.
|
|
581
|
+
* Can be overidden by `ensure_multiple_of` in `preprocess`.
|
|
582
|
+
*
|
|
583
|
+
* @property {number[]} [mean] The mean values for image normalization (same as `image_mean`).
|
|
584
|
+
* @property {number[]} [std] The standard deviation values for image normalization (same as `image_std`).
|
|
585
|
+
*/
|
|
586
|
+
|
|
587
|
+
export class ImageProcessor extends Callable {
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Constructs a new `ImageProcessor`.
|
|
591
|
+
* @param {ImageProcessorConfig} config The configuration object.
|
|
592
|
+
*/
|
|
593
|
+
constructor(config) {
|
|
594
|
+
super();
|
|
595
|
+
|
|
596
|
+
this.image_mean = config.image_mean ?? config.mean;
|
|
597
|
+
this.image_std = config.image_std ?? config.std;
|
|
598
|
+
|
|
599
|
+
this.resample = config.resample ?? 2; // 2 => bilinear
|
|
600
|
+
this.do_rescale = config.do_rescale ?? true;
|
|
601
|
+
this.rescale_factor = config.rescale_factor ?? (1 / 255);
|
|
602
|
+
this.do_normalize = config.do_normalize;
|
|
603
|
+
|
|
604
|
+
this.do_thumbnail = config.do_thumbnail;
|
|
605
|
+
this.size = config.size ?? config.image_size;
|
|
606
|
+
this.do_resize = config.do_resize ?? (this.size !== undefined);
|
|
607
|
+
this.size_divisibility = config.size_divisibility ?? config.size_divisor;
|
|
608
|
+
|
|
609
|
+
this.do_center_crop = config.do_center_crop;
|
|
610
|
+
this.crop_size = config.crop_size;
|
|
611
|
+
this.do_convert_rgb = config.do_convert_rgb ?? true;
|
|
612
|
+
this.do_crop_margin = config.do_crop_margin;
|
|
613
|
+
|
|
614
|
+
this.pad_size = config.pad_size;
|
|
615
|
+
this.do_pad = config.do_pad;
|
|
616
|
+
|
|
617
|
+
if (this.do_pad && !this.pad_size && this.size && this.size.width !== undefined && this.size.height !== undefined) {
|
|
618
|
+
// Should pad, but no pad size specified
|
|
619
|
+
// We infer the pad size from the resize size
|
|
620
|
+
this.pad_size = this.size
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
this.do_flip_channel_order = config.do_flip_channel_order ?? false;
|
|
624
|
+
|
|
625
|
+
this.config = config;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
|
|
630
|
+
* corresponding dimension of the specified size.
|
|
631
|
+
* @param {RawImage} image The image to be resized.
|
|
632
|
+
* @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to.
|
|
633
|
+
* @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.
|
|
634
|
+
* @returns {Promise<RawImage>} The resized image.
|
|
635
|
+
*/
|
|
636
|
+
async thumbnail(image, size, resample = 2) {
|
|
637
|
+
const input_height = image.height;
|
|
638
|
+
const input_width = image.width;
|
|
639
|
+
|
|
640
|
+
const output_height = size.height;
|
|
641
|
+
const output_width = size.width;
|
|
642
|
+
|
|
643
|
+
// We always resize to the smallest of either the input or output size.
|
|
644
|
+
let height = Math.min(input_height, output_height)
|
|
645
|
+
let width = Math.min(input_width, output_width)
|
|
646
|
+
|
|
647
|
+
if (height === input_height && width === input_width) {
|
|
648
|
+
return image;
|
|
649
|
+
}
|
|
650
|
+
if (input_height > input_width) {
|
|
651
|
+
width = Math.floor(input_width * height / input_height);
|
|
652
|
+
} else if (input_width > input_height) {
|
|
653
|
+
height = Math.floor(input_height * width / input_width);
|
|
654
|
+
}
|
|
655
|
+
return await image.resize(width, height, { resample });
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).
|
|
661
|
+
* @param {RawImage} image The image to be cropped.
|
|
662
|
+
* @param {number} gray_threshold Value below which pixels are considered to be gray.
|
|
663
|
+
* @returns {Promise<RawImage>} The cropped image.
|
|
664
|
+
*/
|
|
665
|
+
async crop_margin(image, gray_threshold = 200) {
|
|
666
|
+
|
|
667
|
+
const gray_image = image.clone().grayscale();
|
|
668
|
+
|
|
669
|
+
const minValue = min(gray_image.data)[0];
|
|
670
|
+
const maxValue = max(gray_image.data)[0];
|
|
671
|
+
const diff = maxValue - minValue;
|
|
672
|
+
|
|
673
|
+
if (diff === 0) {
|
|
674
|
+
return image;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
const threshold = gray_threshold / 255;
|
|
678
|
+
|
|
679
|
+
let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0;
|
|
680
|
+
const gray_image_data = gray_image.data;
|
|
681
|
+
for (let j = 0; j < gray_image.height; ++j) {
|
|
682
|
+
const row = j * gray_image.width;
|
|
683
|
+
for (let i = 0; i < gray_image.width; ++i) {
|
|
684
|
+
if ((gray_image_data[row + i] - minValue) / diff < threshold) {
|
|
685
|
+
// We have a non-zero pixel, so we update the min/max values accordingly
|
|
686
|
+
x_min = Math.min(x_min, i);
|
|
687
|
+
y_min = Math.min(y_min, j);
|
|
688
|
+
x_max = Math.max(x_max, i);
|
|
689
|
+
y_max = Math.max(y_max, j);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
image = await image.crop([x_min, y_min, x_max, y_max]);
|
|
695
|
+
return image;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/**
|
|
699
|
+
* Pad the image by a certain amount.
|
|
700
|
+
* @param {Float32Array} pixelData The pixel data to pad.
|
|
701
|
+
* @param {number[]} imgDims The dimensions of the image (height, width, channels).
|
|
702
|
+
* @param {{width:number; height:number}|number} padSize The dimensions of the padded image.
|
|
703
|
+
* @param {Object} options The options for padding.
|
|
704
|
+
* @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.
|
|
705
|
+
* @param {boolean} [options.center=false] Whether to center the image.
|
|
706
|
+
* @param {number|number[]} [options.constant_values=0] The constant value to use for padding.
|
|
707
|
+
* @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.
|
|
708
|
+
*/
|
|
709
|
+
pad_image(pixelData, imgDims, padSize, {
|
|
710
|
+
mode = 'constant',
|
|
711
|
+
center = false,
|
|
712
|
+
constant_values = 0,
|
|
713
|
+
} = {}) {
|
|
714
|
+
const [imageHeight, imageWidth, imageChannels] = imgDims;
|
|
715
|
+
|
|
716
|
+
let paddedImageWidth, paddedImageHeight;
|
|
717
|
+
if (typeof padSize === 'number') {
|
|
718
|
+
paddedImageWidth = padSize;
|
|
719
|
+
paddedImageHeight = padSize;
|
|
720
|
+
} else {
|
|
721
|
+
paddedImageWidth = padSize.width;
|
|
722
|
+
paddedImageHeight = padSize.height;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// Only add padding if there is a difference in size
|
|
726
|
+
if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) {
|
|
727
|
+
const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels);
|
|
728
|
+
if (Array.isArray(constant_values)) {
|
|
729
|
+
// Fill with constant values, cycling through the array
|
|
730
|
+
for (let i = 0; i < paddedPixelData.length; ++i) {
|
|
731
|
+
paddedPixelData[i] = constant_values[i % imageChannels];
|
|
732
|
+
}
|
|
733
|
+
} else if (constant_values !== 0) {
|
|
734
|
+
paddedPixelData.fill(constant_values);
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
const [left, top] = center
|
|
738
|
+
? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)]
|
|
739
|
+
: [0, 0];
|
|
740
|
+
|
|
741
|
+
// Copy the original image into the padded image
|
|
742
|
+
for (let i = 0; i < imageHeight; ++i) {
|
|
743
|
+
const a = (i + top) * paddedImageWidth;
|
|
744
|
+
const b = i * imageWidth;
|
|
745
|
+
for (let j = 0; j < imageWidth; ++j) {
|
|
746
|
+
const c = (a + j + left) * imageChannels;
|
|
747
|
+
const d = (b + j) * imageChannels;
|
|
748
|
+
for (let k = 0; k < imageChannels; ++k) {
|
|
749
|
+
paddedPixelData[c + k] = pixelData[d + k];
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
if (mode === 'symmetric') {
|
|
755
|
+
if (center) {
|
|
756
|
+
throw new Error('`center` padding is not supported when `mode` is set to `symmetric`.');
|
|
757
|
+
// TODO: Implement this
|
|
758
|
+
}
|
|
759
|
+
const h1 = imageHeight - 1;
|
|
760
|
+
const w1 = imageWidth - 1;
|
|
761
|
+
for (let i = 0; i < paddedImageHeight; ++i) {
|
|
762
|
+
const a = i * paddedImageWidth;
|
|
763
|
+
const b = calculateReflectOffset(i, h1) * imageWidth;
|
|
764
|
+
|
|
765
|
+
for (let j = 0; j < paddedImageWidth; ++j) {
|
|
766
|
+
if (i < imageHeight && j < imageWidth) continue; // Do not overwrite original image
|
|
767
|
+
const c = (a + j) * imageChannels;
|
|
768
|
+
const d = (b + calculateReflectOffset(j, w1)) * imageChannels;
|
|
769
|
+
|
|
770
|
+
// Copy channel-wise
|
|
771
|
+
for (let k = 0; k < imageChannels; ++k) {
|
|
772
|
+
paddedPixelData[c + k] = pixelData[d + k];
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
// Update pixel data and image dimensions
|
|
780
|
+
pixelData = paddedPixelData;
|
|
781
|
+
imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]
|
|
782
|
+
}
|
|
783
|
+
return [pixelData, imgDims];
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* Rescale the image' pixel values by `this.rescale_factor`.
|
|
788
|
+
* @param {Float32Array} pixelData The pixel data to rescale.
|
|
789
|
+
* @returns {void}
|
|
790
|
+
*/
|
|
791
|
+
rescale(pixelData) {
|
|
792
|
+
for (let i = 0; i < pixelData.length; ++i) {
|
|
793
|
+
pixelData[i] = this.rescale_factor * pixelData[i];
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* Find the target (width, height) dimension of the output image after
|
|
799
|
+
* resizing given the input image and the desired size.
|
|
800
|
+
* @param {RawImage} image The image to resize.
|
|
801
|
+
* @param {any} size The size to use for resizing the image.
|
|
802
|
+
* @returns {[number, number]} The target (width, height) dimension of the output image after resizing.
|
|
803
|
+
*/
|
|
804
|
+
get_resize_output_image_size(image, size) {
|
|
805
|
+
// `size` comes in many forms, so we need to handle them all here:
|
|
806
|
+
// 1. `size` is an integer, in which case we resize the image to be a square
|
|
807
|
+
|
|
808
|
+
const [srcWidth, srcHeight] = image.size;
|
|
809
|
+
|
|
810
|
+
let shortest_edge;
|
|
811
|
+
let longest_edge;
|
|
812
|
+
|
|
813
|
+
if (this.do_thumbnail) {
|
|
814
|
+
// NOTE: custom logic for `Donut` models
|
|
815
|
+
const { height, width } = size;
|
|
816
|
+
shortest_edge = Math.min(height, width)
|
|
817
|
+
}
|
|
818
|
+
// Support both formats for backwards compatibility
|
|
819
|
+
else if (Number.isInteger(size)) {
|
|
820
|
+
shortest_edge = size;
|
|
821
|
+
longest_edge = this.config.max_size ?? shortest_edge;
|
|
822
|
+
|
|
823
|
+
} else if (size !== undefined) {
|
|
824
|
+
// Extract known properties from `size`
|
|
825
|
+
shortest_edge = size.shortest_edge;
|
|
826
|
+
longest_edge = size.longest_edge;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// If `longest_edge` and `shortest_edge` are set, maintain aspect ratio and resize to `shortest_edge`
|
|
830
|
+
// while keeping the largest dimension <= `longest_edge`
|
|
831
|
+
if (shortest_edge !== undefined || longest_edge !== undefined) {
|
|
832
|
+
// http://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/
|
|
833
|
+
// Try resize so that shortest edge is `shortest_edge` (target)
|
|
834
|
+
const shortResizeFactor = shortest_edge === undefined
|
|
835
|
+
? 1 // If `shortest_edge` is not set, don't upscale
|
|
836
|
+
: Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight);
|
|
837
|
+
|
|
838
|
+
const newWidth = srcWidth * shortResizeFactor;
|
|
839
|
+
const newHeight = srcHeight * shortResizeFactor;
|
|
840
|
+
|
|
841
|
+
// The new width and height might be greater than `longest_edge`, so
|
|
842
|
+
// we downscale again to ensure the largest dimension is `longest_edge`
|
|
843
|
+
const longResizeFactor = longest_edge === undefined
|
|
844
|
+
? 1 // If `longest_edge` is not set, don't downscale
|
|
845
|
+
: Math.min(longest_edge / newWidth, longest_edge / newHeight);
|
|
846
|
+
|
|
847
|
+
// To avoid certain floating point precision issues, we round to 2 decimal places
|
|
848
|
+
let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2)));
|
|
849
|
+
let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2)));
|
|
850
|
+
|
|
851
|
+
if (this.size_divisibility !== undefined) {
|
|
852
|
+
[finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility)
|
|
853
|
+
}
|
|
854
|
+
return [finalWidth, finalHeight];
|
|
855
|
+
|
|
856
|
+
} else if (size !== undefined && size.width !== undefined && size.height !== undefined) {
|
|
857
|
+
// If `width` and `height` are set, resize to those dimensions
|
|
858
|
+
|
|
859
|
+
let newWidth = size.width;
|
|
860
|
+
let newHeight = size.height;
|
|
861
|
+
|
|
862
|
+
// Custom for DPT models
|
|
863
|
+
if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) {
|
|
864
|
+
|
|
865
|
+
// determine new height and width
|
|
866
|
+
let scale_height = newHeight / srcHeight;
|
|
867
|
+
let scale_width = newWidth / srcWidth;
|
|
868
|
+
|
|
869
|
+
// scale as little as possible
|
|
870
|
+
if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) {
|
|
871
|
+
// fit width
|
|
872
|
+
scale_height = scale_width;
|
|
873
|
+
} else {
|
|
874
|
+
// fit height
|
|
875
|
+
scale_width = scale_height;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of);
|
|
879
|
+
newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
return [newWidth, newHeight];
|
|
883
|
+
|
|
884
|
+
} else if (this.size_divisibility !== undefined) {
|
|
885
|
+
return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility);
|
|
886
|
+
} else if (size.min_pixels !== undefined && size.max_pixels !== undefined) {
|
|
887
|
+
// Custom resize logic for Qwen2-VL models
|
|
888
|
+
const { min_pixels, max_pixels } = size;
|
|
889
|
+
const factor = this.config.patch_size * this.config.merge_size;
|
|
890
|
+
return smart_resize(srcHeight, srcWidth, factor, min_pixels, max_pixels);
|
|
891
|
+
} else {
|
|
892
|
+
throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(size)}`);
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* Resizes the image.
|
|
898
|
+
* @param {RawImage} image The image to resize.
|
|
899
|
+
* @returns {Promise<RawImage>} The resized image.
|
|
900
|
+
*/
|
|
901
|
+
async resize(image) {
|
|
902
|
+
const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size);
|
|
903
|
+
return await image.resize(newWidth, newHeight, {
|
|
904
|
+
resample: this.resample,
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/**
|
|
909
|
+
* @typedef {object} PreprocessedImage
|
|
910
|
+
* @property {HeightWidth} original_size The original size of the image.
|
|
911
|
+
* @property {HeightWidth} reshaped_input_size The reshaped input size of the image.
|
|
912
|
+
* @property {Tensor} pixel_values The pixel values of the preprocessed image.
|
|
913
|
+
*/
|
|
914
|
+
|
|
915
|
+
/**
|
|
916
|
+
* Preprocesses the given image.
|
|
917
|
+
*
|
|
918
|
+
* @param {RawImage} image The image to preprocess.
|
|
919
|
+
* @param {Object} overrides The overrides for the preprocessing options.
|
|
920
|
+
* @returns {Promise<PreprocessedImage>} The preprocessed image.
|
|
921
|
+
*/
|
|
922
|
+
async preprocess(image, {
|
|
923
|
+
do_normalize = null,
|
|
924
|
+
do_pad = null,
|
|
925
|
+
do_convert_rgb = null,
|
|
926
|
+
do_convert_grayscale = null,
|
|
927
|
+
do_flip_channel_order = null,
|
|
928
|
+
} = {}) {
|
|
929
|
+
if (this.do_crop_margin) {
|
|
930
|
+
// NOTE: Specific to nougat processors. This is done before resizing,
|
|
931
|
+
// and can be interpreted as a pre-preprocessing step.
|
|
932
|
+
image = await this.crop_margin(image);
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
const [srcWidth, srcHeight] = image.size; // original image size
|
|
936
|
+
|
|
937
|
+
// Convert image to RGB if specified in config.
|
|
938
|
+
if (do_convert_rgb ?? this.do_convert_rgb) {
|
|
939
|
+
image = image.rgb();
|
|
940
|
+
} else if (do_convert_grayscale) {
|
|
941
|
+
image = image.grayscale();
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
// TODO:
|
|
945
|
+
// For efficiency reasons, it might be best to merge the resize and center crop operations into one.
|
|
946
|
+
|
|
947
|
+
// Resize all images
|
|
948
|
+
if (this.do_resize) {
|
|
949
|
+
image = await this.resize(image);
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
// Resize the image using thumbnail method.
|
|
953
|
+
if (this.do_thumbnail) {
|
|
954
|
+
image = await this.thumbnail(image, this.size, this.resample);
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
if (this.do_center_crop) {
|
|
958
|
+
|
|
959
|
+
let crop_width;
|
|
960
|
+
let crop_height;
|
|
961
|
+
if (Number.isInteger(this.crop_size)) {
|
|
962
|
+
crop_width = this.crop_size;
|
|
963
|
+
crop_height = this.crop_size;
|
|
964
|
+
} else {
|
|
965
|
+
crop_width = this.crop_size.width;
|
|
966
|
+
crop_height = this.crop_size.height;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
image = await image.center_crop(crop_width, crop_height);
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
/** @type {HeightWidth} */
|
|
973
|
+
const reshaped_input_size = [image.height, image.width];
|
|
974
|
+
|
|
975
|
+
// NOTE: All pixel-level manipulation (i.e., modifying `pixelData`)
|
|
976
|
+
// occurs with data in the hwc format (height, width, channels),
|
|
977
|
+
// to emulate the behavior of the original Python code (w/ numpy).
|
|
978
|
+
let pixelData = Float32Array.from(image.data);
|
|
979
|
+
let imgDims = [image.height, image.width, image.channels];
|
|
980
|
+
|
|
981
|
+
if (this.do_rescale) {
|
|
982
|
+
this.rescale(pixelData);
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
if (do_normalize ?? this.do_normalize) {
|
|
986
|
+
let image_mean = this.image_mean;
|
|
987
|
+
if (!Array.isArray(this.image_mean)) {
|
|
988
|
+
image_mean = new Array(image.channels).fill(image_mean);
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
let image_std = this.image_std;
|
|
992
|
+
if (!Array.isArray(this.image_std)) {
|
|
993
|
+
image_std = new Array(image.channels).fill(image_mean);
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
if (image_mean.length !== image.channels || image_std.length !== image.channels) {
|
|
997
|
+
throw new Error(`When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
for (let i = 0; i < pixelData.length; i += image.channels) {
|
|
1001
|
+
for (let j = 0; j < image.channels; ++j) {
|
|
1002
|
+
pixelData[i + j] = (pixelData[i + j] - image_mean[j]) / image_std[j];
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// do padding after rescaling/normalizing
|
|
1008
|
+
if (do_pad ?? this.do_pad) {
|
|
1009
|
+
if (this.pad_size) {
|
|
1010
|
+
const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size);
|
|
1011
|
+
[pixelData, imgDims] = padded; // Update pixel data and image dimensions
|
|
1012
|
+
} else if (this.size_divisibility) {
|
|
1013
|
+
const [paddedWidth, paddedHeight] = enforce_size_divisibility([imgDims[1], imgDims[0]], this.size_divisibility);
|
|
1014
|
+
[pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight });
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
if (do_flip_channel_order ?? this.do_flip_channel_order) {
|
|
1019
|
+
if (imgDims[2] !== 3) {
|
|
1020
|
+
throw new Error('Flipping channel order is only supported for RGB images.');
|
|
1021
|
+
}
|
|
1022
|
+
// Convert RGB to BGR
|
|
1023
|
+
for (let i = 0; i < pixelData.length; i += 3) {
|
|
1024
|
+
const temp = pixelData[i];
|
|
1025
|
+
pixelData[i] = pixelData[i + 2];
|
|
1026
|
+
pixelData[i + 2] = temp;
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
const pixel_values = new Tensor('float32', pixelData, imgDims)
|
|
1031
|
+
.permute(2, 0, 1); // convert to channel dimension format (hwc -> chw)
|
|
1032
|
+
|
|
1033
|
+
return {
|
|
1034
|
+
original_size: [srcHeight, srcWidth],
|
|
1035
|
+
reshaped_input_size: reshaped_input_size,
|
|
1036
|
+
pixel_values,
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/**
|
|
1041
|
+
* Calls the feature extraction process on an array of images,
|
|
1042
|
+
* preprocesses each image, and concatenates the resulting
|
|
1043
|
+
* features into a single Tensor.
|
|
1044
|
+
* @param {RawImage[]} images The image(s) to extract features from.
|
|
1045
|
+
* @param {...any} args Additional arguments.
|
|
1046
|
+
* @returns {Promise<ImageProcessorResult>} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.
|
|
1047
|
+
*/
|
|
1048
|
+
async _call(images, ...args) {
|
|
1049
|
+
if (!Array.isArray(images)) {
|
|
1050
|
+
images = [images];
|
|
1051
|
+
}
|
|
1052
|
+
/** @type {PreprocessedImage[]} */
|
|
1053
|
+
const imageData = await Promise.all(images.map(x => this.preprocess(x)));
|
|
1054
|
+
|
|
1055
|
+
// Stack pixel values
|
|
1056
|
+
const pixel_values = stack(imageData.map(x => x.pixel_values), 0);
|
|
1057
|
+
|
|
1058
|
+
return {
|
|
1059
|
+
pixel_values,
|
|
1060
|
+
|
|
1061
|
+
// Original sizes of images
|
|
1062
|
+
original_sizes: imageData.map(x => x.original_size),
|
|
1063
|
+
|
|
1064
|
+
// Reshaped sizes of images, before padding or cropping
|
|
1065
|
+
reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
|
|
1070
|
+
/**
|
|
1071
|
+
* Instantiate one of the processor classes of the library from a pretrained model.
|
|
1072
|
+
*
|
|
1073
|
+
* The processor class to instantiate is selected based on the `image_processor_type` (or `feature_extractor_type`; legacy)
|
|
1074
|
+
* property of the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
|
|
1075
|
+
*
|
|
1076
|
+
* @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
|
|
1077
|
+
* - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.
|
|
1078
|
+
* Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
|
|
1079
|
+
* user or organization name, like `dbmdz/bert-base-german-cased`.
|
|
1080
|
+
* - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.
|
|
1081
|
+
* @param {import('../utils/hub.js').PretrainedOptions} options Additional options for loading the processor.
|
|
1082
|
+
*
|
|
1083
|
+
* @returns {Promise<ImageProcessor>} A new instance of the Processor class.
|
|
1084
|
+
*/
|
|
1085
|
+
static async from_pretrained(pretrained_model_name_or_path, options) {
|
|
1086
|
+
const preprocessorConfig = await getModelJSON(pretrained_model_name_or_path, IMAGE_PROCESSOR_NAME, true, options);
|
|
1087
|
+
return new this(preprocessorConfig);
|
|
1088
|
+
}
|
|
1089
|
+
}
|