Skip to content

Instantly share code, notes, and snippets.

@greeness
Created January 23, 2014 01:48
Show Gist options
  • Save greeness/8571326 to your computer and use it in GitHub Desktop.
Save greeness/8571326 to your computer and use it in GitHub Desktop.
{
"metadata": {
"name": "2d Convolution"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": "%load_ext octavemagic",
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": "octave window = [1 0 1; 0 1 0 ;1 0 1]",
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "display_data",
"text": "window =\n\n 1 0 1\n 0 1 0\n 1 0 1\n"
}
],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": "octave image = [1 1 1 0 0 ; 0 1 1 1 0; 0 0 1 1 1; 0 0 1 1 0; 0 1 1 0 0]",
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "display_data",
"text": "image =\n\n 1 1 1 0 0\n 0 1 1 1 0\n 0 0 1 1 1\n 0 0 1 1 0\n 0 1 1 0 0\n"
}
],
"prompt_number": 4
},
{
"cell_type": "markdown",
"metadata": {},
"source": "Now we convolve the image with the 3x3 window using `conv2`:"
},
{
"cell_type": "code",
"collapsed": false,
"input": "octave conv2(image, window);",
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 8,
"text": "array([[ 1., 1., 2., 1., 1., 0., 0.],\n [ 0., 2., 2., 3., 1., 1., 0.],\n [ 1., 1., 4., 3., 4., 1., 1.],\n [ 0., 1., 2., 4., 3., 3., 0.],\n [ 0., 1., 2., 3., 4., 1., 1.],\n [ 0., 0., 2., 2., 1., 1., 0.],\n [ 0., 1., 1., 1., 1., 0., 0.]])"
}
],
"prompt_number": 8
},
{
"cell_type": "markdown",
"metadata": {},
"source": "Suppose the image dimension is n1xn1, and the windown dimension is n2xn2. The default shape is 'full' which results n1 + n2 - 1 dimension, but we want 'valid' which results n1 - n2 + 1 dimension."
},
{
"cell_type": "code",
"collapsed": false,
"input": "octave conv2(image, window, SHAPE='valid');",
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 9,
"text": "array([[ 4., 3., 4.],\n [ 2., 4., 3.],\n [ 2., 3., 4.]])"
}
],
"prompt_number": 9
},
{
"cell_type": "markdown",
"metadata": {},
"source": "![sf](http://deeplearning.stanford.edu/wiki/images/6/6c/Convolution_schematic.gif)"
},
{
"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