|
import { AutoProcessor, VitMatteForImageMatting, RawImage, Tensor, cat } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.2'; |
|
|
|
env.allowLocalModels = false; |
|
|
|
|
|
const processor = await AutoProcessor.from_pretrained('Xenova/vitmatte-small-composition-1k'); |
|
const model = await VitMatteForImageMatting.from_pretrained('Xenova/vitmatte-small-composition-1k'); |
|
|
|
|
|
const image = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_image.png'); |
|
const trimap = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_trimap.png'); |
|
|
|
|
|
const inputs = await processor(image, trimap); |
|
|
|
|
|
const { alphas } = await model(inputs); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const imageTensor = new Tensor( |
|
'uint8', |
|
new Uint8Array(image.data), |
|
[image.height, image.width, image.channels] |
|
).transpose(2, 0, 1); |
|
|
|
|
|
const alphaChannel = alphas |
|
.squeeze(0) |
|
.mul_(255) |
|
.clamp_(0, 255) |
|
.round_() |
|
.to('uint8'); |
|
|
|
|
|
const imageData = cat([imageTensor, alphaChannel], 0); |
|
|
|
|
|
const outputImage = RawImage.fromTensor(imageData); |
|
outputImage.save('output.png'); |
|
|
|
|