
Geminiで「笑顔が一番良い人選んでくれるアプリ」を作成した話
こんにちは! AIとの対話を通じて、ふと「集合写真の中で一番良い笑顔の人を自動で判定してくれるアプリがあったら面白いな」と思い立ち、GoogleのAI Gemini と一緒に開発に挑戦してみました。
今回は、その開発プロセスと完成したアプリ、そしてAIとの共同作業で直面した課題と解決策についてお話します。
完成した「ベストスマイル判定アプリ」
まずは完成品をご紹介します。

このアプリは、ユーザーが選択した写真から複数の顔を検出し、独自の 「精密笑顔係数」 を算出。一番スコアが高い人をハイライト表示してくれる、というものです。
主な機能
顔検出と感情分析: ブラウザ上で動作する face-api.js というライブラリを使い、写真から顔の位置や表情をリアルタイムで解析します。
精密笑顔係数の算出: face-api.js が判定する「幸福度(happy)」だけでなく、顔のパーツ(ランドマーク)から 「口の横幅と両目の距離の比率」 を計算。これを「笑顔強度」としてスコアに加えることで、より人間らしい、ダイナミックな笑顔を高く評価するようにしました。
結果の可視化: 検出した顔を四角で囲み、一番笑顔スコアが高い人を緑色の枠と★マークでハイライトします。
このすべての機能が、サーバーを必要としない単一のHTMLファイルで完結しているのも特徴です。
開発で一番困った点:AI生成画像が認識されない!
開発は順調に見えましたが、テスト段階で大きな壁にぶつかりました。それは 「顔認識の精度」 です。
特に、テスト用にGemini自身に生成させた集合写真を使うと、ほとんど顔を認識してくれない、という問題が発生しました。
試行錯誤のプロセス
ここから、Geminiとの二人三脚でのデバッグが始まりました。
ステップ1: モデルの変更
当初、処理速度を重視して比較的軽量な顔検出モデル(TinyFaceDetector)を使用していました。しかし、これが精度不足の原因と推測。
私: 「AIが生成した顔が検出されないです。もっと強力なモデルに変更してください。」
この指示で、Geminiはより高精度なモデル(SsdMobilenetv1)にコードを書き換えてくれました。しかし、それでも状況はあまり改善しませんでした。
ステップ2: 信頼度のしきい値との戦い
高精度なモデルは、逆に「これは絶対に顔だ」という確信が持てないと検出結果として報告してくれません。AIが生成した、人間には自然に見える顔でも、モデルの基準からすると少しだけ「不自然」だったのかもしれません。
そこで、この「確信度」の基準となる しきい値(minConfidence) を下げるアプローチを取りました。
私: 「まだ検出漏れがあります。検出の信頼度しきい値を少し下げてみてください。」
Geminiはこの指示を受け、コード内の minConfidence の値を 0.5 から 0.4 に変更。
すると、検出数が 2人 から 3人 に増えました!
しかし、まだ全員は認識されません。そこで、さらに指示を出します。
私: 「あと一人が認識されません。しきい値をさらに下げて、これが最終調整です。」
最終的に、Geminiはしきい値を 0.2 まで引き下げました。その結果、見事に写真に写っている全員を検出できるようになったのです。
この経験から、AIとの開発では「何が問題か」を人間が正しく推測し、具体的な指示を出すことの重要性を学びました。AIは完璧ではありませんが、的確なパートナーとして対話することで、人間だけでは時間のかかる問題もスピーディに解決できると実感しました。
全ソースコード
最後に、今回作成したアプリの全ソースコードを公開します。
単一のHTMLファイルなので、コピーして index.html として保存すれば、すぐにブラウザで動かせます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>1番の笑顔値が高い人を見つけるアプリ (精密評価版)</title>
<!-- face-api.jsライブラリを読み込み -->
<script src="[https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/dist/face-api.min.js](https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/dist/face-api.min.js)"></script>
<style>
/* 全体のスタイル */
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background-color: #f0f2f5;
color: #333;
display: flex;
flex-direction: column;
align-items: center;
margin: 0;
padding: 20px;
}
/* メインコンテナ */
.container {
width: 100%;
max-width: 800px;
background-color: #fff;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
padding: 24px;
box-sizing: border-box;
}
/* ヘッダー */
header {
text-align: center;
margin-bottom: 24px;
border-bottom: 1px solid #e0e0e0;
padding-bottom: 16px;
}
h1 {
color: #1a73e8;
margin: 0;
}
/* 入力エリア */
.input-area {
text-align: center;
margin-bottom: 24px;
}
#status-text {
color: #666;
min-height: 1.2em;
}
/* ファイル選択ボタンのスタイル */
.file-input-label {
display: inline-block;
padding: 12px 24px;
background-color: #1a73e8;
color: white;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.3s ease;
font-weight: 500;
}
.file-input-label:hover {
background-color: #155ab6;
}
.file-input-label.disabled {
background-color: #aaa;
cursor: not-allowed;
}
#image-selector {
display: none; /* input自体は非表示にする */
}
/* 画像と結果の表示エリア */
.display-area {
position: relative;
text-align: center;
}
#image-preview, #result-canvas {
max-width: 100%;
height: auto;
border-radius: 8px;
margin-top: 16px;
border: 1px solid #ddd;
}
#image-preview { display: none; }
#result-canvas { display: none; }
/* 結果リスト */
.result-list-container {
margin-top: 24px;
padding-top: 16px;
border-top: 1px solid #e0e0e0;
}
h2 { text-align: center; color: #333; margin-bottom: 16px; }
#result-list { list-style-type: none; padding: 0; text-align: center; }
#result-list li {
background-color: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 8px;
padding: 12px;
margin: 8px auto;
max-width: 300px;
font-size: 1.1em;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
#result-list li:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.05); }
.highlight { font-weight: bold; color: #28a745; }
/* ローディングスピナー */
.loader {
display: none; border: 5px solid #f3f3f3; border-radius: 50%;
border-top: 5px solid #1a73e8; width: 40px; height: 40px;
animation: spin 1s linear infinite; margin: 20px auto;
}
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
</style>
</head>
<body>
<div class="container">
<header>
<h1>1番の笑顔値が高い人を見つけるアプリ (精密評価版)</h1>
</header>
<div class="input-area">
<p id="status-text">モデルを読み込んでいます...</p>
<label for="image-selector" id="file-label" class="file-input-label disabled">写真を選択</label>
<input type="file" id="image-selector" accept="image/*" disabled>
</div>
<div class="display-area">
<img id="image-preview" src="" alt="選択された画像">
<div id="loader" class="loader"></div>
<canvas id="result-canvas"></canvas>
</div>
<div class="result-list-container" id="result-container" style="display:none;">
<h2>解析結果</h2>
<ul id="result-list"></ul>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', async () => {
const imageSelector = document.getElementById('image-selector');
const imagePreview = document.getElementById('image-preview');
const resultCanvas = document.getElementById('result-canvas');
const resultList = document.getElementById('result-list');
const resultContainer = document.getElementById('result-container');
const loader = document.getElementById('loader');
const statusText = document.getElementById('status-text');
const fileLabel = document.getElementById('file-label');
const MODEL_URL = '[https://cdn.jsdelivr.net/gh/justadudewhohacks/face-api.js@0.22.2/weights](https://cdn.jsdelivr.net/gh/justadudewhohacks/face-api.js@0.22.2/weights)';
async function loadModels() {
try {
//【変更点】高精度なモデル(SsdMobilenetv1)を読み込むように変更
await faceapi.nets.ssdMobilenetv1.loadFromUri(MODEL_URL);
await faceapi.nets.faceLandmark68Net.loadFromUri(MODEL_URL);
await faceapi.nets.faceExpressionNet.loadFromUri(MODEL_URL);
statusText.textContent = '準備完了です。写真を選択してください。';
imageSelector.disabled = false;
fileLabel.classList.remove('disabled');
} catch (error) {
console.error('モデルの読み込みに失敗しました:', error);
statusText.textContent = 'エラー: モデルの読み込みに失敗しました。';
}
}
loadModels();
imageSelector.addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) return;
resetUI();
const reader = new FileReader();
reader.onload = (e) => {
imagePreview.src = e.target.result;
imagePreview.onload = async () => {
imagePreview.style.display = 'block';
await processImage(imagePreview);
};
};
reader.readAsDataURL(file);
});
function resetUI() {
imagePreview.style.display = 'none';
resultCanvas.style.display = 'none';
resultContainer.style.display = 'none';
resultList.innerHTML = '';
}
/** 2点間の距離を計算するヘルパー関数 */
function getDistance(p1, p2) {
return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
}
async function processImage(imgElement) {
statusText.textContent = '顔を検出し、笑顔を精密分析中...';
loader.style.display = 'block';
try {
//【最終調整】検出モデルの信頼度をさらに調整 (0.3 -> 0.2)
const detections = await faceapi.detectAllFaces(imgElement, new faceapi.SsdMobilenetv1Options({ minConfidence: 0.2 }))
.withFaceLandmarks()
.withFaceExpressions();
loader.style.display = 'none';
if (detections.length === 0) {
statusText.textContent = '顔が検出されませんでした。別の写真をお試しください。';
return;
}
statusText.textContent = `${detections.length}人の顔を検出しました。`;
const faces = detections.map((detection, index) => {
const landmarks = detection.landmarks;
const mouthLeft = landmarks.positions[48];
const mouthRight = landmarks.positions[54];
const eyeLeft = landmarks.positions[36];
const eyeRight = landmarks.positions[45];
const mouthWidth = getDistance(mouthLeft, mouthRight);
const eyeDistance = getDistance(eyeLeft, eyeRight);
const smileRatio = mouthWidth / eyeDistance;
const smileIntensity = Math.min(1, Math.max(0, (smileRatio - 0.5) / 0.5));
const baseHappyScore = detection.expressions.happy;
const refinedSmileScore = baseHappyScore * 0.7 + smileIntensity * 0.3;
return {
id: index + 1,
position: detection.detection.box,
smileScore: refinedSmileScore,
};
});
analyzeAndDisplayResults(imgElement, faces);
} catch (error) {
console.error('顔検出中にエラーが発生しました:', error);
statusText.textContent = 'エラー: 顔検出中に問題が発生しました。';
loader.style.display = 'none';
}
}
function analyzeAndDisplayResults(imgElement, faces) {
const ctx = resultCanvas.getContext('2d');
resultCanvas.width = imgElement.naturalWidth;
resultCanvas.height = imgElement.naturalHeight;
ctx.drawImage(imgElement, 0, 0);
let highestScore = 0;
let bestSmileFaceId = -1;
faces.forEach(face => {
if (face.smileScore > highestScore) {
highestScore = face.smileScore;
bestSmileFaceId = face.id;
}
});
faces.forEach(face => {
const { x, y, width, height } = face.position;
const isBestSmile = face.id === bestSmileFaceId;
ctx.lineWidth = Math.max(5, resultCanvas.width * 0.005);
ctx.strokeStyle = isBestSmile ? '#28a745' : '#1a73e8';
ctx.strokeRect(x, y, width, height);
const fontSize = Math.max(24, resultCanvas.width * 0.02);
const text = `ID:${face.id} - ${Math.round(face.smileScore * 100)}${isBestSmile ? ' ★' : ''}`;
ctx.font = `bold ${fontSize}px sans-serif`;
const textMetrics = ctx.measureText(text);
const textBgHeight = fontSize * 1.2;
ctx.fillStyle = 'rgba(255, 255, 255, 0.85)';
ctx.fillRect(x, y - textBgHeight, textMetrics.width + 10, textBgHeight);
ctx.fillStyle = isBestSmile ? '#28a745' : '#1a73e8';
ctx.fillText(text, x + 5, y - (textBgHeight * 0.2));
});
faces.sort((a, b) => b.smileScore - a.smileScore);
faces.forEach(face => {
const li = document.createElement('li');
const isBestSmile = face.id === bestSmileFaceId;
// 表示を100点満点に
li.textContent = `顔 ${face.id}: 精密笑顔係数 ${Math.round(face.smileScore * 100)}点`;
if (isBestSmile) {
li.innerHTML += ' ★';
li.classList.add('highlight');
}
resultList.appendChild(li);
});
imagePreview.style.display = 'none';
resultCanvas.style.display = 'block';
resultContainer.style.display = 'block';
}
});
</script>
</body>
</html>
まとめ
今回のプロジェクトを通じて、AI(Gemini)が単なる「コード生成ツール」ではなく、対話を通じて共に問題を解決してくれる 「開発パートナー」 になり得ることを強く感じました。
皆さんも何かアイデアがあれば、AIに相談しながら形にしてみてはいかがでしょうか。きっと面白い発見があるはずです。