-
Notifications
You must be signed in to change notification settings - Fork 15
/
filter_3by3.py
66 lines (54 loc) · 1.89 KB
/
filter_3by3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from PIL import Image
import numpy as np
import sys
# filter = [0, 0, 0, 0, 1, 0, 0, 0, 0]
# filter = [0, 1, 0, 1, -4, 1, 0, 1, 0]
# filter = [0, 1, 0, 0, -2, 0, 0, 1, 0]
# filter = [0, 0, 0, 1, -2, 1, 0, 0, 0]
filter = [0, 1, 0, 1, -4, 1, 0, 1, 0]
# filter = [1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0, 1.0/9.0]
def image_process(src):
width, height = src.size
dst = Image.new('RGB', (width, height))
img_pixels = np.array([[src.getpixel((x,y)) for y in range(height)] for x in range(width)])
color = np.zeros((len(filter), 3))
for y in range(1, height-1):
for x in range(1, width-1):
color[0] = img_pixels[x-1][y-1]
color[1] = img_pixels[x-1][y]
color[2] = img_pixels[x-1][y+1]
color[3] = img_pixels[x][y-1]
color[4] = img_pixels[x][y]
color[5] = img_pixels[x][y+1]
color[6] = img_pixels[x+1][y-1]
color[7] = img_pixels[x+1][y]
color[8] = img_pixels[x+1][y+1]
sum_color = np.zeros(3)
for num in range(len(filter)):
sum_color += color[num] * filter[num]
r,g,b = map(int, (sum_color))
r = min([r, 255])
r = max([r, 0])
g = min([g, 255])
g = max([g, 0])
b = min([b, 255])
b = max([b, 0])
dst.putpixel((x,y), (r,g,b))
return dst
if __name__ == '__main__':
param = sys.argv
if (len(param) != 2):
print("Usage: $ python " + param[0] + " sample.jpg")
quit()
# open image file
try:
input_img = Image.open(param[1])
except:
print('faild to load %s' % param[1])
quit()
if input_img is None:
print('faild to load %s' % param[1])
quit()
output_img = image_process(input_img)
output_img.save("filtered_" + param[1])
output_img.show()