画像に関する質問応答
画像の内容、数量、属性について具体的な質問をします。
「画像に関する質問応答」はCoddyKit上の無料AI Prompt Engineeringレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Prompt Engineering学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Prompt Engineeringコースには全4レッスンが含まれています。
視覚的質問応答
視覚的質問応答(VQA)は、画像について自然言語で尋ねられた質問に答えるタスクです。すべてを説明する画像説明とは異なり、VQAでは特定の質問への回答にモデルの焦点を絞ります。
VQAプロンプトは正確かつ直接的で、視覚的な内容のカウント、特定、比較、推論を求めることがよくあります。プロンプトの品質によって、正確で役立つ回答が得られるか、曖昧で一般的な回答になるかが決まります。
基本的なVQAプロンプトの構造
VQAプロンプトでは、画像と具体的な質問を組み合わせます。直接的で利用しやすい回答を得るには、質問を十分に具体的にすることが重要です。
import anthropic, base64
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
def ask_about_image(image_path, question, answer_format='Direct answer. No extra explanation.'):
with open(image_path, 'rb') as f:
img_b64 = base64.standard_b64encode(f.read()).decode('utf-8')
prompt = f'{question}\n\n{answer_format}'
r = client.messages.create(
model='claude-opus-4-5', max_tokens=150,
messages=[{'role': 'user', 'content': [
{'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/jpeg', 'data': img_b64}},
{'type': 'text', 'text': prompt}
]}]
)
return r.content[0].text
# Example VQA calls (replace image.jpg with actual image)
print('VQA function defined. Ready for image questions.')数を数える質問
カウントは、一般的なVQAタスクです。正確なカウントを求めるプロンプトを使うと、曖昧なプロンプトよりも正確な結果が得られます。
# Vague (bad):
vague_prompt = 'How many people are there?'
# Precise (good): specifies what counts and what does not
counting_prompt = '''
How many people are visible in this image?
Count only: people whose faces OR bodies are at least 50% visible.
Do NOT count: people who are heavily cropped, cut off at the edge, or only partially visible.
Return a single number.
'''
# Even more precise: handles partial visibility explicitly
precise_count = '''
Count the number of distinct individuals visible in this image.
If a person is partially obscured, count them if more than half their body is visible.
Return JSON: {"count": integer, "partially_visible": integer, "notes": "string or null"}
'''
print('Counting prompts: vague vs precise.')
print('Precise prompts define edge cases explicitly.')ブランドとロゴの識別
画像内のブランドロゴの識別は、一般的な製品分析タスクです。何を探すのか、どのような形式で返すのかをプロンプトで指定する必要があります。
logo_prompt = '''
Identify all visible brand logos, company names, and product labels in this image.
For each, note:
- Brand/company name
- Where it appears in the image (top-left, center, on a product, etc.)
- Confidence: high (clearly legible) | medium (partially visible) | low (partially obscured)
Return JSON: {"brands": [{"name": str, "location": str, "confidence": str}]}
If no logos are visible, return: {"brands": []}
'''
import anthropic, base64, json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
def identify_brands(image_path):
with open(image_path, 'rb') as f:
img_b64 = base64.standard_b64encode(f.read()).decode('utf-8')
r = client.messages.create(
model='claude-opus-4-5', max_tokens=200,
messages=[{'role': 'user', 'content': [
{'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/jpeg', 'data': img_b64}},
{'type': 'text', 'text': logo_prompt}
]}]
)
return json.loads(r.content[0].text)
print('Brand identification function defined.')感情と表情の認識
画像内の感情表現を識別するには、不確実性を考慮した慎重なプロンプト設計が必要です。
emotion_prompt = '''
Describe the emotional expression of the person in this image.
Assess:
- Primary emotion: (happy, sad, angry, surprised, fearful, disgusted, neutral, or other)
- Intensity: (low, moderate, high)
- Confidence: (high if expression is clear, medium if subtle, low if face is obscured or turned away)
- Evidence: which specific facial features support your assessment
Return JSON:
{
"primary_emotion": str,
"intensity": str,
"confidence": str,
"evidence": str,
"secondary_emotion": str or null
}
If no person or face is clearly visible, return: {"primary_emotion": null, "confidence": "none", "reason": str}
'''
print(emotion_prompt)空間的な位置関係に関する質問
物体同士の相対的な位置を尋ねる質問では、プロンプトに空間関係を表す語彙を明示的に含める必要があります。
spatial_prompt = '''
Answer questions about the spatial relationships of objects in this image.
Use these spatial terms consistently:
- Position in frame: top-left, top-center, top-right, middle-left, center, middle-right, bottom-left, bottom-center, bottom-right
- Relative position: in front of, behind, to the left of, to the right of, above, below, overlapping
- Distance: in the foreground, in the midground, in the background
Question: {question}
Answer in one or two sentences using the spatial vocabulary above.
'''
# Example questions:
questions = [
'Where is the red cup relative to the laptop?',
'Is the plant in the foreground or background?',
'What object is to the left of the person?'
]
for q in questions:
print(spatial_prompt.replace('{question}', q)[:200])
print('---')品質と状態の評価
画像内の物体の品質や状態を評価します。製品検査、不動産評価、品質管理などに役立ちます。
condition_prompt = '''
Assess the condition of the main subject in this image.
Rate on these dimensions (1-5 scale, 5=excellent):
- Physical condition: (1=heavily damaged, 5=like new)
- Cleanliness: (1=very dirty, 5=spotless)
- Completeness: (1=major parts missing, 5=fully intact)
For each rating, provide one-sentence evidence.
Return JSON:
{
"physical_condition": {"score": int, "evidence": str},
"cleanliness": {"score": int, "evidence": str},
"completeness": {"score": int, "evidence": str},
"overall_grade": "excellent|good|fair|poor",
"recommendation": str
}
'''
print('Condition assessment prompt defined.')
print('Useful for: product inspection, real estate, equipment maintenance.')Yes/No形式のVQA質問
二択のYes/No質問では、単純な真偽値が必要なのに、モデルが曖昧な文章で回答することを防ぐプロンプトが必要です。
def yes_no_question(image_path, question):
with open(image_path, 'rb') as f:
img_b64 = base64.standard_b64encode(f.read()).decode('utf-8')
prompt = f'''
Answer this yes/no question about the image.
Return JSON: {{"answer": "yes|no", "confidence": "high|medium|low", "reason": str}}
Do NOT answer with maybe, possibly, or a hedged statement.
If you genuinely cannot determine the answer, return {{"answer": "unclear", "confidence": "low", "reason": str}}
Question: {question}
'''
r = client.messages.create(
model='claude-opus-4-5', max_tokens=100,
messages=[{'role': 'user', 'content': [
{'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/jpeg', 'data': img_b64}},
{'type': 'text', 'text': prompt}
]}]
)
return json.loads(r.content[0].text)
# Example: 'Is there a safety helmet visible in the image?'
print('Yes/no VQA function defined.')VQA質問の連結
同じ画像について複数のVQA質問を1つのプロンプトにまとめると、API呼び出しの回数を減らせます。
multi_question_prompt = '''
Answer all of the following questions about this image.
Return a JSON object where each key is the question ID.
Questions:
1. How many people are visible?
2. What is the approximate age range of the youngest person?
3. Is there any food visible in the image?
4. What is the dominant color in the image?
5. Is the setting indoors or outdoors?
Return JSON:
{
"q1": {"answer": str},
"q2": {"answer": str},
"q3": {"answer": "yes|no", "details": str or null},
"q4": {"answer": str},
"q5": {"answer": "indoors|outdoors|unclear"}
}
'''
print('Multi-question VQA prompt — answers 5 questions in one API call.')VQAの不確実性への対応
VQAの質問には、確実に答えられないものもあります。画像がぼやけている、対象の要素が部分的に隠れている、答えが本当に曖昧である、といった場合です。推測を無理にさせるのではなく、明示的に不確実性を示すようプロンプトで求めてください。
uncertainty_vqa_prompt = '''
Answer this question about the image as precisely as possible.
If the answer is not clearly visible or is ambiguous, say so explicitly.
Question: {question}
Return JSON:
{
"answer": str,
"confidence": "high|medium|low|cannot_determine",
"limitation": str or null
}
For confidence levels:
- high: Answer is clearly visible and unambiguous
- medium: Visible but some uncertainty
- low: Partially visible or requires inference
- cannot_determine: Not enough visual information
Question: What brand is printed on the water bottle?
'''
print(uncertainty_vqa_prompt)ドメイン固有のVQAプロンプト
分野ごとに、必要とされるVQAの語彙や測定基準は異なります。ドメイン固有のプロンプトを使うと、より正確で実用的な回答が得られます。
# Manufacturing quality control VQA
qc_prompt = '''
Inspect this product image for quality defects.
Answer each question:
1. Are there any visible scratches or surface damage? (yes/no + location)
2. Is the product alignment within expected tolerance? (yes/no)
3. Are all required labels/markings present? (yes/no + list missing ones)
4. Overall QC result: PASS or FAIL?
Return JSON:
{"scratches": {"present": bool, "location": str or null},
"alignment_ok": bool,
"labels_complete": bool, "missing_labels": [str],
"qc_result": "PASS|FAIL",
"fail_reasons": [str]}
'''
# Food safety VQA
food_prompt = '''
Inspect this food preparation image.
1. Are gloves being worn? 2. Is hair covered? 3. Any visible contamination risk?
Return JSON: {"gloves": bool, "hair_covered": bool, "contamination_risk": bool, "details": str}
'''
print("Domain-specific QC and food safety VQA prompts defined.")クイックチェック
画像内の物体を数える場合、正確で利用しやすい回答を得られる可能性が最も高いVQAプロンプトはどれですか?
VQAプロンプト — 要点
効果的なVisual Question Answeringには、綿密に設計されたプロンプトが必要です。
- 質問は具体的かつ直接的にし、someやvariousのような曖昧な語は避けます
- カウントに関する質問では、部分的にしか見えていないものを数えるかどうかなど、境界ケースを明確に定義します
- 曖昧な文章による回答を防ぐため、出力形式(JSON、単一の数値、yes/noなど)を正確に指定します
- 不確かな出力を検出できるよう、すべての回答に信頼度レベルを含めます
- APIコストを削減するため、同じ画像に関する複数の質問は1回の呼び出しにまとめます
- 二択のyes/no質問では、unclearという逃げ道を含む曖昧な回答を明示的に防ぎます
- 医療、法律、製品などのドメイン固有のVQAでは、プロンプトにその分野の用語を含める必要があります
よくある質問
「画像に関する質問応答」レッスンは無料ですか?
はい。「画像に関する質問応答」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Prompt Engineeringコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Prompt Engineeringコースには全4レッスンが含まれています。
「画像に関する質問応答」で何を学びますか?
画像の内容、数量、属性について具体的な質問をします。 ブラウザで直接実行するハンズオンコードでAI Prompt Engineeringを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
AI Prompt Engineeringを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのAI Prompt Engineeringは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「画像に関する質問応答」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このAI Prompt Engineeringレッスンでコードを書いて実行できますか?
はい。すべてのAI Prompt Engineeringレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。