Skip to content

Instantly share code, notes, and snippets.

@myurasov
Created April 8, 2021 09:21
Show Gist options
  • Save myurasov/da47e08bc20ef91f789f61d2b4abc93c to your computer and use it in GitHub Desktop.
Save myurasov/da47e08bc20ef91f789f61d2b4abc93c to your computer and use it in GitHub Desktop.
Image_Resize_TF_vs_PIL
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from multiprocessing import Pool, cpu_count\n",
"\n",
"import numpy as np\n",
"import tensorflow as tf\n",
"from PIL import Image\n",
"from tqdm import tqdm"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"N = 1000"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def _resize_tf(_):\n",
" x = Image.open(\"dog.jpg\")\n",
" x = tf.constant(np.array(x))\n",
" x = x[tf.newaxis, ...]\n",
" x = tf.image.resize(x, [224, 224], method=tf.image.ResizeMethod.BICUBIC)[\n",
" 0, ...\n",
" ].numpy()\n",
"\n",
"\n",
"def _resize_PIL(_):\n",
" x = Image.open(\"dog.jpg\")\n",
" x = x.resize((224, 224), Image.BICUBIC)\n",
" x = np.array(x)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 1000/1000 [00:02<00:00, 384.79it/s]\n"
]
}
],
"source": [
"with Pool(cpu_count()) as pool:\n",
" X = list(\n",
" tqdm(\n",
" pool.imap(\n",
" _resize_PIL,\n",
" range(N),\n",
" ),\n",
" total=N,\n",
" smoothing=0,\n",
" )\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 1000/1000 [00:38<00:00, 25.74it/s]\n"
]
}
],
"source": [
"for i in tqdm(range(N), smoothing=0):\n",
" _resize_tf(i)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|██████████| 1000/1000 [00:45<00:00, 21.89it/s]\n"
]
}
],
"source": [
"for i in tqdm(range(N), smoothing=0):\n",
" _resize_PIL(i)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"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": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment