はじめに
美術館に足を運ぶのが難しい時でも、世界中の名画を楽しめたら素敵だと思いませんか?
現代のテクノロジー、特にPythonとオープンAPIを組み合わせれば、それが実現できます。
今回ご紹介するのは、アメリカ・ニューヨークの**メトロポリタン美術館(The Metropolitan Museum of Art / 通称:MET)**が提供している公式APIを使って、
ランダムな名画をPythonで取得・表示するミニアプリです。
インストール不要のライブラリと数行のコードで、
自宅にいながら毎日違う作品を楽しむ「おうち美術館」がすぐに実現できます。
使用するもの
-
requests
:APIからデータを取得 -
PIL
(Pillow):画像処理 -
matplotlib
:画像をきれいに表示 - METの公開API:https://metmuseum.github.io/
Pythonコード
import requests
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
import random
# METの全オブジェクトIDを取得
all_ids_url = "https://collectionapi.metmuseum.org/public/collection/v1/objects"
all_ids = requests.get(all_ids_url).json()["objectIDs"]
# シャッフルして先頭200件を使う(画像がないものを除外するため多めに取る)
random.shuffle(all_ids)
selected_ids = all_ids[:200]
# 最大10点の画像付き作品を表示
count = 0
for object_id in selected_ids:
if count >= 10:
break
url = f"https://collectionapi.metmuseum.org/public/collection/v1/objects/{object_id}"
res = requests.get(url).json()
title = res.get("title", "No Title")
artist = res.get("artistDisplayName", "Unknown Artist")
image_url = res.get("primaryImageSmall", "")
# 画像がある作品のみ処理
if image_url:
try:
img = Image.open(BytesIO(requests.get(image_url).content))
plt.figure(figsize=(4, 4))
plt.imshow(img)
plt.axis("off")
plt.title(f"{title}\n{artist}", fontsize=10)
plt.tight_layout()
plt.show()
count += 1
except:
continue