My Jupyter Notebook has the following code to upload an image to Colab:
from google.colab import files
uploaded = files.upload()
I get prompted
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.