3.0.0 • Published 4 months ago

vision-camera-plugin-face-detector v3.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

vision-camera-face-detector-v3

GitHub license npm version

Description

react-native-vision-camera-face-detector-v3 is a React Native library that integrates with the Vision Camera module to provide face detection functionality. It allows you to easily detect faces in real-time using the front camera and visualize the detected faces on the screen. This also include a function called frameResize that fixes the mismatch between the frame and view size.

Features

  • Real-time face detection using the front camera
  • Integration with the Vision Camera module
  • Adjustable face visualization with customizable styles
  • Frame Resize Functionality: Includes a function called frameResize() that fixes the mismatch between the frame and view size, allowing for accurate face visualization on the screen.

Installation

yarn add vision-camera-face-detector-v3

Usage

import { StyleSheet, Text, View } from 'react-native';
import React, { useEffect, useState } from 'react';
import {
  Camera,
  useCameraDevice,
  useFrameProcessor,
} from 'react-native-vision-camera';
import { scanFaces, frameResize } from 'vision-camera-face-detector-v3';
import { Worklets } from 'react-native-worklets-core';

export default function App() {
  const device = useCameraDevice('front');

  React.useEffect(() => {
    (async () => {
      const status = await Camera.requestCameraPermission();
      console.log({ status });
    })();
  }, [device]);

  const frameProcessor = useFrameProcessor((frame) => {
    'worklet';

    try {
      const scannedFaces = scanFaces(frame, {});
      console.log(scannedFaces);
    } catch (error) {
      console.error({ error });
    }
  }, []);

  if (device == null) return <Text>No Device</Text>;
  if (device) {
    return (
      <View style={{ position: 'relative', flex: 1 }}>
        <Camera
          style={StyleSheet.absoluteFill}
          device={device}
          isActive={!!device}
          frameProcessor={frameProcessor}
          //pixel format should be either yuv or rgb
          pixelFormat="yuv"
        />
      </View>
    );
  }
}

Configuration

Ensure that you have the necessary permissions for camera usage. The library includes a function Camera.requestCameraPermission() for requesting camera permissions.

  • Also make sure that the pixelFormat is not set to native, as the frameProccessor needs to be either yuv or rgb

Frame Resize Fix

The frameResize() function provided by vision-camera-face-detector-v3 allows you to adjust the detected face coordinates to match the dimensions of your view. This is particularly useful when visualizing the detected faces on the screen. Here's an example of how to use it in conjunction with the React Native Vision Camera:

Parameters:

  • faces: An array containing face data obtained from the face detection process.
  • frameHeight: Height of the camera frame.
  • frameWidth: Width of the camera frame.
  • viewHeight: Height of the view where faces will be visualized.
  • viewWidth: Width of the view where faces will be visualized.
import { StyleSheet, Text, View } from 'react-native';
import React, { useEffect, useState } from 'react';
import {
  Camera,
  useCameraDevice,
  useFrameProcessor,
} from 'react-native-vision-camera';
import { scanFaces, frameResize } from 'vision-camera-face-detector-v3';
import { Worklets } from 'react-native-worklets-core';

export default function App() {
  const device = useCameraDevice('front');
  const [face, setFace] = useState(null);
  const [fixedFace, setFixedFace] = useState(null);
  const [viewDimensions, setViewDimensions] = useState({ height: 0, width: 0 });
  const [frameDimensions, setFrameDimensions] = useState({
    height: 0,
    width: 0,
  });

  React.useEffect(() => {
    (async () => {
      const status = await Camera.requestCameraPermission();
      console.log({ status });
    })();
  }, [device]);

  const onFaceDetected = Worklets.createRunInJsFn((faces, frameInfo) => {
    setFrameDimensions(frameInfo);
    if (faces.length > 0) {
      setFace(faces);
    } else {
      setFace(null);
    }
  });

  const frameProcessor = useFrameProcessor((frame) => {
    'worklet';

    try {
      const scannedFaces = scanFaces(frame, {});
      if (scannedFaces.length > 0) {
        const { height, width } = frame;
        const frameInfo = { height, width };
        onFaceDetected(scannedFaces, frameInfo);
      }
    } catch (error) {
      console.error({ error });
    }
  }, []);

  useEffect(() => {
    if (face) {
      const fix = frameResize(
        face,
        frameDimensions.height,
        frameDimensions.width,
        viewDimensions.height,
        viewDimensions.width
      );
      setFixedFace(fix);
    }
    return () => {};
  }, [face]);

  if (device == null) return <Text>No Device</Text>;
  if (device) {
    return (
      <View style={{ position: 'relative', flex: 1 }}>
        <Camera
          enableFpsGraph
          onLayout={(e) => {
            setViewDimensions({
              height: e.nativeEvent.layout.height,
              width: e.nativeEvent.layout.width,
            });
          }}
          style={StyleSheet.absoluteFill}
          device={device}
          isActive={!!device}
          frameProcessor={frameProcessor}
          //pixel format should be either yuv or rgb
          pixelFormat="yuv"
        />
        {fixedFace != null && (
          <View
            style={{
              borderColor: 'red',
              borderWidth: 3,
              width: fixedFace.bounds.height,
              height: fixedFace.bounds.width,
              left: fixedFace.bounds.left,
              top: fixedFace.bounds.top,
              position: 'absolute',
              zIndex: 100,
            }}
          />
        )}
      </View>
    );
  }
}

Support and Contribution

If you encounter any issues or have suggestions, feel free to open an issue or submit a pull request.

Certainly! You can add a "Credits" section to your README to acknowledge the repository vision-camera-face-detector-tmp. Here's an example:

Credits

This project utilizes the vision-camera-face-detector-tmp repository, which provides essential functionalities for face detection. We extend our gratitude to the contributors and maintainers of vision-camera-face-detector-tmp for their valuable work.

Please check out their repository for additional details and consider giving them a star to show your appreciation.

JSONStreamabort-controlleracceptsacornacorn-jsxacorn-walkadd-streamagent-baseaggregate-errorajvanseransi-alignansi-escapesansi-fragmentsansi-regexansi-stylesanymatchappdirsjsargargparsearray-buffer-byte-lengtharray-ifyarray-includesarray-unionarray.prototype.flatarray.prototype.flatmaparray.prototype.maparray.prototype.tosortedarraybuffer.prototype.slicearrifyasapast-typesastral-regexasyncasync-limiterasync-retryasynciterator.prototypeavailable-typed-arraysbabel-corebabel-jestbabel-plugin-istanbulbabel-plugin-jest-hoistbabel-plugin-polyfill-corejs2babel-plugin-polyfill-corejs3babel-plugin-polyfill-regeneratorbabel-plugin-syntax-trailing-function-commasbabel-plugin-transform-flow-enumsbabel-preset-current-node-syntaxbabel-preset-fbjsbabel-preset-jestbalanced-matchbase64-jsbasic-ftpbefore-after-hookbig-integerblboxenbplist-parserbrace-expansionbracesbrowserslistbserbufferbuffer-frombundle-namebytescacheable-lookupcacheable-requestcall-bindcaller-callsitecaller-pathcallsitescamelcasecamelcase-keyscaniuse-litechalkchar-regexchardetci-infocjs-module-lexerclean-stackcli-boxescli-cursorcli-spinnerscli-widthcliuicloneclone-deepcocollect-v8-coveragecolor-convertcolor-namecolorettecommand-existscommandercommitlintcommondircompare-funccompressiblecompressionconcat-mapconcat-streamconfig-chainconfigstoreconnectconventional-changelogconventional-changelog-angularconventional-changelog-atomconventional-changelog-codemirrorconventional-changelog-conventionalcommitsconventional-changelog-coreconventional-changelog-emberconventional-changelog-eslintconventional-changelog-expressconventional-changelog-jqueryconventional-changelog-jshintconventional-changelog-preset-loaderconventional-changelog-writerconventional-commits-filterconventional-commits-parserconventional-recommended-bumpconvert-source-mapcore-js-compatcore-util-iscosmiconfigcreate-jestcreate-requirecross-spawncrypto-random-stringcsstypedargsdata-uri-to-bufferdayjsdebugdecamelizedecamelize-keysdecompress-responsededentdeep-extenddeep-isdeepmergedefault-browserdefault-browser-iddefaultsdefer-to-connectdefine-data-propertydefine-lazy-propdefine-propertiesdegeneratordeldenodeifydepddeprecated-react-native-prop-typesdeprecationdestroydetect-newlinediffdiff-sequencesdir-globdoctrinedot-propeastasianwidthee-firstelectron-to-chromiumemitteryemoji-regexencodeurlend-of-streamenvinfoerror-exerror-stack-parsererrorhandleres-abstractes-array-method-boxes-properlyes-get-iteratores-iterator-helperses-set-tostringtages-shim-unscopableses-to-primitiveescaladeescape-goatescape-htmlescape-string-regexpescodegeneslinteslint-config-prettiereslint-plugin-eslint-commentseslint-plugin-ft-floweslint-plugin-jesteslint-plugin-prettiereslint-plugin-reacteslint-plugin-react-hookseslint-plugin-react-nativeeslint-plugin-react-native-globalseslint-scopeeslint-visitor-keysespreeesprimaesqueryesrecurseestraverseesutilsetagevent-target-shimexecaexitexpectexternal-editorfast-deep-equalfast-difffast-globfast-json-stable-stringifyfast-levenshteinfast-xml-parserfastqfb-watchmanfetch-blobfiguresfile-entry-cachefill-rangefinalhandlerfind-cache-dirfind-upflat-cacheflattedflow-enums-runtimeflow-parserfor-eachform-data-encoderformdata-polyfillfreshfs-extrafs.realpathfseventsfunction-bindfunction.prototype.namefunctions-have-namesgensyncget-caller-fileget-intrinsicget-package-typeget-streamget-symbol-descriptionget-urigit-raw-commitsgit-semver-tagsgit-upgit-url-parseglobglob-parentglobal-dirsglobalsglobalthisglobbygopdgotgraceful-fsgraphemerhandlebarshard-rejectionhashas-bigintshas-flaghas-property-descriptorshas-protohas-symbolshas-tostringtaghas-yarnhermes-estreehermes-parserhermes-profile-transformerhosted-git-infohtml-escaperhttp-cache-semanticshttp-errorshttp-proxy-agenthttp2-wrapperhttps-proxy-agenthuman-signalshuskyiconv-liteieee754ignoreimage-sizeimport-freshimport-lazyimport-localimurmurhashindent-stringinflightinheritsiniinquirerinternal-slotinterpretinvariantipis-absoluteis-argumentsis-array-bufferis-arrayishis-async-functionis-bigintis-boolean-objectis-callableis-ciis-core-moduleis-date-objectis-directoryis-dockeris-extglobis-finalizationregistryis-fullwidth-code-pointis-generator-fnis-generator-functionis-git-dirtyis-git-repositoryis-globis-inside-containeris-installed-globallyis-interactiveis-mapis-negative-zerois-npmis-numberis-number-objectis-objis-path-cwdis-path-insideis-plain-objis-plain-objectis-regexis-relativeis-setis-shared-array-bufferis-sshis-streamis-stringis-symbolis-text-pathis-typed-arrayis-typedarrayis-unc-pathis-unicode-supportedis-weakmapis-weakrefis-weaksetis-windowsis-wslis-yarn-globalisarrayisexeisobjectissue-parseristanbul-lib-coverageistanbul-lib-instrumentistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsiterate-iteratoriterate-valueiterator.prototypejestjest-changed-filesjest-circusjest-clijest-configjest-diffjest-docblockjest-eachjest-environment-nodejest-get-typejest-haste-mapjest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-snapshotjest-utiljest-validatejest-watcherjest-workerjoijs-tokensjs-yamljsc-androidjsc-safe-urljscodeshiftjsescjson-bufferjson-parse-better-errorsjson-parse-even-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjson-stringify-safejson5jsonfilejsonparsejsx-ast-utilskeyvkind-ofkleurlatest-versionlevenlevnlines-and-columnslocate-pathlodashlodash.camelcaselodash.capitalizelodash.debouncelodash.escaperegexplodash.isfunctionlodash.isplainobjectlodash.isstringlodash.kebabcaselodash.mergelodash.mergewithlodash.snakecaselodash.startcaselodash.throttlelodash.uniqlodash.uniqbylodash.upperfirstlog-symbolslogkittyloose-envifylowercase-keyslru-cachemacos-releasemake-dirmake-errormakeerrormap-objmemoize-onemeowmerge-streammerge2metrometro-babel-transformermetro-cachemetro-cache-keymetro-configmetro-coremetro-file-mapmetro-inspector-proxymetro-minify-tersermetro-minify-uglifymetro-react-native-babel-presetmetro-react-native-babel-transformermetro-resolvermetro-runtimemetro-source-mapmetro-symbolicatemetro-transform-pluginsmetro-transform-workermicromatchmimemime-dbmime-typesmimic-fnmimic-responsemin-indentminimatchminimistminimist-optionsmkdirpmsmute-streamnatural-comparenatural-compare-litenegotiatorneo-asyncnetmasknew-github-release-urlnocachenode-abort-controllernode-dirnode-domexceptionnode-fetchnode-int64node-releasesnode-stream-zipnormalize-package-datanormalize-pathnormalize-urlnpm-run-pathnullthrowsob1object-assignobject-inspectobject-keysobject.assignobject.entriesobject.fromentriesobject.hasownobject.valueson-finishedon-headersonceonetimeopenoptionatororaos-nameos-tmpdirp-cancelablep-limitp-locatep-mapp-trypac-proxy-agentpac-resolverpackage-jsonparent-moduleparse-jsonparse-pathparse-urlparseurlpath-existspath-is-absolutepath-keypath-parsepath-typepicocolorspicomatchpifypiratespkg-dirpod-installprelude-lsprettierprettier-linter-helperspretty-formatprocess-nextick-argspromisepromise.allsettledpromptsprop-typesproto-listprotocolsproxy-agentproxy-from-envpumppunycodepupapure-randqueuequeue-microtaskquick-lrurange-parserrcreactreact-devtools-corereact-isreact-nativereact-native-builder-bobreact-native-vision-camerareact-native-worklets-corereact-refreshreact-shallow-rendererread-pkgread-pkg-upreadable-streamreadlinerecastrechoirredentreflect.getprototypeofregenerateregenerate-unicode-propertiesregenerator-runtimeregenerator-transformregexp.prototype.flagsregexpu-coreregistry-auth-tokenregistry-urlregjsparserrelease-itrequire-directoryrequire-from-stringrequire-main-filenameresolveresolve-alpnresolve-cwdresolve-fromresolve-globalresolve.exportsresponselikerestore-cursorretryreusifyrimrafrun-applescriptrun-asyncrun-parallelrxjssafe-array-concatsafe-buffersafe-regex-testsafer-bufferschedulersemversemver-diffsendserialize-errorserve-staticset-blockingset-function-namesetprototypeofshallow-cloneshebang-commandshebang-regexshell-quoteshelljsside-channelsignal-exitsisteransislashslice-ansismart-buffersockssocks-proxy-agentsource-mapsource-map-supportspdx-correctspdx-exceptionsspdx-expression-parsespdx-license-idssplit2sprintf-jsstack-utilsstackframestacktrace-parserstatusesstdin-discarderstop-iteration-iteratorstring-hash-64string-lengthstring-natural-comparestring-widthstring.prototype.matchallstring.prototype.trimstring.prototype.trimendstring.prototype.trimstartstring_decoderstrip-ansistrip-bomstrip-final-newlinestrip-indentstrip-json-commentsstrnumsudo-promptsupports-colorsupports-preserve-symlinks-flagsynckittemptersertest-excludetext-extensionstext-tablethroatthroughthrough2titleizetmptmplto-fast-propertiesto-regex-rangetoidentifiertr46trim-newlinestslibtsutilstype-checktype-detecttype-festtyped-array-buffertyped-array-byte-lengthtyped-array-byte-offsettyped-array-lengthtypedarraytypedarray-to-buffertypescriptuglify-esuglify-jsunbox-primitiveunc-path-regexundici-typesunicode-canonical-property-names-ecmascriptunicode-match-property-ecmascriptunicode-match-property-value-ecmascriptunicode-property-aliases-ecmascriptunique-stringuniversal-user-agentuniversalifyunpipeuntildifyupdate-browserslist-dbupdate-notifieruri-jsurl-joinuse-sync-external-storeutil-deprecateutils-mergev8-compile-cache-libv8-to-istanbulvalidate-npm-package-licensevaryvlqwalkerwcwidthweb-streams-polyfillwebidl-conversionswhatwg-fetchwhatwg-urlwhichwhich-boxed-primitivewhich-builtin-typewhich-collectionwhich-modulewhich-typed-arraywidest-linewildcard-matchwindows-releasewordwrapwrap-ansiwrappywrite-file-atomicwsxdg-basedirxtendy18nyallistyamlyargsyargs-parserynyocto-queue
3.0.0

4 months ago