Skip to content

Instantly share code, notes, and snippets.

@aessam
Last active March 31, 2019 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aessam/31dedcf60749514d6db9a8b8c0232fda to your computer and use it in GitHub Desktop.
Save aessam/31dedcf60749514d6db9a8b8c0232fda to your computer and use it in GitHub Desktop.
I was trying to understand how convolutional network works with filters, I decided to replicate it.
from PIL import Image, ImageDraw
import random
from sys import argv
if len(argv) != 3:
print("<<script>> Image outputDir")
exit(1)
image_name = argv[1]
out = argv[2]
def random_vertical_filter():
base = 1000
start_range = 0.8
to = int(start_range * base)
a = (random.randint(0, to) + ((1 - start_range) * base)) / 1000
b = (random.randint(0, to) + ((1 - start_range) * base)) / 1000
c = (random.randint(0, to) + ((1 - start_range) * base)) / 1000
return [
[1-a, 0, -a],
[1-b, 0, -b],
[1-c, 0, -c]
]
def random_horizontal_filter():
base = 1000
start_range = 0.8
to = int(start_range * base)
a = (random.randint(0, to) + ((1 - start_range) * base)) / 1000
b = (random.randint(0, to) + ((1 - start_range) * base)) / 1000
c = (random.randint(0, to) + ((1 - start_range) * base)) / 1000
return [
[1-a, 1-b, 1-c],
[0,0,0],
[-a, -b, -c]
]
#filter = [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
#filter = [[.5, .5, .5], [0, 0, 0], [-.5, -.5, -.5]]
#filter = [[-1, -1, -1], [0, 0, 0], [1, 1, 1]]
#filter = [[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]
filter = [[ 0, -1, -1],
[ 1, 0, -1],
[ 1, 1, 0]]
#filter = random_horizontal_filter()
im = Image.open(image_name)
pix = im.load()
outim = Image.new('RGB', im.size)
outdraw = ImageDraw.Draw(outim)
outpix = outim.load()
for y in range(1, im.size[1]-1):
for x in range(1, im.size[0]-1):
all = 0
for iy in range(-1, 2, 1):
for ix in range(-1, 2, 1):
zx = int(sum(pix[x + ix, y + iy])/3)
zx *= filter[ix][iy]
all += int(zx)
outpix[x, y] = (all, all, all)
outim.save(out + "/" + str(filter) + ".png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment