0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MET美術館のAPIを使って美術をランダムに鑑賞しよう

Posted at

はじめに

美術館に足を運ぶのが難しい時でも、世界中の名画を楽しめたら素敵だと思いませんか?

現代のテクノロジー、特に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

実行結果

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?