Skip to content

Instantly share code, notes, and snippets.

@tyage
Created June 30, 2015 08:01
Show Gist options
  • Save tyage/3cc5e44955580f2aa629 to your computer and use it in GitHub Desktop.
Save tyage/3cc5e44955580f2aa629 to your computer and use it in GitHub Desktop.
import math
f = open('./mandrill.pgm', 'r')
# format
f.readline()
# size
width, height = f.readline().rstrip().split(' ')
# max
max_value = int(f.readline().rstrip())
table = [[]]
for data in f:
for dot in data.rstrip().split(' '):
if len(table[-1]) >= int(width):
table.append([])
table[-1].append(int(dot))
sobel_x = [
[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]
]
sobel_y = [
[1, 2, 1],
[0, 0, 0],
[-1, -2, -1]
]
sobel_table = []
sobel_file = open('./out.pgm', 'w')
sobel_file.write('P2\n254 254\n255\n')
for y in range(1, int(height) - 1):
sobel_table.append([])
for x in range(1, int(width) - 1):
diff_x = sum([sobel_x[dy][dx] * table[y - 1 + dy][x - 1 + dx] for dx in range(3) for dy in range(3)])
diff_y = sum([sobel_y[dy][dx] * table[y - 1 + dy][x - 1 + dx] for dx in range(3) for dy in range(3)])
diff = int(math.sqrt(diff_x ** 2 + diff_y ** 2))
if diff > max_value:
diff = max_value
if diff < 0:
diff = 0
sobel_table[-1].append(diff)
sobel_file.write(' '.join([str(i) for i in sobel_table[-1]]) + '\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment