Views
No views yet
npm i @huggingface/transformersCLIPSegForImageSegmentation model.1import { AutoTokenizer, AutoProcessor, CLIPSegForImageSegmentation, RawImage } from '@huggingface/transformers';
2
3// Load tokenizer, processor, and model
4const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clipseg-rd64-refined');
5const processor = await AutoProcessor.from_pretrained('Xenova/clipseg-rd64-refined');
6const model = await CLIPSegForImageSegmentation.from_pretrained('Xenova/clipseg-rd64-refined');
7
8// Run tokenization
9const texts = ['a glass', 'something to fill', 'wood', 'a jar'];
10const text_inputs = tokenizer(texts, { padding: true, truncation: true });
11
12// Read image and run processor
13const image = await RawImage.read('https://github.com/timojl/clipseg/blob/master/example_image.jpg?raw=true');
14const image_inputs = await processor(image);
15
16// Run model with both text and pixel inputs
17const { logits } = await model({ ...text_inputs, ...image_inputs });
18// logits: Tensor {
19// dims: [4, 352, 352],
20// type: 'float32',
21// data: Float32Array(495616)[ ... ],
22// size: 495616
23// }1// Visualize images
2const preds = logits
3 .unsqueeze_(1)
4 .sigmoid_()
5 .mul_(255)
6 .round_()
7 .to('uint8');
8
9for (let i = 0; i < preds.dims[0]; ++i) {
10 const img = RawImage.fromTensor(preds[i]);
11 img.save(`prediction_${i}.png`);
12}| Original | "a glass" | "something to fill" | "wood" | "a jar" |
|---|---|---|---|---|
![]() | ![]() | ![]() | ![]() | ![]() |
onnx).