Skip to content

Instantly share code, notes, and snippets.

@MichaelPHolstein
Last active April 18, 2023 17:29
Show Gist options
  • Save MichaelPHolstein/4e210eab935c47acc24feb67d3545bb6 to your computer and use it in GitHub Desktop.
Save MichaelPHolstein/4e210eab935c47acc24feb67d3545bb6 to your computer and use it in GitHub Desktop.

Revisions

  1. MichaelPHolstein revised this gist Mar 11, 2021. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions script.js
    Original file line number Diff line number Diff line change
    @@ -35,8 +35,8 @@ const backgroundRemoval = async () => {
    const newImg = ctx.createImageData(canvas.width, canvas.height)
    const newImgData = newImg.data

    segmentation.data.forEach((pixel, i) => {
    if (pixel == 1) {
    segmentation.data.forEach((segment, i) => {
    if (segment == 1) {
    newImgData[i * 4] = imgData[i * 4]
    newImgData[i * 4 + 1] = imgData[i * 4 + 1]
    newImgData[i * 4 + 2] = imgData[i * 4 + 2]
  2. MichaelPHolstein created this gist Mar 11, 2021.
    50 changes: 50 additions & 0 deletions script.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    IMAGE_SRC = './img/8.jpg'

    const loadImage = () => {
    const img = new Image()
    img.src = IMAGE_SRC

    const canvas = document.querySelector('canvas')
    const ctx = canvas.getContext('2d')

    img.addEventListener('load', () => {
    canvas.width = img.width
    canvas.height = img.height
    ctx.drawImage(img, 0, 0)
    backgroundRemoval()
    })
    }

    const backgroundRemoval = async () => {
    const canvas = document.querySelector('canvas')

    const net = await bodyPix.load({
    architecture: 'ResNet50',
    outputStride: 32,
    quantBytes: 4
    })
    const segmentation = await net.segmentPerson(canvas, {
    internalResolution: 'medium',
    segmentationThreshold: 0.7,
    scoreTreshold: 0.7
    })

    const ctx = canvas.getContext('2d')
    const { data: imgData } = ctx.getImageData(0, 0, canvas.width, canvas.height)

    const newImg = ctx.createImageData(canvas.width, canvas.height)
    const newImgData = newImg.data

    segmentation.data.forEach((pixel, i) => {
    if (pixel == 1) {
    newImgData[i * 4] = imgData[i * 4]
    newImgData[i * 4 + 1] = imgData[i * 4 + 1]
    newImgData[i * 4 + 2] = imgData[i * 4 + 2]
    newImgData[i * 4 + 3] = imgData[i * 4 + 3]
    }
    })

    ctx.putImageData(newImg, 0, 0)
    }

    loadImage()