google colaboratoryとgoogle driveの特定のディレクトリ内のファイル名を比較
google colaboratoryを使って画像認識をしてみた。教師データが正しいかどうかを目で見て確認するのにgoogle driveを使いたい。
- google colaboratory上でスクレイピングして画像を集める
- 写真が合ってるか(キーワードで検索の結果なので、間違った画像もたくさんある)を確かめるために、一旦google driveにコピー
- google driveのWeb画面で不要なファイルを削除
- 削除したファイルをgoogle colaboratory上のゲストOS上にも反映させる
ということがやりたかったので、そのメモ。
(再帰的に比較とか複雑なことをやっているわけではなく、特定のディレクトリ同士を比較)
実行
google driveのマウント
from google.colab import drive drive.mount('/content/drive')
認証キーを求められるので、別画面で確認したキーを入力し、Enter
mountできたかどうか確認
google driveのrootが、/content/drive/My Drive という名前でマウントされる。My Driveと間にスペースが入っているので注意。このスペースありの命名した人ちょっと来なさいと言いたい...
!ls '/content/drive/My Drive'
画像収集
ここでは、猫の画像(*.jpg形式)をスクレイピングして、image_data/cat/ 配下に格納したとする。
プログラムは割愛。
google colaboratory --> google drive へファイルコピー
google drive上にディレクトリを作成し、コピー。distutils.dir_utilは、ディレクトリが存在してもコピーできる。
import os # google colaboratory上の画像収集directory名 images_dir = 'image_data/cat' # google drive上のdirectory名。colab_work_tmp(名前は任意)の下にdirectory を作成して作業したい。 gdir = '/content/drive/My Drive/colab_work_tmp/' + images_dir # ディレクトリ作成 if not os.path.exists(gdir): os.makedirs(gdir) # images_dir --> gdir にコピー from distutils.dir_util import copy_tree copy_tree(images_dir, gdir)
google drive上でファイルを削除(手動で)
google drive のWebUIで、ファイルを見て不要なファイルを削除。
ディレクトリ同士を比較し、google drive上で削除されたファイルを、google colaboratoryでも削除
image_data/leo/ 配下に、ライオンの画像を格納したので、ここでは image_data/cat と image_data/leoをまとめて処理する。
imagepath = ['image_data/cat/','image_data/leo/'] gdir = '/content/drive/My Drive/colab_work_tmp/' from pathlib import Path for i in imagepath: p = Path(i) #pathオブジェクトを作成 p.glob('*.jpg') #比較対象は *.jpg のみ # google colaboratory上のファイルを1つずつ、google driveでのpath名を作成して存在を確認、存在しなければ削除 for fpath in p.glob('*.jpg'): gpath = gdir + str(fpath) if not os.path.exists(gpath): print(fpath) os.remove(fpath)