luoyutianyang commited on
Commit
798fa34
·
verified ·
1 Parent(s): 8a1af6f

Update egg-api.js

Browse files
Files changed (1) hide show
  1. egg-api.js +133 -133
egg-api.js CHANGED
@@ -1,133 +1,133 @@
1
- import express from 'express';
2
- import fs from 'fs';
3
- import path from 'path';
4
- import cv from 'opencv4nodejs';
5
- import Jimp from 'jimp';
6
- import axios from 'axios';
7
- import sharp from 'sharp';
8
-
9
- const app = express();
10
- const port = 3000;
11
- const outputDir = './output';
12
-
13
- // 确保输出目录存在
14
- if (!fs.existsSync(outputDir)){
15
- fs.mkdirSync(outputDir);
16
- }
17
- // 从文件夹加载所有分类器
18
- async function loadClassifiersFromFolder(folderPath) {
19
- const classifiers = [];
20
- const files = fs.readdirSync(folderPath);
21
- for (const file of files) {
22
- const filePath = path.join(folderPath, file);
23
- const classifier = new cv.CascadeClassifier(filePath);
24
- classifiers.push(classifier);
25
- }
26
- return classifiers;
27
- }
28
-
29
-
30
- async function downloadAndConvertImage(url, dest) {
31
- try {
32
- const response = await axios({
33
- method: 'get',
34
- url: url,
35
- responseType: 'arraybuffer'
36
- });
37
-
38
- await sharp(response.data)
39
- .toFormat('jpeg')
40
- .toFile(dest);
41
-
42
- console.log('Image downloaded and converted successfully.');
43
- } catch (error) {
44
- console.error('Error downloading or converting image:', error);
45
- throw error;
46
- }
47
- }
48
-
49
- // 图像处理函数
50
- async function processImage(inputImagePath, outputImagePath, classifiersFolder, replacementImagePath) {
51
- try {
52
- const classifiers = await loadClassifiersFromFolder(classifiersFolder);
53
-
54
- if (!fs.existsSync(inputImagePath)) {
55
- throw new Error(`Input image not found at ${inputImagePath}`);
56
- }
57
-
58
- // 使用 Jimp 验证图片文件是否有效
59
- const jimpImage = await Jimp.read(inputImagePath);
60
- if (!jimpImage) {
61
- throw new Error('Failed to read the image with Jimp. The image file might be corrupted or not supported.');
62
- }
63
-
64
- const img = cv.imread(inputImagePath);
65
- if (img.empty) {
66
- throw new Error('Failed to read the image with OpenCV. The image file might be corrupted or not supported.');
67
- }
68
-
69
- const grayImg = img.bgrToGray();
70
- const allFaces = [];
71
- classifiers.forEach(classifier => {
72
- const faces = classifier.detectMultiScale(grayImg).objects;
73
- allFaces.push(...faces);
74
- });
75
-
76
-
77
-
78
- const replacementFace = await Jimp.read(replacementImagePath);
79
- allFaces.forEach((faceRect, i) => {
80
- const resizedReplacementFace = replacementFace.resize(faceRect.width, faceRect.height);
81
- const faceRegion = img.getRegion(faceRect);
82
- const replacementBuffer = resizedReplacementFace.bitmap.data;
83
- for (let y = 0; y < faceRect.height; y++) {
84
- for (let x = 0; x < faceRect.width; x++) {
85
- const idx = (y * faceRect.width + x) << 2;
86
- const [r, g, b, a] = replacementBuffer.slice(idx, idx + 4);
87
- if (a > 0) {
88
- faceRegion.set(y, x, new cv.Vec3(b, g, r));
89
- }
90
- }
91
- }
92
- });
93
- cv.imwrite(outputImagePath, img);
94
- } catch (error) {
95
- console.error('Error during image processing:', error);
96
- throw error;
97
- }
98
- }
99
-
100
- // Express接口
101
- app.get('/process-image', async (req, res) => {
102
- const { imageUrl } = req.query;
103
-
104
- if (!imageUrl) {
105
- return res.status(400).send('Image URL is required');
106
- }
107
-
108
- const inputImagePath = path.join(outputDir, 'test.jpg'); // 使用jpg格式保存
109
- const outputImagePath = path.join(outputDir, 'image_with_replaced_faces.jpg');
110
- const replacementImagePath = './replacement_face.png';
111
- const classifiersFolder = './classifiers';
112
-
113
- try {
114
- // 下载并转换输入图片
115
- await downloadAndConvertImage(imageUrl, inputImagePath);
116
- // 检查下载的图片文件是否存在且有效
117
- if (!fs.existsSync(inputImagePath) || fs.statSync(inputImagePath).size === 0) {
118
- throw new Error('Downloaded image file is not found or is empty.');
119
- }
120
- // 处理图片
121
- await processImage(inputImagePath, outputImagePath, classifiersFolder, replacementImagePath);
122
-
123
- // 返回处理后的图片链接
124
- res.sendFile(outputImagePath, { root: '.' });
125
- } catch (error) {
126
- console.error('Error processing image:', error);
127
- res.status(500).send('Error processing image');
128
- }
129
- });
130
-
131
- app.listen(port, () => {
132
- console.log(`Server is running on http://localhost:${port}`);
133
- });
 
1
+ import express from 'express';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import cv from 'opencv4nodejs';
5
+ import Jimp from 'jimp';
6
+ import axios from 'axios';
7
+ import sharp from 'sharp';
8
+
9
+ const app = express();
10
+ const port = 7860;
11
+ const outputDir = './output';
12
+
13
+ // 确保输出目录存在
14
+ if (!fs.existsSync(outputDir)){
15
+ fs.mkdirSync(outputDir);
16
+ }
17
+ // 从文件夹加载所有分类器
18
+ async function loadClassifiersFromFolder(folderPath) {
19
+ const classifiers = [];
20
+ const files = fs.readdirSync(folderPath);
21
+ for (const file of files) {
22
+ const filePath = path.join(folderPath, file);
23
+ const classifier = new cv.CascadeClassifier(filePath);
24
+ classifiers.push(classifier);
25
+ }
26
+ return classifiers;
27
+ }
28
+
29
+
30
+ async function downloadAndConvertImage(url, dest) {
31
+ try {
32
+ const response = await axios({
33
+ method: 'get',
34
+ url: url,
35
+ responseType: 'arraybuffer'
36
+ });
37
+
38
+ await sharp(response.data)
39
+ .toFormat('jpeg')
40
+ .toFile(dest);
41
+
42
+ console.log('Image downloaded and converted successfully.');
43
+ } catch (error) {
44
+ console.error('Error downloading or converting image:', error);
45
+ throw error;
46
+ }
47
+ }
48
+
49
+ // 图像处理函数
50
+ async function processImage(inputImagePath, outputImagePath, classifiersFolder, replacementImagePath) {
51
+ try {
52
+ const classifiers = await loadClassifiersFromFolder(classifiersFolder);
53
+
54
+ if (!fs.existsSync(inputImagePath)) {
55
+ throw new Error(`Input image not found at ${inputImagePath}`);
56
+ }
57
+
58
+ // 使用 Jimp 验证图片文件是否有效
59
+ const jimpImage = await Jimp.read(inputImagePath);
60
+ if (!jimpImage) {
61
+ throw new Error('Failed to read the image with Jimp. The image file might be corrupted or not supported.');
62
+ }
63
+
64
+ const img = cv.imread(inputImagePath);
65
+ if (img.empty) {
66
+ throw new Error('Failed to read the image with OpenCV. The image file might be corrupted or not supported.');
67
+ }
68
+
69
+ const grayImg = img.bgrToGray();
70
+ const allFaces = [];
71
+ classifiers.forEach(classifier => {
72
+ const faces = classifier.detectMultiScale(grayImg).objects;
73
+ allFaces.push(...faces);
74
+ });
75
+
76
+
77
+
78
+ const replacementFace = await Jimp.read(replacementImagePath);
79
+ allFaces.forEach((faceRect, i) => {
80
+ const resizedReplacementFace = replacementFace.resize(faceRect.width, faceRect.height);
81
+ const faceRegion = img.getRegion(faceRect);
82
+ const replacementBuffer = resizedReplacementFace.bitmap.data;
83
+ for (let y = 0; y < faceRect.height; y++) {
84
+ for (let x = 0; x < faceRect.width; x++) {
85
+ const idx = (y * faceRect.width + x) << 2;
86
+ const [r, g, b, a] = replacementBuffer.slice(idx, idx + 4);
87
+ if (a > 0) {
88
+ faceRegion.set(y, x, new cv.Vec3(b, g, r));
89
+ }
90
+ }
91
+ }
92
+ });
93
+ cv.imwrite(outputImagePath, img);
94
+ } catch (error) {
95
+ console.error('Error during image processing:', error);
96
+ throw error;
97
+ }
98
+ }
99
+
100
+ // Express接口
101
+ app.get('/process-image', async (req, res) => {
102
+ const { imageUrl } = req.query;
103
+
104
+ if (!imageUrl) {
105
+ return res.status(400).send('Image URL is required');
106
+ }
107
+
108
+ const inputImagePath = path.join(outputDir, 'test.jpg'); // 使用jpg格式保存
109
+ const outputImagePath = path.join(outputDir, 'image_with_replaced_faces.jpg');
110
+ const replacementImagePath = './replacement_face.png';
111
+ const classifiersFolder = './classifiers';
112
+
113
+ try {
114
+ // 下载并转换输入图片
115
+ await downloadAndConvertImage(imageUrl, inputImagePath);
116
+ // 检查下载的图片文件是否存在且有效
117
+ if (!fs.existsSync(inputImagePath) || fs.statSync(inputImagePath).size === 0) {
118
+ throw new Error('Downloaded image file is not found or is empty.');
119
+ }
120
+ // 处理图片
121
+ await processImage(inputImagePath, outputImagePath, classifiersFolder, replacementImagePath);
122
+
123
+ // 返回处理后的图片链接
124
+ res.sendFile(outputImagePath, { root: '.' });
125
+ } catch (error) {
126
+ console.error('Error processing image:', error);
127
+ res.status(500).send('Error processing image');
128
+ }
129
+ });
130
+
131
+ app.listen(port, () => {
132
+ console.log(`Server is running on http://localhost:${port}`);
133
+ });