1+ """ Here is the challenge problem for 2d loops>
2+ Images are often represented as 3d arrays,
3+ where the rows and columns are the pixels in the image,
4+ and each pixel has an r, g, and b value.
5+
6+ The interesting thing is that we can iterate over images.
7+ The challenge is, given an image, create a program that
8+ will return a different image where each pixel is the average
9+ of the pixels surrounding it in the original image.
10+
11+ The neighbors of an image are all the pixels that surroun it,
12+ 1 on each side, and 4 on the diagonals, for 8 in total.
13+ Each pixel doesn't necessarily have 8 neighbors, though (think about why)
14+
15+ The code to grab an image from the internet and make it
16+ into an array is given to you. The code also displays the new image
17+ you create in the end.
18+
19+ NOTE: The image is 3 dimensional because each pixel has rgb values.
20+ To find the average value of all of a pixels neighbors, you must
21+ change the average of the red value to the red value, blue to blue, etc.
22+ For example, if the neighbors of a pixel with value [1,2,3]
23+ were [20,30,40] and [10,120,30], the new pixel that would replace the original one would be
24+ [15,75,35]
25+ """
26+
27+ from PIL import Image
28+ import requests
29+ import numpy
30+ import matplotlib .pyplot as plt
31+
32+ url = "https://images.dog.ceo/breeds/waterdog-spanish/20180723_185544.jpg"
33+ img = numpy .array (Image .open (requests .get (url , stream = True ).raw ))
34+ newimg = img
35+ transpose = numpy .transpose (img )
36+
37+
38+ #write code to create newimg here
39+ def solution1 ():
40+ """Iterating over the image here. i is a variable from 0 to the width of the image.
41+ j is a variable that ranges from 0 to the height of the image. i is associated with
42+ values"""
43+ for i in range (len (img )):
44+ for j in range (len (img [0 ])):
45+ x_n = [0 ]
46+ y_n = [0 ]
47+
48+ if (i == 0 ):
49+ x_n .append (1 )
50+ elif (i == len (img )- 1 ):
51+ x_n .append (- 1 )
52+ else :
53+ x_n .append (1 )
54+ x_n .append (- 1 )
55+
56+ if (j == 0 ):
57+ y_n .append (1 )
58+ elif (j == len (img [0 ])- 1 ):
59+ y_n .append (- 1 )
60+ else :
61+ y_n .append (1 )
62+ y_n .append (- 1 )
63+
64+ r_avg = - 1 * img [i ][j ][0 ]
65+ g_avg = - 1 * img [i ][j ][1 ]
66+ b_avg = - 1 * img [i ][j ][2 ]
67+ c = - 1
68+
69+ for x in x_n :
70+ for y in y_n :
71+ r_avg += img [i + x ][j + y ][0 ]
72+ g_avg += img [i + x ][j + y ][1 ]
73+ b_avg += img [i + x ][j + y ][2 ]
74+ c += 1
75+ r_avg = r_avg / c
76+ g_avg = g_avg / c
77+ b_avg = b_avg / c
78+
79+ newimg [i ][j ] = [r_avg , g_avg , b_avg ]
80+
81+
82+
83+
84+ solution1 ()
85+
86+ plt .imshow (newimg )
87+ plt .show ()
88+
89+ plt .imshow (transpose )
90+ plt .show ()
0 commit comments