


Douyin's very popular picture multiple-choice special effects can be quickly implemented using the front end!
This article brings you relevant knowledge about front-end picture special effects. It mainly introduces to you how the front-end implements a picture multiple-choice special effect that has been very popular on Douyin recently. It is very comprehensive and detailed. Let’s take a look at it together. I hope Help those in need.
Due to security reasons, the Nuggets did not set allow="microphone *;camera *" on the iframe tag, causing the camera to open fail! Please click "View Details" in the upper right corner to view! Or click the link below to view
//复制链接预览 https://code.juejin.cn/pen/7160886403805970445
Preface
Recently, there is a Picture Multiple Choice Question
in Douyin special effects that is particularly popular. Today, let’s talk about how to implement the front-end. Next, I will mainly talk about how to judge the left and right head swing
.
Architecture and Concept
The abstract overall implementation idea is as follows
import '@mediapipe/face_mesh';
import '@tensorflow/tfjs-core';
import '@tensorflow/tfjs-backend-webgl';
import * as faceLandmarksDetection from '@tensorflow-models/face-landmarks-detection';
Create face modelIntroduce tensorflow trained face feature point detection model, prediction
486 3D facial feature points are used to infer the approximate facial geometry of the human face.
- maxFaces
Default is 1. The maximum number of faces the model will detect. The number of faces returned can be less than the maximum (for example, when there are no faces in the input). It is strongly recommended to set this value to the maximum expected number of faces, otherwise the model will continue to search for missing faces, which may slow down performance.
- refineLandmarks
The default is false. If set to true, refines landmark coordinates around the eyes and lips, and outputs additional landmarks around the iris. (I can set
falsehere because we are not using eye coordinates)
- solutionPath
The path to the location of the am binary and model files. (It is strongly recommended to put the model into domestic object storage. The first load can save a lot of time. The size is about
10M)
async createDetector(){ const model = faceLandmarksDetection.SupportedModels.MediaPipeFaceMesh; const detectorConfig = { maxFaces:1, //检测到的最大面部数量 refineLandmarks:false, //可以完善眼睛和嘴唇周围的地标坐标,并在虹膜周围输出其他地标 runtime: 'mediapipe', solutionPath: 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh', //WASM二进制文件和模型文件所在的路径 }; this.detector = await faceLandmarksDetection.createDetector(model, detectorConfig); }
##人Face recognition
The faces list returned contains the detected faces for each face in the image. If the model cannot detect any faces, the list will be empty. For each face, it contains a bounding box of the detected face, and an array of keypoints. MediaPipeFaceMesh returns 468 keypoints. Each keypoint contains x and y, as well as a name.
Now you can use the detector to detect faces. The estimateFaces method accepts images and videos in a variety of formats, including:HTMLVideoElement,
HTMLImageElement
,HTMLCanvasElement
, andTensor3D
.
- flipHorizontal
- Optional. Default is false. When image data comes from a camera, the result must be flipped horizontally.
async renderPrediction() { var video = this.$refs['video']; var canvas = this.$refs['canvas']; var context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); const Faces = await this.detector.estimateFaces(video, { flipHorizontal:false, //镜像 }); if (Faces.length > 0) { this.log(`检测到人脸`); } else { this.log(`没有检测到人脸`); } }
This box represents the bounding box of the face in the image pixel space, xMin, xMax represent x-bounds, yMin, yMax represent y-bounds, width, height Represents the dimensions of the bounding box.
For keypoints, x and y represent the actual keypoint location in the image pixel space. z represents the depth at which the center of the head is the origin. The smaller the value, the closer the key point is to the camera. The size of Z uses roughly the same scale as x.
This name provides a label for some key points, such as "lips", "left eye", etc. Note that not every keypoint has a label.
How to judge
Find the two points on the face
The first point
The center position of the foreheadThe second point Chin center position
<pre class='brush:php;toolbar:false;'>const place1 = (face.keypoints || []).find((e,i)=>i===10); //额头位置
const place2 = (face.keypoints || []).find((e,i)=>i===152); //下巴位置
/*
x1,y1
|
|
|
x2,y2 -------|------- x4,y4
x3,y3
*/
const [x1,y1,x2,y2,x3,y3,x4,y4] = [
place1.x,place1.y,
0,place2.y,
place2.x,place2.y,
this.canvas.width, place2.y
];</pre>
Calculate
forehead center position and
chin center position ,y3,x4,y4
getAngle({ x: x1, y: y1 }, { x: x2, y: y2 }){ const dot = x1 * x2 + y1 * y2 const det = x1 * y2 - y1 * x2 const angle = Math.atan2(det, dot) / Math.PI * 180 return Math.round(angle + 360) % 360 } const angle = this.getAngle({ x: x1 - x3, y: y1 - y3, }, { x: x2 - x3, y: y2 - y3, }); console.log('角度',angle)
通过获取角度,通过角度的大小来判断左右摆头。
推荐:《web前端开发视频教程》
The above is the detailed content of Douyin's very popular picture multiple-choice special effects can be quickly implemented using the front end!. For more information, please follow other related articles on the PHP Chinese website!

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Mac version
God-level code editing software (SublimeText3)