import my_extension as me def grayscale(x, y, neighbors): r, g, b = neighbors[(x, y)] val = int(0.3 * r + 0.6 * g + 0.1 * b) return (val, val, val) def blur(x, y, neighbors): totalr = 0 num = 0 for coord in neighbors: r, g, b = neighbors[coord] totalr += r num += 1 val = int(totalr / num) return (val, val, val) def threshold(x, y, neighbors): if neighbors[(x, y)][0] > 128: return (255, 255, 255) else: return (0, 0, 0) def edge_detect(x, y, n): if len(n) < 9: return (0, 0, 0) # Ignore edges else: # Sobel edge detection: https://en.wikipedia.org/wiki/Sobel_operator x_plus = n[(x - 1, y - 1)][0] + 2 * n[(x - 1, y)][0] + n[(x - 1, y + 1)][0] x_minus = n[(x + 1, y - 1)][0] + 2 * n[(x + 1, y)][0] + n[(x + 1, y + 1)][0] y_plus = n[(x - 1, y - 1)][0] + 2 * n[(x, y - 1)][0] + n[(x + 1, y - 1)][0] y_minus = n[(x - 1, y + 1)][0] + 2 * n[(x, y + 1)][0] + n[(x + 1, y + 1)][0] G = int(((x_plus - x_minus) ** 2 + (y_plus - y_minus) ** 2) ** 0.5 / 8.0) return (G, G, G) #I = load_image("apple.png") # Creates and returns an me.Image object. # Could also be done as I = me.Image("apple.jpg") # but the above method forces you to create (in C++) a Python object -- # this'll be useful in the next lab. # Make sure your apply method creates an (internal) copy of the image before applying your operation -- # some of them (blur and edge-detect in particular) won't work if you're updating the image "in-place" print("I =", I) # (Image Object 211x239) print("I['width'] =", I["width"]) # 211 print("I['height'] =", I["height"]) # 239 print("I['foo'] =", I["foo"]) # None print("applying grayscale...", end=""); I.apply(grayscale, 0); I.save("apple_gray.png"); print("done!") print("blurring...", end=""); I.apply(blur, 3); I.save("apple_blur.png"); print("done!") print("thresholding...", end=""); I.apply(threshold, 0); I.save("apple_thresh.png"); print("done!") print("edge-detection...", end=""); I.apply(edge_detect, 1); I.save("apple_edges.png"); print("done!")