はじめに
私は組込みエンジニアですが、最近はChatGPT等のGenerative AIのおかげでアイデアさえあればアプリを簡単に実装できる時代になっています。(エンジニアとしてはすごいと思う反面、何か悲しい気持ちもありますが…)ということでChatGPTを活用しながら全く知らない言語やライブラリで何か継続して作っていこう!という試みです。もう何番煎じかわからないし、水くらい薄いですが、BeautifulSoupを使って画像検索スライドショーを作ってみたので需要はないですが、自分のモチベ維持のために投稿します。
*Python, BeautifulSoupに関しては大昔に自力でも実装しているのですが、第一弾ということで…
成果物
コード
バージョン
- python 3.10.9
from bs4 import BeautifulSoup
import requests
import cv2
import time
import numpy as np
url = 'https://www.google.com/search?q='
# get user input
user_input = input("Enter a word you want to search: ")
# get image url
search_url = url + user_input + '&source=lnms&tbm=isch'
response = requests.get(search_url)
soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')
urls = [img['src'] for img in img_tags]
del urls[0]
# display images
for url in urls:
img_response = requests.get(url)
img_array = np.array(bytearray(img_response.content), dtype=np.uint8)
img = cv2.imdecode(img_array, -1)
cv2.namedWindow("slideshow", cv2.WINDOW_NORMAL)
cv2.imshow("slideshow", img)
cv2.waitKey(3000)
time.sleep(1)
改良案
- 元画像ではなくリサイズ済み画像を参照しているので見られる画像が小さいし、荒い
参考文献
なし