python-3.x - 使用 Python Pillow 在 Google Colab 上调整图像大小
问题描述
我的 ipynb 和一个名为 PRimage 的文件夹(包含 100 多张图像)在我的 google 驱动器中,并且我的驱动器已经安装在 /content/drive 中。我的图像按顺序排列,例如。1_1.jpg、1_2.jpg 等。我正在尝试使用 for 循环来调整所有图像的大小,如下所示:
from google.colab import drive
drive.mount('/content/drive')
from os import listdir
from matplotlib import image
from PIL import Image
loaded_images = list()
for filename in listdir('/content/drive/My Drive/PRimage'):
img_data = image.imread('/content/drive/My Drive/PRimage/'+ filename)
loaded_images.append(img_data)
print('> loaded %s %s' % (filename, img_data.shape))
def resize():
files = listdir('/content/drive/My Drive/PRimage')
for item in files:
image = Image.open(item)
image.thumbnail((64,64))
print(image.size)
resize()
但是,我收到此错误消息:
解决方案
插入一个新的代码单元并用于pwd
检查您当前的工作目录。确保它位于/content/drive/My Drive/PRimage
. 用于cd /content/drive/My\ Drive/PRimage
更改目录。你FileNotFoundError
是你未知密码的原因。在这种情况下,请始终查找您的根工作目录。您的代码从 pwd 执行,并期望其中有类似的 dir 结构。
调整图像大小的辅助函数
def resize_image(src_img, size=(64,64), bg_color="white"):
from PIL import Image
# rescale the image so the longest edge is the right size
src_img.thumbnail(size, Image.ANTIALIAS)
# Create a new image of the right shape
new_image = Image.new("RGB", size, bg_color)
# Paste the rescaled image onto the new centered background
new_image.paste(src_img, (int((size[0] - src_img.size[0]) / 2), int((size[1] - src_img.size[1]) / 2)))
# return the resized image
return new_image
# get the list of test image files
test_folder = '/content/drive/My Drive/PRimage'
test_image_files = os.listdir(test_folder)
# Empty array on which to store the images
image_arrays = []
size = (64,64)
background_color="white"
# Get the images
for file_idx in range(len(test_image_files)):
img = Image.open(os.path.join(test_folder, test_image_files[file_idx]))
# resize the image
resized_img = np.array(resize_image(img, size, background_color))
# Add the image to the array of images
image_arrays.append(resized_img)
推荐阅读
- destructuring - Hylang 地图解构
- powershell - 获取证书到期日期powershell
- ruby - 忽略特定的 \n 字符,同时仍然启用 m 标志
- python - Python 3.6.5 中的 Base58 和 utf-8 编码问题
- docker - 离开 docker swarm,但让服务继续运行
- swift - 'initializeMemory(as:at:count:to:)' 已弃用
- excel - 使用日期隐藏excel中的列
- php - php - 表单提交按钮不起作用
- labview - 在LabVIEW中解压从串口读取的二进制数据
- php - 使用 javascript 从 echo 下拉列表中传递数据