正在 google colab 中加载图像

Loading images in google colab

我的 Jupyter Notebook 使用以下代码将图像上传到 Colab:

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

系统提示我输入文件。哪个被上传。

我使用以下方式验证文件上传是否成功:

!ls

我看到它就在那里。

我使用以下方法检查当前工作目录:

import os
os.getcwd()

它告诉我它是 /content

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

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

加载文件失败。

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

对正在发生的事情有什么想法吗?

我假设您可能没有从内存中写入文件?

上传后尝试以下代码:

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

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

希望这对你有用。

使用此功能上传文件。它也会保存它们。

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

更新

现在(2018 年 9 月),左侧窗格有一个 "Files" 选项卡,可让您轻松浏览文件和上传文件。您也可以直接双击文件名进行下载。

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

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

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

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

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

data.printdir()

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- 就是这样!享受吧!

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

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

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

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

import matplotlib.pyplot as plt

plt.imshow(im)
plt.show()

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

!wget "copy paste the image address here"

检查!ls

使用以下代码显示图像:

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

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

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

代码解释

一旦你 运行 colab 中的这段代码,就会出现一个带有两个按钮 "Chose file" 和 "cancel upload" 的小图形用户界面,使用这些按钮你可以选择任何本地文件并上传。

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

运行 这个命令:

import os
!ls
os.getcwd()

!ls - 将为您提供上传的文件名

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

"----------------------------从上传的文件中获取图像数据- --------------

运行代码:

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)

代码解释

第 1 行:

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

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

第 3 至 9 行:

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

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

结尾的文件

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

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

第 7 行你可以打印完整路径

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

第9行可以打印图像数据

"-------------------------查看图片----- --------------------

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)

快乐编码,就这么简单。

更简单的方法:

因为 colab 提供了挂载 google 驱动器的选项

  1. 将图像上传到您的 google 驱动器
  2. 点击安装驱动器(上传图标右侧)
  3. 查看 'drive/My Drive/'
  4. 下的文件

检查文件的代码

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

将其上传到笔记本后,执行此操作

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

您可以通过单击左侧的文件夹绘图按钮将文件手动上传到 google colab 工作目录。然后就可以像在您的计算机上一样访问它们。

您可以使用此函数绘制您的图像,给出 路径。 使用函数是构建代码的好方法。

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