djeetee
djeetee

Reputation: 1837

Loading images in google colab

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?

Upvotes: 26

Views: 187247

Answers (11)

Bruno Degomme
Bruno Degomme

Reputation: 1143

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

Upvotes: 5

Elvin Aghammadzada
Elvin Aghammadzada

Reputation: 881

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()

Upvotes: 1

DINA TAKLIT
DINA TAKLIT

Reputation: 8388

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) 

Upvotes: 2

Camdun
Camdun

Reputation: 9

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()

Upvotes: 0

Akhilesh_IN
Akhilesh_IN

Reputation: 1327

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")

Upvotes: 2

DataFramed
DataFramed

Reputation: 1631

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()

Upvotes: 13

Pallawi.ds
Pallawi.ds

Reputation: 113

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.

Upvotes: 4

korakot
korakot

Reputation: 40838

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.

Upvotes: 25

minakshi das
minakshi das

Reputation: 111

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()

Upvotes: 7

Yasser M
Yasser M

Reputation: 672

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!

Upvotes: 15

Pais
Pais

Reputation: 63

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.

Upvotes: 1

Related Questions