Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save files from Google Colab to Google Drive

I'm doing some image manipulation, and I'm able to download the images, but trying to figure out how to save the images directly to google drive.

  mask_out=cv2.subtract(rgb,img)
  mask_out=cv2.subtract(rgb,mask_out)
  mask_out[rgb == [20, 0, 25]] = 255
  cv2.imwrite('out4.jpeg' , mask_out)
  cv2_imshow(mask_out)
  cv2.waitKey(0)
  cv2.imwrite('res.png' , mask_out)    
  files.download('res.png')

you can see from the code that the desired image exists within the mask-out variable. It's easy enough to read files from Drive in Colab but I can't find the docs on saving files.

like image 645
user379468 Avatar asked Nov 12 '20 16:11

user379468


2 Answers

Easy way to save is to mount google drive and provide path to the folder in drive where files need to be saved.

Mount Drive

from google.colab import drive
drive.mount('/content/drive')

Generate Random Image and show

import cv2
import numpy as np
from google.colab.patches import cv2_imshow

rgb_img = np.random.randint(0, 255, size=(400,400,3), dtype=np.uint8)

#cv2.imshow('RGB', rgb_img)
#cv2.waitKey(0)

cv2_imshow(rgb_img)

Save image to drive directly

Path to save in drive can be found easily by clicking files on left side, navigating to folder and right click to choose Copy path. This will save the image to folder named Delete in Google Drive.

# Save Image
cv2.imwrite('/content/drive/My Drive/Delete/res.png' , rgb_img)

Using copy command

This was not asked but can be useful. Assuming /content/res.png is image path and /content/drive/My Drive/Delete is destination.

Alternate option is write image in colab and copy to drive using !cp "/content/res.png" "/content/drive/My Drive/Delete" after drive mount.

like image 157
B200011011 Avatar answered Oct 06 '22 03:10

B200011011


First of all you have to share a google drive folder in "edit" mode, for example: https://drive.google.com/drive/folders/1wNJUZtQD_6oBvvUhWRlAb0xjjjoLZQ?usp=sharing (the link is not valid, it's just an example)

The id you need to copy into the code is: 1wNJUZtQD_6oBvvUhWRlAb0xjjjoLZQ

!pip install --upgrade gupload

from pydrive.auth import GoogleAuth
from google.colab import auth

# Authenticate and create the PyDrive client.
auth.authenticate_user()

!gupload --to '1wNJUZtQD_6oBvvUhWRlAb0xjjjoLZQ' res.png

# if multiple images
# !gupload --to '1wNJUZtQD_6oBvvUhWRlAb0xjjjoLZQ' *.png
like image 36
RashidLadj_Winux Avatar answered Oct 06 '22 01:10

RashidLadj_Winux