Python 在 google colab 中加载图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49186905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:00:52  来源:igfitidea点击:

Loading images in google colab

pythonopencvgoogle-colaboratory

提问by djeetee

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

我的 Jupyter Notebook 有以下代码可以将图像上传到 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

它告诉我它是 /content

now, any of the following calls...

现在,以下任何调用...

cv2.imread(img_path, 1)
cv2.imread(img_path, 0)
cv2.imread(img_path)

fails to load the file.

无法加载文件。

they also fail whether i'm using just the file name or the full path.

无论我只使用文件名还是完整路径,它们也会失败。

Any thoughts on what is going on?

关于发生了什么的任何想法?

回答by korakot

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.

现在(2018 年 9 月),左窗格有一个“文件”选项卡,可让您轻松浏览文件和上传文件。您也可以通过双击文件名来下载。

回答by Yasser Mustafa

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:

Colab google:在多个子目录中上传图片:如果您想使用 Colab google 在多个子目录中上传图片(或文件),请按照以下步骤操作: - 我假设您的图片(文件)被分成 3 个子目录(训练、验证、测试)在名为 (dataDir) 的主目录中: 1- 将文件夹 (dataDir) 压缩到 (dataDir.zip) 2- 在 Colab 单元格中编写此代码:

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:

3- 按“选择文件”并从您的 PC 上传 (dataDir.zip) 到 Colab 现在 (dataDir.zip) 已上传到您的谷歌驱动器!4-让我们通过编写以下简单代码将文件夹(dataDir.zip)解压缩到名为(data)的文件夹中:

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:

5- 现在一切都准备好了,让我们通过打印(数据)文件夹的内容来检查:

data.printdir()

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

6-然后读取图像,计算它们,拆分它们并播放它们,请编写以下代码:

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!

7-就是这样!享受!

回答by DataFramed

Hack to upload image file in colab!

破解在 colab 中上传图像文件!

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

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

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

以下代码将图像(文件)从本地驱动器加载到 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:

使用以下命令在 google colab notebook 中查看图像:

import matplotlib.pyplot as plt

plt.imshow(im)
plt.show()

回答by minakshi das

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

您可以使用以下命令直接从互联网上的 colab 上的图像

!wget "copy paste the image address here"

check with!ls

检查!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()

回答by Pallawi.ds

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

在 google Colab 上上传、读取和查看图像文件的最简单方法。

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

"---------------------上传图片到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.

在 中运行此代码后colab,将出现一个带有“选择文件”和“取消上传”两个按钮的小 gui,使用这些按钮您可以选择任何本地文件并上传。

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

"---------------------检查图片是否上传--------------- ----”

Run this command:

运行此命令:

import os
!ls
os.getcwd()

!ls- will give you the uploaded files names

!ls- 会给你上传的文件名

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

os.getcwd()- 将为您提供上传文件的文件夹路径。

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

第 1 行:

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

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

items 将包含上传文件的所有文件名的列表。

line 3 to 9:

第 3 至 9 行:

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

for第 3 行中的循环可帮助您遍历上传的文件列表。

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"

第 4 行,在我的例子中,我只想读取图像文件,所以我选择只打开那些以 ".jpg"

line 5 will help you to see the image file names

第 5 行将帮助您查看图像文件名

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

第 6 行将帮助您使用文件夹生成图像数据的完整路径

line 7 you can print the full path

第 7 行,您可以打印完整路径

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

第 8 行将帮助您读取彩色图像数据并将其存储在image变量中

line 9 you can print the image data

第 9 行,您可以打印图像数据

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

快乐编码,就这么简单。

回答by Akhilesh_IN

Simpler Way:

更简单的方法:

As colab gives options to mount google drive

由于 colab 提供了挂载谷歌驱动器的选项

  1. Upload images to your google drive
  2. Click on mount drive (right side of upload icon)
  3. See files under 'drive/My Drive/'
  1. 将图片上传到您的谷歌驱动器
  2. 单击安装驱动器(上传图标右侧)
  3. 查看下的文件 'drive/My Drive/'

code to check files

检查文件的代码

import glob
glob.glob("drive/My Drive/your_dir/*.jpg")

回答by Camdun

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

回答by Pais

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.

用您的文件名替换“wash care labels.xx”。这将从内存中写入文件。然后尝试调用该文件。

Hope this works for you.

希望这对你有用。