npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@01works/mediapipe

v0.10.21-250425.63951

Published

Mediapipe tools for all environments

Readme

MediaPipe 라이브러리

MediaPipe 비전 태스크를 쉽게 사용할 수 있는 래퍼 라이브러리입니다.

설치

npm install @01works/mediapipe

기능

  • 얼굴 랜드마크 감지 (FaceLandmarkerTask)
  • 이미지 세그멘테이션 (ImageSegmenterTask)
  • 객체 감지 (ObjectDetectorTask)
  • 자동 에러 처리 및 리소스 관리
  • 성능 모니터링 (FPS, 프레임 처리 시간)
  • 다양한 시각화 도구 (바운딩 박스, 마스크 등)
  • 자동 및 수동 프레임 처리 지원
  • 비디오, 이미지, 캔버스 입력 지원

사용 예시

얼굴 랜드마크 감지

자동 프레임 처리 모드

import {
  FaceLandmarkerTask,
  TaskResult,
  FaceLandmarkerResult,
  TaskStatus,
} from '@01works/mediapipe'

// 얼굴 랜드마크 태스크 생성
const faceLandmarker = new FaceLandmarkerTask(
  {
    enableWebGPU: true, // WebGPU 사용 (기본값: false)
    numFaces: 1, // 감지할 얼굴 수 (기본값: 1)
    autoProcess: true, // 자동 프레임 처리 활성화 (기본값: true)
  },
  (result: TaskResult<FaceLandmarkerResult>) => {
    // 결과 처리
    if (result.data) {
      console.log('얼굴 랜드마크:', result.data.faceLandmarks)
    }
  },
)

// 태스크 초기화 및 시작
try {
  await faceLandmarker.initialize()
  await faceLandmarker.initializeVideoStream('user') // 카메라 스트림 초기화
  await faceLandmarker.start()

  // 얼굴 감지 여부 확인
  if (faceLandmarker.isFaceDetected()) {
    console.log('얼굴이 감지되었습니다!')
  }

  // 특정 얼굴 부위 데이터 가져오기
  const eyeData = faceLandmarker.getFeatureData('left_eye')
  if (eyeData) {
    console.log('왼쪽 눈 위치:', eyeData[0].position)
  }

  // 성능 정보 확인
  const { fps, processingTime } = faceLandmarker.getPerformanceInfo()
  console.log(
    `FPS: ${fps.toFixed(1)}, 처리 시간: ${processingTime.toFixed(2)}ms`,
  )
} catch (error) {
  console.error('얼굴 랜드마크 오류:', error)
} finally {
  // 사용 완료 후 정리
  await faceLandmarker.dispose()
}

수동 프레임 처리 모드

import {
  FaceLandmarkerTask,
  TaskResult,
  FaceLandmarkerResult,
} from '@01works/mediapipe'

// 얼굴 랜드마크 태스크 생성 (자동 프레임 처리 비활성화)
const faceLandmarker = new FaceLandmarkerTask(
  {
    enableWebGPU: true,
    numFaces: 1,
    autoProcess: false, // 자동 프레임 처리 비활성화
  },
  (result: TaskResult<FaceLandmarkerResult>) => {
    // 결과 콜백 (선택적)
  },
)

// 태스크 초기화
await faceLandmarker.initialize()

// 이미지 요소에서 얼굴 감지
const image = document.getElementById('input-image') as HTMLImageElement
const result = await faceLandmarker.processSingleFrame(image)

if (result) {
  console.log('감지된 얼굴:', result.faceLandmarks)
}

// 비디오 프레임 처리 (requestAnimationFrame 사용)
const video = document.getElementById('input-video') as HTMLVideoElement
const processVideoFrame = async () => {
  if (video.readyState >= 2) {
    const result = await faceLandmarker.processSingleFrame(video)
    if (result) {
      // 결과 처리
    }
  }
  requestAnimationFrame(processVideoFrame)
}
requestAnimationFrame(processVideoFrame)

// 사용 완료 후 정리
await faceLandmarker.dispose()

이미지 세그멘테이션

자동 프레임 처리 모드

import {
  ImageSegmenterTask,
  ImageSegmenterModelType,
  TaskResult,
  ImageSegmenterResult,
} from '@01works/mediapipe'

// 이미지 세그멘터 태스크 생성
const imageSegmenter = new ImageSegmenterTask(
  {
    modelType: ImageSegmenterModelType.SELFIE_SEGMENTER, // 모델 타입 (기본값: SELFIE_SEGMENTER)
    enableWebGPU: true, // WebGPU 사용 (기본값: false)
    autoProcess: true, // 자동 프레임 처리 활성화 (기본값: true)
  },
  (result: TaskResult<ImageSegmenterResult>) => {
    // 결과 처리
    if (result.data?.categoryMask) {
      console.log('세그멘테이션 마스크 크기:', result.data.categoryMask.length)
    }
  },
)

// 태스크 초기화 및 시작
try {
  await imageSegmenter.initialize()
  await imageSegmenter.initializeVideoStream('user') // 카메라 스트림 초기화
  await imageSegmenter.start()

  // 마스크 처리 옵션 설정
  imageSegmenter.setDefaultMaskOptions({
    threshold: 0.5,
    foregroundColor: 'rgba(255, 0, 0, 0.5)',
    backgroundColor: 'rgba(0, 0, 0, 0)',
    opacity: 0.7,
  })

  // 마스크 그리기
  const maskCanvas = imageSegmenter.drawMask()
  if (maskCanvas) {
    document.body.appendChild(maskCanvas)
  }
} catch (error) {
  console.error('이미지 세그멘테이션 오류:', error)
} finally {
  // 사용 완료 후 정리
  await imageSegmenter.dispose()
}

수동 프레임 처리 모드

import { ImageSegmenterTask, ImageSegmenterModelType } from '@01works/mediapipe'

// 이미지 세그멘터 태스크 생성 (자동 프레임 처리 비활성화)
const imageSegmenter = new ImageSegmenterTask({
  modelType: ImageSegmenterModelType.SELFIE_SEGMENTER,
  enableWebGPU: true,
  autoProcess: false, // 자동 프레임 처리 비활성화
})

// 태스크 초기화
await imageSegmenter.initialize()

// 이미지 요소에서 세그멘테이션 수행
const image = document.getElementById('input-image') as HTMLImageElement
const result = await imageSegmenter.processSingleFrame(image)

if (result?.categoryMask) {
  // 마스크 데이터 직접 처리
  const imageData = imageSegmenter.processMaskData(
    result.categoryMask,
    result.width,
    result.height,
    (value, x, y, index) => {
      // 각 픽셀에 대한 처리 로직
      return value > 0.5
        ? { r: 255, g: 0, b: 0, a: 0.7 } // 전경
        : { r: 0, g: 0, b: 0, a: 0 } // 배경
    },
  )

  // 이미지 데이터를 캔버스에 그리기
  const canvas = document.getElementById('output-canvas') as HTMLCanvasElement
  const ctx = canvas.getContext('2d')
  if (ctx) {
    ctx.putImageData(imageData, 0, 0)
  }
}

// 사용 완료 후 정리
await imageSegmenter.dispose()

객체 감지

자동 프레임 처리 모드

import {
  ObjectDetectorTask,
  TaskResult,
  ObjectDetectorResult,
} from '@01works/mediapipe'

// 객체 감지 태스크 생성
const objectDetector = new ObjectDetectorTask(
  {
    enableWebGPU: true, // WebGPU 사용 (기본값: false)
    scoreThreshold: 0.5, // 감지 점수 임계값 (기본값: 0.5)
    autoProcess: true, // 자동 프레임 처리 활성화 (기본값: true)
  },
  (result: TaskResult<ObjectDetectorResult>) => {
    // 결과 처리
    if (result.data) {
      console.log('감지된 객체:', result.data.detections)
    }
  },
)

// 태스크 초기화 및 시작
try {
  await objectDetector.initialize()
  await objectDetector.initializeVideoStream('environment') // 후면 카메라 스트림 초기화
  await objectDetector.start()

  // 바운딩 박스 옵션 설정
  objectDetector.setDefaultBoxOptions({
    lineWidth: 3,
    lineColor: 'green',
    fillColor: 'rgba(0, 255, 0, 0.2)',
    showLabels: true,
    showScores: true,
  })

  // 바운딩 박스 그리기
  objectDetector.drawBoundingBoxes()

  // 특정 카테고리 필터링
  const persons = objectDetector.filterByCategories(['person'])
  console.log('감지된 사람 수:', persons.length)

  // 높은 점수의 객체만 필터링
  const highConfidenceObjects = objectDetector.filterByScore(0.8)
  console.log('높은 신뢰도 객체 수:', highConfidenceObjects.length)
} catch (error) {
  console.error('객체 감지 오류:', error)
} finally {
  // 사용 완료 후 정리
  await objectDetector.dispose()
}

수동 프레임 처리 모드

import { ObjectDetectorTask } from '@01works/mediapipe'

// 객체 감지 태스크 생성 (자동 프레임 처리 비활성화)
const objectDetector = new ObjectDetectorTask({
  enableWebGPU: true,
  scoreThreshold: 0.5,
  autoProcess: false, // 자동 프레임 처리 비활성화
})

// 태스크 초기화
await objectDetector.initialize()

// 이미지 요소에서 객체 감지
const image = document.getElementById('input-image') as HTMLImageElement
const result = await objectDetector.processSingleFrame(image)

if (result?.detections.length) {
  console.log('감지된 객체:', result.detections)

  // 특정 캔버스에 바운딩 박스 그리기
  const canvas = document.getElementById('output-canvas') as HTMLCanvasElement
  objectDetector.drawBoundingBoxes(canvas)
}

// 사용 완료 후 정리
await objectDetector.dispose()

에러 처리

모든 태스크는 에러 처리를 위한 메커니즘을 제공합니다:

try {
  await faceLandmarker.initialize()
} catch (error) {
  console.error('초기화 오류:', error)
}

// 또는 결과 콜백에서 에러 확인
faceLandmarker.setResultCallback((result) => {
  if (result.error) {
    console.error('처리 오류:', result.error)
    return
  }

  // 정상 결과 처리
  console.log('결과:', result.data)
})

상태 관리

태스크의 상태를 확인할 수 있습니다:

import { TaskStatus } from '@01works/mediapipe'

const status = faceLandmarker.getStatus()
if (status === TaskStatus.READY) {
  console.log('태스크가 준비되었습니다.')
} else if (status === TaskStatus.ERROR) {
  console.error('태스크 오류:', faceLandmarker.getError())
}

성능 모니터링

태스크의 성능을 모니터링할 수 있습니다:

// 현재 FPS 가져오기
const fps = faceLandmarker.getFPS()
console.log(`현재 FPS: ${fps.toFixed(1)}`)

// 프레임 처리 시간 가져오기
const processingTime = faceLandmarker.getFrameProcessingTime()
console.log(`프레임 처리 시간: ${processingTime.toFixed(2)}ms`)

// 성능 정보 한 번에 가져오기
const { fps, processingTime } = faceLandmarker.getPerformanceInfo()

캔버스 및 비디오 접근

태스크의 캔버스와 비디오 요소에 접근할 수 있습니다:

// 캔버스 가져오기
const canvas = faceLandmarker.getCanvas()
if (canvas) {
  document.body.appendChild(canvas)
}

// 비디오 요소 가져오기
const video = faceLandmarker.getVideo()

그리기 옵션 설정

비디오나 이미지를 캔버스에 그리는 방식을 설정할 수 있습니다:

faceLandmarker.setDrawOptions({
  fit: 'cover', // 'cover', 'contain', 'fill' 중 하나
  objectPosition: 'center', // 'center', 'top', 'bottom', 'left', 'right' 중 하나
})

자동 프레임 처리 설정

태스크의 자동 프레임 처리 여부를 동적으로 변경할 수 있습니다:

// 자동 프레임 처리 비활성화
faceLandmarker.setAutoProcess(false)

// 자동 프레임 처리 활성화
faceLandmarker.setAutoProcess(true)

// 현재 자동 프레임 처리 상태 확인
const isAutoProcessing = faceLandmarker.isAutoProcessing()

리소스 관리

모든 태스크는 사용 완료 후 반드시 정리해야 합니다:

await faceLandmarker.dispose()

라이선스

MIT