前端 基于TensorFlow.js与Web Worker的智能证件照生成方案 - putImageData(outputImageData, 0, 0)

📅 2026-11-30 👤 拼多多助力营销技巧 📂 pdd帮助力 👁️ 399 次阅读

功能简介

本文基于TensorFlow.js与Web Worker实现了常用的“证件照”功能,可以对照片实现抠图并替换背景。值得一提的是,正常抠图的操作应该由后端进行,这里只是主要演示该功能实现步骤,并不建议该功能由前端全权处理。 限于个人技术能力有限,当前功能实现的并不怎么良好,抠图不够精细且缺少对图片处理后的画质修复等操作,这些还请诸位大佬见谅了。

效果演示

原图

## 效果图

功能亮点

智能人像分割:基于BodyPix模型实现精准人像抠图实时背景替换:支持动态颜色选择和边缘优化算法多尺寸适配:预设常用证件照尺寸+自定义毫米级精度高性能处理:Web Worker独立线程保障主线程流畅性模型加载优化:按需加载MobileNetV1量化模型边缘平滑算法:卷积核模糊处理提升证件照专业度

主要逻辑详解

加载模型

// 初始化模型

async function loadModel() {

try {

console.log('开始加载模型...');

if (!bodyPixModel) {

bodyPixModel = await bodyPix.load({

architecture: 'MobileNetV1',

outputStride: 16,

multiplier: 0.75,

quantBytes: 2

});

console.log('模型加载成功');

}

return bodyPixModel;

} catch (error) {

console.error('模型加载失败:', error);

throw error;

}

}

该方法的主要作用便是加载bodyPixModel模型,这里用到的模型为MobileNetV1。关于bodyPix模型下load方法的各种参数可以自行搜索一下官方文档查看。

人像分割核心流程

// 使用 BodyPix 进行人像分割

console.log('开始人像分割...');

const segmentation = await model.segmentPerson(imgDataForSegmentation, {

flipHorizontal: false,

internalResolution: 'medium',

segmentationThreshold: config.segmentationThreshold || 0.7

});

console.log('人像分割完成');

// 创建输出 Canvas

const outputCanvas = new OffscreenCanvas(img.width, img.height);

const outputCtx = outputCanvas.getContext('2d');

// 绘制原始图片

outputCtx.drawImage(img, 0, 0);

// 应用背景色

const backgroundColor = hexToRgb(config.bgColor);

const outputImageData = outputCtx.getImageData(0, 0, img.width, img.height);

const pixelData = outputImageData.data;

// 应用分割结果

for (let i = 0; i < segmentation.data.length; i++) {

const n = i * 4;

if (segmentation.data[i] === 0) { // 背景部分

pixelData[n] = backgroundColor.r;

pixelData[n + 1] = backgroundColor.g;

pixelData[n + 2] = backgroundColor.b;

pixelData[n + 3] = 255;

}

}

outputCtx.putImageData(outputImageData, 0, 0);

这里的主要逻辑是分割图像及应用选择的背景色。

边缘平滑算法

// 边缘平滑处理

async function smoothEdges(ctx, width, height) {

const imageData = ctx.getImageData(0, 0, width, height);

const data = imageData.data;

const kernel = [

[0.075, 0.124, 0.075],

[0.124, 0.204, 0.124],

[0.075, 0.124, 0.075]

];

const tempData = new Uint8ClampedArray(data);

for (let y = 1; y < height - 1; y++) {

for (let x = 1; x < width - 1; x++) {

const idx = (y * width + x) * 4;

if (isEdgePixel(data, idx, width)) {

let r = 0, g = 0, b = 0, a = 0;

for (let ky = -1; ky <= 1; ky++) {

for (let kx = -1; kx <= 1; kx++) {

const offset = ((y + ky) * width + (x + kx)) * 4;

const weight = kernel[ky + 1][kx + 1];

r += tempData[offset] * weight;

g += tempData[offset + 1] * weight;

b += tempData[offset + 2] * weight;

a += tempData[offset + 3] * weight;

}

}

data[idx] = r;

data[idx + 1] = g;

data[idx + 2] = b;

data[idx + 3] = a;

}

}

}

ctx.putImageData(imageData, 0, 0);

}

这里使用3*3卷积核对边缘像素进行了加权平均处理,从而消除锯齿效果。这里用到的isEdgePixel()方法目的是判断一个像素是否为图像的边缘像素,方法是通过比较该像素与其相邻像素的alpha通道值(也就是透明度)。

function isEdgePixel(data, idx, width) {

const alpha = data[idx + 3];

const leftAlpha = data[idx - 4 + 3];

const rightAlpha = data[idx + 4 + 3];

const topAlpha = data[idx - width * 4 + 3];

const bottomAlpha = data[idx + width * 4 + 3];

return (alpha !== leftAlpha ||

alpha !== rightAlpha || 拼多多帮助力入口

alpha !== topAlpha ||

alpha !== bottomAlpha);

}

完整代码

IDPhoto.vue

idphoto.workder.js

import * as tf from '@tensorflow/tfjs'

import * as bodyPix from '@tensorflow-models/body-pix'

let bodyPixModel = null;

// 初始化模型

async function loadModel() {

try {

console.log('开始加载模型...');

if (!bodyPixModel) {

bodyPixModel = await bodyPix.load({

architecture: 'MobileNetV1',

outputStride: 16,

multiplier: 0.75,

quantBytes: 2

});

console.log('模型加载成功');

}

return bodyPixModel;

} catch (error) {

console.error('模型加载失败:', error);

throw error;

}

}

// 处理图片的 Worker

self.onmessage = async function(e) {

console.log('Worker 收到消息:', e.data);

const { imageData, config } = e.data;

try {

if (!imageData || !config) {

throw new Error('缺少必要的参数')

}

// 加载模型

const model = await loadModel();

console.log('模型准备就绪');

// 创建图片元素

const img = await createImageBitmap(

await fetch(imageData).then(r => r.blob())

);

// 创建离屏 Canvas

const canvas = new OffscreenCanvas(img.width, img.height);

const ctx = canvas.getContext('2d');

if (!ctx) {

throw new Error('无法创建Canvas上下文')

}

// 绘制原始图片

ctx.drawImage(img, 0, 0);

console.log('图片绘制完成');

// 获取图片数据

const imgDataForSegmentation = ctx.getImageData(0, 0, img.width, img.height);

// 使用 BodyPix 进行人像分割

console.log('开始人像分割...');

const segmentation = await model.segmentPerson(imgDataForSegmentation, {

flipHorizontal: false,

internalResolution: 'medium',

segmentationThreshold: config.segmentationThreshold || 0.7

});

console.log('人像分割完成');

// 创建输出 Canvas

const outputCanvas = new OffscreenCanvas(img.width, img.height);

const outputCtx = outputCanvas.getContext('2d');

// 绘制原始图片

outputCtx.drawImage(img, 0, 0);

// 应用背景色

const backgroundColor = hexToRgb(config.bgColor);

const outputImageData = outputCtx.getImageData(0, 0, img.width, img.height);

const pixelData = outputImageData.data;

// 应用分割结果

for (let i = 0; i < segmentation.data.length; i++) {

const n = i * 4;

if (segmentation.data[i] === 0) { // 背景部分

pixelData[n] = backgroundColor.r;

pixelData[n + 1] = backgroundColor.g;

pixelData[n + 2] = backgroundColor.b;

pixelData[n + 3] = 255;

}

}

outputCtx.putImageData(outputImageData, 0, 0);

// 优化边缘

await smoothEdges(outputCtx, img.width, img.height);

// 转换为 Blob

const resultBlob = await outputCanvas.convertToBlob({

type: 'image/png'

});

console.log('处理完成,发送结果');

self.postMessage({

status: 'success',

result: resultBlob

});

} catch (error) {

console.error('Worker处理错误:', error);

self.postMessage({

status: 'error',

error: error.message || '处理图片时发生未知错误'

});

}

};

// 边缘平滑处理

async function smoothEdges(ctx, width, height) {

const imageData = ctx.getImageData(0, 0, width, height);

const data = imageData.data;

const kernel = [

[0.075, 0.124, 0.075],

[0.124, 0.204, 0.124],

[0.075, 0.124, 0.075]

];

const tempData = new Uint8ClampedArray(data);

for (let y = 1; y < height - 1; y++) {

for (let x = 1; x < width - 1; x++) {

const idx = (y * width + x) * 4;

if (isEdgePixel(data, idx, width)) {

let r = 0, g = 0, b = 0, a = 0;

for (let ky = -1; ky <= 1; ky++) {

for (let kx = -1; kx <= 1; kx++) {

const offset = ((y + ky) * width + (x + kx)) * 4;

const weight = kernel[ky + 1][kx + 1];

r += tempData[offset] * weight;

g += tempData[offset + 1] * weight;

b += tempData[offset + 2] * weight;

a += tempData[offset + 3] * weight;

}

}

data[idx] = r;

data[idx + 1] = g;

data[idx + 2] = b;

data[idx + 3] = a;

}

}

}

ctx.putImageData(imageData, 0, 0);

}

function isEdgePixel(data, idx, width) {

const alpha = data[idx + 3];

const leftAlpha = data[idx - 4 + 3];

const rightAlpha = data[idx + 4 + 3];

const topAlpha = data[idx - width * 4 + 3];

const bottomAlpha = data[idx + width * 4 + 3];

return (alpha !== leftAlpha ||

alpha !== rightAlpha ||

alpha !== topAlpha ||

alpha !== bottomAlpha);

}

function hexToRgb(hex) {

const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);

return result ? {

r: parseInt(result[1], 16),

g: parseInt(result[2], 16),

b: parseInt(result[3], 16)

} : null;

}

注

以上便是证件照功能的全部逻辑,其实我这里写的相当简陋且具有很大的扩展空间。各位大佬如果有精力,可以在这个基础上 增加服装替换、美颜等功能,以及可以进一步优化UI界面(我这里样式写的不是特别好)。 总之,感谢阅读了,愿你我都能在技术之路上更进一步!

前端 基于TensorFlow.js与Web Worker的智能证件照生成方案

文章链接

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧