24

My Jupyter Notebook has the following code to upload an image to Colab:

from google.colab import files
uploaded = files.upload()

I get prompted for the file. Which gets uploaded.

I verify that the file upload was successful using:

!ls

and I see that it's there.

I check the current working directory using:

import os
os.getcwd()

and it tells me that it is /content

now, the following call fails:

assert os.path.exists(img_path)

It also fails whether i'm using just the file name or the full path.

Any thoughts on what is going on?

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
djeetee
  • 1,799
  • 7
  • 24
  • 36
  • Are you sure that the files are there? `files.upload()` normally doesn’t save the files. – korakot Mar 09 '18 at 06:49
  • Does this answer your question? [How can I open images in a Google Colaboratory notebook cell from uploaded png files?](https://stackoverflow.com/questions/49478791/how-can-i-open-images-in-a-google-colaboratory-notebook-cell-from-uploaded-png-f) which is also a possible duplicate. – Jarmos Apr 09 '20 at 10:55

11 Answers11

25

Use this function to upload files. It will SAVE them as well.

def upload_files():
  from google.colab import files
  uploaded = files.upload()
  for k, v in uploaded.items():
    open(k, 'wb').write(v)
  return list(uploaded.keys())

Update

Now (sep 2018), the left pane has a "Files" tab that let you browse files and upload files easily. You can also download by just double click the file names.

korakot
  • 37,818
  • 16
  • 123
  • 144
15

Colab google: uploading images in multiple subdirectories: If you would like to upload images (or files) in multiples subdirectories by using Colab google, please follow the following steps: - I'll suppose that your images(files) are split into 3 subdirectories (train, validate, test) in the main directory called (dataDir): 1- Zip the folder (dataDir) to (dataDir.zip) 2- Write this code in a Colab cell:

from google.colab import files
uploaded = files.upload()

3- Press on 'Choose Files' and upload (dataDir.zip) from your PC to the Colab Now the (dataDir.zip) is uploaded to your google drive! 4- Let us unzip the folder(dataDir.zip) to a folder called (data) by writing this simple code:

import zipfile
import io
data = zipfile.ZipFile(io.BytesIO(uploaded['dataDir.zip']), 'r')
data.extractall()

5- Now everything is ready, let us check that by printing content of (data) folder:

data.printdir()

6- Then to read the images, count them, split them and play around them, please write the following code:

train_data_dir = 'data/training'  
validation_data_dir = 'data/validation'  
test_data_dir = 'data/test' 
target_names = [item for item in os.listdir(train_data_dir) if os.path.isdir(os.path.join(train_data_dir, item))]
nb_train_samples = sum([len(files) for _, _, files in os.walk(train_data_dir)])  
nb_validation_samples = sum([len(files) for _, _, files in os.walk(validation_data_dir)])
nb_test_samples = sum([len(files) for _, _, files in os.walk(test_data_dir)])
total_nb_samples = nb_train_samples + nb_validation_samples + nb_test_samples

nb_classes = len(target_names)      # number of output classes

print('Training a CNN Multi-Classifier Model ......')
print('\n - names of classes: ', target_names, '\n - # of classes: ', nb_classes)
print(' - # of trained samples: ', nb_train_samples, '\n - # of validation samples: ', nb_validation_samples,
      '\n - # of test samples: ', nb_test_samples,
       '\n - total # of samples: ', total_nb_samples, '\n - train ratio:', round(nb_train_samples/total_nb_samples*100, 2),
      '\n - validation ratio:', round(nb_validation_samples/total_nb_samples*100, 2),
      '\n - test ratio:', round(nb_test_samples/total_nb_samples*100, 2),
     ' %', '\n - # of epochs: ', epochs, '\n - batch size: ', batch_size)

7- That is it! Enjoy!

Yasser M
  • 654
  • 7
  • 9
  • man thank you so much for the response. The missing piece in what I was doing was using zip files. Doing that will solve the issue of creating folder/subfolder!!! I will give it a try :) tanks again. – djeetee Mar 28 '18 at 13:12
  • No problem! Meanwhile, u can use the same function to upload (.py) file and then to import it to your colab notebook. – Yasser M Mar 29 '18 at 13:19
13

Hack to upload image file in colab!

https://colab.research.google.com/

Following code loads image (file(s)) from local drive to colab.

from google.colab import files
from io import BytesIO
from PIL import Image

uploaded = files.upload()
im = Image.open(BytesIO(uploaded['Image_file_name.jpg']))

View the image in google colab notebook using following command:

import matplotlib.pyplot as plt

plt.imshow(im)
plt.show()
GStav
  • 1,066
  • 12
  • 20
DataFramed
  • 1,491
  • 16
  • 21
6

You can an image on colab directly from internet using the command

!wget "copy paste the image address here"

check with!ls

Display the image using the code below:

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread("Sample-image.jpg")
img_cvt=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img_cvt)
plt.show()
minakshi das
  • 101
  • 2
  • 3
5

You can upload files manually to your google colab working directory by clicking on the folder drawing button on the left. They are then accessible just as they would be on your computer.

enter image description here

Bruno Degomme
  • 883
  • 10
  • 11
  • Do you have a code example? I thought using this would work, but it's not working. `from PIL import Image as im im.open(dragon.png) im.show()` – Azurespot Aug 27 '21 at 18:14
  • The following worked for me ```from PIL import Image im = Image.open("dragon.png") im```. im.show() is buggy on google colab, just use "im" instead (see https://stackoverflow.com/questions/60034512/cant-show-an-image-using-pil-on-google-colab) – Bruno Degomme Aug 28 '21 at 09:45
4

The simplest way to upload, read and view an image file on google Colab.

"---------------------Upload image to colab -code---------------------------"

from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

Code explanation

Once you run this code in colab, a small gui with two buttons "Chose file" and "cancel upload" would appear, using these buttons you can choose any local file and upload it.

"---------------------Check if image was uploaded---------------------------"

Run this command:

import os
!ls
os.getcwd()

!ls - will give you the uploaded files names

os.getcwd() - will give you the folder path where your files were uploaded.

"---------------------------get image data from uploaded file--------------"

Run the code:

0 import cv2
1 items = os.listdir('/content')
2 print (items)
3 for each_image in items:
4  if each_image.endswith(".jpg"):
5   print (each_image)
6   full_path = "/content/" + each_image
7   print (full_path)
8   image = cv2.imread(full_path)
9   print (image)

Code explanation

line 1:

items = os.listdir('/content')
print(items)

items will have a list of all the filenames of the uploaded file.

line 3 to 9:

for loop in line 3 helps you to iterate through the list of uploaded files.

line 4, in my case I only wanted to read the image file so I chose to open only those files which end with ".jpg"

line 5 will help you to see the image file names

line 6 will help you to generate full path of image data with the folder

line 7 you can print the full path

line 8 will help you to read the color image data and store it in image variable

line 9 you can print the image data

"--------------------------view the image-------------------------"

import matplotlib.pyplot as plt
import os
import cv2
items = os.listdir('/content')
print (items)    

for each_image in items:
  if each_image.endswith(".jpg"):
    print (each_image)
    full_path = "/content/" + each_image
    print (full_path)
    image = cv2.imread(full_path)
    image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
plt.figure()
plt.imshow(image)
plt.colorbar()
plt.grid(False)

happy coding and it simple as that.

Pallawi.ds
  • 103
  • 1
  • 7
2

Simpler Way:

As colab gives options to mount google drive

  1. Upload images to your google drive
  2. Click on mount drive (right side of upload icon)
  3. See files under 'drive/My Drive/'

code to check files

import glob
glob.glob("drive/My Drive/your_dir/*.jpg")
Akhilesh_IN
  • 1,217
  • 1
  • 13
  • 19
2

You can use this function to plot ur images giving a path. using function is good thing to well structure your code.

from PIL import Image # Image manipulations
import matplotlib.pyplot as plt
%matplotlib inline

# This function is used more for debugging and showing results later. It plots the image into the notebook
def imshow(image_path):
  # Open the image to show it in the first column of the plot 
  image = Image.open(image_path)  
  # Create the figure 
  fig = plt.figure(figsize=(50,5))
  ax = fig.add_subplot(1, 1, 1) 
  # Plot the image in the first axe with it's category name
  ax.axis('off')
  ax.set_title(image_path)
  ax.imshow(image) 
DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74
1

Am assuming you might not have written the file from memory?

try the below code after the upload:

with open("wash care labels", 'w') as f:
    f.write(uploaded[uploaded.keys()[0]])

replace "wash care labels.xx" with your file name. This writes the file from memory. then try calling the file.

Hope this works for you.

Pais
  • 63
  • 1
  • 7
  • to reference the file names: uploaded[uploaded.keys()[0]] does not work as indexing is not possible. the dictionary needs to be converted to a list: list(uploaded.keys())[0]. Still the code runs but loading the image fails. – djeetee Mar 09 '18 at 15:41
1
from deepface import DeepFace
import cv2
import matplotlib.pyplot as plt

from google.colab import files
from io import BytesIO
from PIL import Image

uploaded = files.upload()


next line

# im = Image.open(BytesIO(uploaded['img.PNG']))
img = cv2.imread("theCorona.PNG")
plt.imshow(img[:,:, ::-1])
plt.show()
0

after you uploaded it to your notebook, do this

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

img = cv2.imread('./your image file.jpg')
cv2_imshow(img)
cv2.waitKey()
Camdun
  • 9
  • 1