Изменение размера изображений в Google Colab с использованием подушки Python - PullRequest
0 голосов
/ 18 января 2020

У меня есть ipynb и папка с именем PRimage (более 100 изображений) на моем диске Google, и мой диск уже смонтирован в / content / drive. Мои изображения расположены в последовательности, например. 1_1.jpg, 1_2.jpg и так далее. Я пытаюсь использовать для l oop, чтобы изменить размеры всех изображений, например:

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

Однако я получаю это сообщение об ошибке:

enter image description here

1 Ответ

0 голосов
/ 20 января 2020

Вставьте новую ячейку кода и используйте pwd, чтобы проверить текущий рабочий каталог . Убедитесь, что это на /content/drive/My Drive/PRimage. Используйте cd /content/drive/My\ Drive/PRimage, чтобы изменить каталоги. Ваш FileNotFoundError является причиной вашего неизвестного pwd. Всегда ищите ваши root рабочие каталоги в таких случаях. Ваш код выполняется из 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...