Skip to content

Instantly share code, notes, and snippets.

@conanak99
Created April 14, 2018 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conanak99/d79a9b82d39a6f3262f5c7a366215f70 to your computer and use it in GitHub Desktop.
Save conanak99/d79a9b82d39a6f3262f5c7a366215f70 to your computer and use it in GitHub Desktop.
const rp = require('request-promise');
const Jimp = require("jimp");
(async () => {
const imageUrl = 'https://pbs.twimg.com/media/DWr05hUXcAA9s8n.jpg';
const detectResult = await detectImage(imageUrl);
addMustache(imageUrl, detectResult, 'jav_rau.jpg');
})();
async function addMustache(url, detectResult, output) {
// Tính toán vị trí và khuôn mặt
const face = detectResult[0]; // Hình chỉ nhận được 1 khuôn mặt
const landmarks = face.faceLandmarks;
const mouthLeft = landmarks['mouthLeft'];
const mouthRight = landmarks['mouthRight'];
const x1 = mouthLeft.x, y1 = mouthLeft.y;
const x2 = mouthRight.x, y2= mouthRight.y;
// Cạnh đối và cạnh kề
const ab = y2 - y1;
const ac = x2 - x1;
// Cạnh huyền = căn tổng bình phương 2 cạnh
const bc = Math.sqrt(ab * ab + ac * ac);
const tanACB = ab / ac;
// Qui đổi radian sang độ
const deg = Math.atan(tanACB) * 180 / Math.PI;
// Resize và quay bộ râu
let source = await Jimp.read(url);
const mustache = await Jimp.read('mustache.png');
const mustacheWidth = bc;
mustache.resize(mustacheWidth, Jimp.AUTO).rotate(deg);
// Xác định vị trí đặt râu
const x = landmarks['upperLipTop'].x;
const moveY = (landmarks['upperLipTop'].y - landmarks['noseTip'].y) / 2;
const y = landmarks['upperLipTop'].y - moveY;
// Đặt bộ râu vào giữa tọa độ x,y
addImageCenter(source, mustache, x, y);
return source.write(output);
}
function addImageCenter(source, image, x, y) {
const { height, width } = image.bitmap;
const newX = x - width / 2;
const newY = y - height / 2;
return source.composite(image, newX, newY);
}
async function detectImage(source) {
const subscriptionKey = "3845387fabbf4ba5bfe958a2409b8238";
const uri = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";
const options = {
uri,
qs: {
returnFaceId: true,
returnFaceLandmarks: true,
},
method: 'POST',
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey
},
body: {
url: source
},
json: true // Automatically parses the JSON string in the response
};
const result = await rp(options);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment