Skip to content

Instantly share code, notes, and snippets.

@myazdani
Created December 3, 2014 23:10
Show Gist options
  • Save myazdani/8870a40099ac864a308f to your computer and use it in GitHub Desktop.
Save myazdani/8870a40099ac864a308f to your computer and use it in GitHub Desktop.
resize images given path
{
"metadata": {
"name": "resize_images"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": "import cv2\nimport os\nfrom pylab import *\n%matplotlib inline",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": "Setup read/write file types, paths, interpolation algorithms, etc"
},
{
"cell_type": "code",
"collapsed": false,
"input": "src_path, src_image_type = \"/Users/myazdaniUCSD/Desktop/testing/\", \".jpg\"\nout_path, out_image_type = \"/Users/myazdaniUCSD/Desktop/write_path/\", \".bmp\"\n\nsize = (512,512)\ninterpolation_alg = cv2.INTER_CUBIC \n# other interpolation algorithms:\n# INTER_NEAREST\n# INTER_LINEAR \n# INTER_AREA\n# INTER_CUBIC\n# INTER_LANCZOS4",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": "Get all image paths"
},
{
"cell_type": "code",
"collapsed": false,
"input": "image_paths = [] \nfor root, dirs, files in os.walk(src_path):\n image_paths.extend([(root, f) for f in files if f.endswith(src_image_type)])",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": "Resize image and save"
},
{
"cell_type": "code",
"collapsed": false,
"input": "for image_path in image_paths:\n img = cv2.imread(os.path.join(image_path[0],image_path[1]),cv2.IMREAD_GRAYSCALE)\n img_resized = cv2.resize(img, size, interpolation = interpolation_alg)\n direcotry = directory = os.path.join(out_path,image_path[0].split(src_path)[1])\n if not os.path.exists(directory): os.makedirs(directory)\n cv2.imwrite(os.path.join(directory, image_path[1].split(\".jpg\")[0]+ out_image_type), img_resized)",
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "code",
"collapsed": false,
"input": "",
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment