Loading images in google colab

限于喜欢 提交于 2019-12-02 18:38:10

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.

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!

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

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.

DataFramed

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!