LoginSignup
0
0

More than 5 years have passed since last update.

Google colaboratoryからGoogleDriveの画像読み書きテスト

Last updated at Posted at 2018-09-23

タダで使えるGoogle ColabとGoogleDriveの連携技をやってみた。
CPUパワー&ストレージを仮想マシンが持ってくれて、Azureみたいなことがタダでできちゃう。

GoogleDriveFileOpen.py
#! pip install pydrive

# pydriveでGoogle Driveの認証設定
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

#ここは、GoogleDriveのURLから持ってくる「https://drive.google.com/drive/folders/XXXXXXXXXXXXXXX」
id = "XXXXXXXXXXXXXXX"

#ファイル一覧表示して、IDをチェック
filelist = drive.ListFile({'q': "'%s' in parents and trashed=false" % id}).GetList()

#とりあえずjpgファイル1つめ
for f in filelist:
  if "jpg" in f["title"]:
    print("filename:" + f["title"] + ", id:" + f["id"])
    fname = f["title"]
    fid = f["id"]
    break

#GoogleDriveでまずコンテンツを開く
drivefile = drive.CreateFile({'id': fid})
drivefile.GetContentFile(fname)

#ここからは普通の画像ファイルと同じ
from PIL import Image
from PIL import ImageOps
import numpy as np

img = Image.open(fname)
print(img.format, img.size)

# 画像を256x256にリサイズしてノーマライズしてみる
resizeimg = img.resize((256,256), Image.LANCZOS)
img2 = ImageOps.equalize(resizeimg)
# numpy配列にするなら以下
#array = np.asarray(img2)
#print(array)

#結果を別ファイルとして出力
outfilename = "normalized.jpg"
driveoutfile = drive.CreateFile({'title': outfilename, 'mimeType': 'image/jpeg'})
driveoutfile.SetContentFile(outfilename)
driveoutfile.Upload()

見た目はまんまJupiter Notebook
スクリーンショット_2018-09-23_23-14-15.png

[参考]
https://qiita.com/pashango2/items/145d858eff3c505c100a
https://qiita.com/uni-3/items/201aaa2708260cc790b8
https://qiita.com/uni-3/items/201aaa2708260cc790b8
https://note.nkmk.me/python-numpy-image-processing/

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