luoyutianyang commited on
Commit
f61a046
·
verified ·
1 Parent(s): dca294e

Update egg-api.js

Browse files
Files changed (1) hide show
  1. egg-api.js +79 -79
egg-api.js CHANGED
@@ -11,7 +11,7 @@ const app = express();
11
  const port = 7860;
12
 
13
  // 从文件夹加载所有分类器
14
- async function loadClassifiersFromFolder(folderPath) {
15
  const classifiers = [];
16
  const files = fs.readdirSync(folderPath);
17
  for (const file of files) {
@@ -20,10 +20,10 @@ async function loadClassifiersFromFolder(folderPath) {
20
  classifiers.push(classifier);
21
  }
22
  return classifiers;
23
- }
24
 
25
  // 下载并转换图像到内存中
26
- async function downloadAndConvertImage(url) {
27
  try {
28
  const response = await axios({
29
  method: 'get',
@@ -41,103 +41,103 @@ async function downloadAndConvertImage(url) {
41
  console.error('Error downloading or converting image:', error);
42
  throw error;
43
  }
44
- }
45
 
46
  // 图像处理函数
47
- async function processImage(imageBuffer, classifiersFolder, replacementImageBuffer) {
48
- try {
49
- const classifiers = await loadClassifiersFromFolder(classifiersFolder);
50
 
51
- const jimpImage = await Jimp.read(imageBuffer);
52
- if (!jimpImage) {
53
- throw new Error('Failed to read the image with Jimp. The image file might be corrupted or not supported.');
54
- }
55
 
56
- const img = cv.imdecode(imageBuffer);
57
- if (img.empty) {
58
- throw new Error('Failed to read the image with OpenCV. The image file might be corrupted or not supported.');
59
- }
60
 
61
- const grayImg = img.bgrToGray();
62
- const allFaces = [];
63
- classifiers.forEach(classifier => {
64
- const faces = classifier.detectMultiScale(grayImg).objects;
65
- allFaces.push(...faces);
66
- });
67
 
68
- // 如果没有检测到人脸,抛出错误
69
- if (allFaces.length === 0) {
70
- throw new Error('No faces detected in the image.');
71
- }
72
 
73
- const replacementFace = await Jimp.read(replacementImageBuffer);
74
- allFaces.forEach((faceRect, i) => {
75
- const resizedReplacementFace = replacementFace.resize(faceRect.width, faceRect.height);
76
- const faceRegion = img.getRegion(faceRect);
77
 
78
- const replacementBuffer = resizedReplacementFace.bitmap.data;
79
- const centerX = faceRect.width / 2;
80
- const centerY = faceRect.height / 2;
81
- const maxRadius = Math.min(centerX, centerY);
82
- for (let y = 0; y < faceRect.height; y++) {
83
- for (let x = 0; x < faceRect.width; x++) {
84
- const distance = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);
85
- if (distance <= maxRadius) {
86
- const idx = (y * faceRect.width + x) << 2;
87
- const [r, g, b, a] = replacementBuffer.slice(idx, idx + 4);
88
 
89
- if (a > 0) {
90
- faceRegion.set(y, x, new cv.Vec3(b, g, r));
91
- }
92
  }
93
  }
94
  }
95
- });
96
- const outputBuffer = cv.imencode('.jpg', img);
97
- return outputBuffer;
98
- } catch (error) {
99
- console.error('Error during image processing:', error);
100
- throw error;
101
- }
102
  }
 
103
 
104
  // Express接口
105
  app.get('/process-image', async (req, res) => {
106
- const { imageUrl, replacementImageUrl } = req.query;
107
 
108
- if (!imageUrl || !replacementImageUrl) {
109
- return res.status(400).send('Both image URL and replacement image URL are required');
110
- }
111
 
112
- const classifiersFolder = './classifiers';
113
- let replacementImageBuffer;
114
- try {
115
- // 下载并转换输入图片和替换图片到内存中
116
- const imageBuffer = await downloadAndConvertImage(imageUrl);
117
- if (replacementImageUrl === 'replace') {
118
- // 使用默认的本地替换图像路径
119
- const defaultReplacementImagePath = './replacement_face.png';
120
- replacementImageBuffer = await Jimp.read(defaultReplacementImagePath);
121
- } else {
122
- // 下载并转换替换图片到内存中
123
- replacementImageBuffer = await downloadAndConvertImage(replacementImageUrl);
124
- }
125
 
126
- // 处理图片
127
- const outputBuffer = await processImage(imageBuffer, classifiersFolder, replacementImageBuffer);
128
 
129
- // 返回处理后的图片
130
- res.set('Content-Type', 'image/jpeg');
131
- res.send(outputBuffer);
132
- } catch (error) {
133
- if (error.message === 'No faces detected in the image.') {
134
- res.status(404).send('No faces detected in the image.');
135
- } else {
136
- console.error('Error processing image:', error);
137
- res.status(500).send('Error processing image');
138
- }
139
  }
140
- });
 
141
 
142
  // 记录使用次数和内存占用的全局变量
143
  let usageCount = 0;
 
11
  const port = 7860;
12
 
13
  // 从文件夹加载所有分类器
14
+ const loadClassifiersFromFolder = async (folderPath) => {
15
  const classifiers = [];
16
  const files = fs.readdirSync(folderPath);
17
  for (const file of files) {
 
20
  classifiers.push(classifier);
21
  }
22
  return classifiers;
23
+ };
24
 
25
  // 下载并转换图像到内存中
26
+ const downloadAndConvertImage = async (url) => {
27
  try {
28
  const response = await axios({
29
  method: 'get',
 
41
  console.error('Error downloading or converting image:', error);
42
  throw error;
43
  }
44
+ };
45
 
46
  // 图像处理函数
47
+ const processImage = async (imageBuffer, classifiersFolder, replacementImageBuffer) => {
48
+ try {
49
+ const classifiers = await loadClassifiersFromFolder(classifiersFolder);
50
 
51
+ const jimpImage = await Jimp.read(imageBuffer);
52
+ if (!jimpImage) {
53
+ throw new Error('Failed to read the image with Jimp. The image file might be corrupted or not supported.');
54
+ }
55
 
56
+ const img = cv.imdecode(imageBuffer);
57
+ if (img.empty) {
58
+ throw new Error('Failed to read the image with OpenCV. The image file might be corrupted or not supported.');
59
+ }
60
 
61
+ const grayImg = img.bgrToGray();
62
+ const allFaces = [];
63
+ classifiers.forEach(classifier => {
64
+ const faces = classifier.detectMultiScale(grayImg).objects;
65
+ allFaces.push(...faces);
66
+ });
67
 
68
+ // 如果没有检测到人脸,抛出错误
69
+ if (allFaces.length === 0) {
70
+ throw new Error('No faces detected in the image.');
71
+ }
72
 
73
+ const replacementFace = await Jimp.read(replacementImageBuffer);
74
+ allFaces.forEach((faceRect, i) => {
75
+ const resizedReplacementFace = replacementFace.resize(faceRect.width, faceRect.height);
76
+ const faceRegion = img.getRegion(faceRect);
77
 
78
+ const replacementBuffer = resizedReplacementFace.bitmap.data;
79
+ const centerX = faceRect.width / 2;
80
+ const centerY = faceRect.height / 2;
81
+ const maxRadius = Math.min(centerX, centerY);
82
+ for (let y = 0; y < faceRect.height; y++) {
83
+ for (let x = 0; x < faceRect.width; x++) {
84
+ const distance = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);
85
+ if (distance <= maxRadius) {
86
+ const idx = (y * faceRect.width + x) << 2;
87
+ const [r, g, b, a] = replacementBuffer.slice(idx, idx + 4);
88
 
89
+ if (a > 0) {
90
+ faceRegion.set(y, x, new cv.Vec3(b, g, r));
 
91
  }
92
  }
93
  }
94
+ }
95
+ });
96
+ const outputBuffer = cv.imencode('.jpg', img);
97
+ return outputBuffer;
98
+ } catch (error) {
99
+ console.error('Error during image processing:', error);
100
+ throw error;
101
  }
102
+ };
103
 
104
  // Express接口
105
  app.get('/process-image', async (req, res) => {
106
+ const { imageUrl, replacementImageUrl } = req.query;
107
 
108
+ if (!imageUrl || !replacementImageUrl) {
109
+ return res.status(400).send('Both image URL and replacement image URL are required');
110
+ }
111
 
112
+ const classifiersFolder = './classifiers';
113
+ let replacementImageBuffer;
114
+ try {
115
+ // 下载并转换输入图片和替换图片到内存中
116
+ const imageBuffer = await downloadAndConvertImage(imageUrl);
117
+ if (replacementImageUrl === 'replace') {
118
+ // 使用默认的本地替换图像路径
119
+ const defaultReplacementImagePath = './replacement_face.png';
120
+ replacementImageBuffer = await Jimp.read(defaultReplacementImagePath);
121
+ } else {
122
+ // 下载并转换替换图片到内存中
123
+ replacementImageBuffer = await downloadAndConvertImage(replacementImageUrl);
124
+ }
125
 
126
+ // 处理图片
127
+ const outputBuffer = await processImage(imageBuffer, classifiersFolder, replacementImageBuffer);
128
 
129
+ // 返回处理后的图片
130
+ res.set('Content-Type', 'image/jpeg');
131
+ res.send(outputBuffer);
132
+ } catch (error) {
133
+ if (error.message === 'No faces detected in the image.') {
134
+ res.status(404).send('No faces detected in the image.');
135
+ } else {
136
+ console.error('Error processing image:', error);
137
+ res.status(500).send('Error processing image');
 
138
  }
139
+ }
140
+ });
141
 
142
  // 记录使用次数和内存占用的全局变量
143
  let usageCount = 0;