Skip to content

Instantly share code, notes, and snippets.

@aaossa
Created November 29, 2022 20:02
Show Gist options
  • Save aaossa/68e3ef2d5432e566030af889de03df21 to your computer and use it in GitHub Desktop.
Save aaossa/68e3ef2d5432e566030af889de03df21 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"import PIL\n",
"from PIL import Image, ImageFile\n",
"from tqdm import tqdm\n",
"\n",
"\n",
"# Needed for some images in Pinterest and Wikimedia dataset\n",
"PIL.Image.MAX_IMAGE_PIXELS = 3000000000\n",
"# Some images are \"broken\" in Wikimedia dataset\n",
"ImageFile.LOAD_TRUNCATED_IMAGES = True\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from torchvision import transforms\n",
"\n",
"images_transforms = transforms.Compose([\n",
" transforms.Resize(256),\n",
" transforms.CenterCrop(224),\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Parameters\n",
"INPUT_DIR = os.path.join(\"images\", \"img\")\n",
"OUTPUT_DIR = os.path.join(\"mini-images-224-224-v2\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create OUTPUT_DIR if not exists\n",
"os.makedirs(OUTPUT_DIR, exist_ok=True)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for file in tqdm(os.listdir(INPUT_DIR)[::-1]):\n",
" input_path = os.path.join(INPUT_DIR, file)\n",
" if not os.path.isfile(input_path):\n",
" print(\"input_path is not file\", input_path)\n",
" continue\n",
" output_path = os.path.join(OUTPUT_DIR, file)\n",
" if os.path.exists(output_path):\n",
" continue\n",
" image = Image.open(input_path).convert(\"RGB\")\n",
" # image = image.resize(TARGET_SIZE, resample=PIL.Image.BILINEAR)\n",
" image = images_transforms(image)\n",
" image.save(output_path)\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "3.8.5",
"language": "python",
"name": "3.8.5"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment