Last active
March 31, 2019 22:47
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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