Skip to content

Instantly share code, notes, and snippets.

@rupeshknn
Created October 16, 2022 04:45
Show Gist options
  • Select an option

  • Save rupeshknn/1194d211d98e02afcc881c568c502ca4 to your computer and use it in GitHub Desktop.

Select an option

Save rupeshknn/1194d211d98e02afcc881c568c502ca4 to your computer and use it in GitHub Desktop.
combine images of different sizes with same width
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "fc99d84f",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import numpy as np\n",
"from PIL import Image"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "0703e8ce",
"metadata": {},
"outputs": [],
"source": [
"images_dir = r\"combine_images/\"\n",
"files = os.listdir(images_dir)\n",
"images = [Image.open(images_dir + file_name).convert('RGB') for file_name in files]"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "7cbf449b",
"metadata": {},
"outputs": [],
"source": [
"required_width = max([im.size[0] for im in images])"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "283837f8",
"metadata": {},
"outputs": [],
"source": [
"new_images = []\n",
"for im in images:\n",
" width, height = im.size\n",
" ratio = required_width/width\n",
" new_width = int(ratio*width)\n",
" new_height = int(ratio*height)\n",
" new_images.append(im.resize((new_width, new_height)))"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "5b445308",
"metadata": {},
"outputs": [],
"source": [
"full_width = new_images[0].size[0]\n",
"full_height = sum([im.size[1] for im in new_images])\n",
"positions = np.cumsum([0, *[im.size[1] for im in new_images]])[:-1]"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "6817f585",
"metadata": {},
"outputs": [],
"source": [
"combined_image = Image.new('RGB', (full_width, full_height))\n",
"for pos,im in zip(positions, new_images):\n",
" combined_image.paste(im, (0,pos))"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "bde6e584",
"metadata": {},
"outputs": [],
"source": [
"im_format = 'JPEG'\n",
"combined_image.save(images_dir + r'result.' + im_format, format=im_format, quality=100)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "faeb3239",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.10.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment