如何在Google Colaboratory中显示位于非公开Goog​​le云端硬盘文件夹中的图片

时间:2018-01-11 14:42:44

标签: python google-colaboratory

有没有优雅的方式显示位于非公共驱动器文件夹中的图像,除了使用某个python库下载和显示它?

这是我目前的解决方案:

import matplotlib.pyplot as plt
import cv2
import numpy as np
import io

from google.colab import files
from googleapiclient.http import MediaIoBaseDownload
from googleapiclient.discovery import build
from google.colab import auth
from oauth2client.client import GoogleCredentials
from urllib.request import urlopen

# Connect to Google Drive
auth.authenticate_user()

# Open image file as BGR Mat 
def gdrive_open_image(file_id):
  # Get byte stream
  data = gdrive_open_file(file_id)
  # Decode the array into an image
  return cv2.imdecode(np.fromstring(data, dtype='uint8'), cv2.IMREAD_COLOR)


# Open arbitary file as bytestream
def gdrive_open_file(file_id):
  drive_service = build('drive', 'v3')
  request = drive_service.files().get_media(fileId=file_id)
  stream = io.BytesIO()
  downloader = MediaIoBaseDownload(stream, request)
  done = False
  while done is False:
    status, done = downloader.next_chunk()

  return stream.getvalue()

# Display Image
plt.imshow(cv2.cvtColor(gdrive_open_image('some_file_id'), cv2.COLOR_BGR2RGB), aspect='equal', interpolation='bicubic')
plt.axis('off')
plt.show()

0 个答案:

没有答案