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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| import math from PIL import Image import matplotlib.pyplot as plt
img = Image.open("CNN.png") img = img.convert("1")
raw = img.load()
pngV = [[raw[w, h] for w in range(img.size[1])] for h in range(img.size[0])]
kernel = [ [0, 0, 0], [0, 1, 0], [1, 0, 1], ]
kernel1 = [ [1] ]
def conv(v, w, step=1, pad=0, fill_value=1, bias=0): v_row = len(v) v_col = len(v[0]) if pad: for _ in range(pad): v.insert(0, [fill_value for _ in range(v_col + pad * 2)]) for i in range(pad, v_row + pad): for _ in range(pad): v[i].insert(0, fill_value) v[i].append(fill_value) for _ in range(pad): v.append([fill_value for _ in range(v_col + pad * 2)]) v_row += pad * 2 v_col += pad * 2
w_row = len(w) w_col = len(w[0]) res = [] for x in range(w_row // 2, v_row - w_row // 2, step): line = [] for y in range(w_col // 2, v_col - w_col // 2, step): temp = 0 for i in range(w_row): for j in range(w_col): t = v[x + i - w_row // 2][y + j - w_col // 2] * w[i][j] temp += t temp += bias line.append(temp) res.append(line) return res
def relu(v): for i in range(len(v)): for j in range(len(v[i])): v[i][j]=v[i][j] if v[i][j] > 0 else 0 return v
def max_pooling(v,size=2): v_row = math.ceil(len(v) / size) v_col = math.ceil(len(v[0]) / size) r = [] for y in range(v_row): line = [] for x in range(v_col): compare = [] for j in range(y*size, y*size + size if y*size + size < len(v) else len(v)): for i in range(x*size, x*size + size if x*size+size < len(v) else len(v[0])): compare.append(v[j][i]) line.append(max(compare)) r.append(line) return r
if __name__ == '__main__': v = conv(pngV, kernel, step=9, pad=0, bias=-763) v = relu(v) v = max_pooling(v) plt.imshow(v) plt.show() plt.imsave("2.png", v)
|