user2884456
user2884456

Reputation: 49

Blurring an image in Python without PIL

I am attempting to define a function that will blur an image in python without the use of PIL. The color of each pixel needs to be averaged with the colors of the 8 surrounding pixels i.e.:

The value of o needs to be averaged with all the values of x.

x x x
x o x
x x x

I have:

def blur():
global photo
pixels = Image.getPixels(photo)
for row in range(photo.height()):
    for col in range(photo.width()):
        red = pixels[row][col][0]
        green = pixels[row][col][1]
        blue = pixels[row][col][2]
Image.setPixels(photo,pixels)

Where Image.getPixels() returns the red, green, and blue values between 0 and 255 in the same list ([0] returns red, [1] returns green, and [2] returns blue) and their x and y values represented by row and col. I have searched fairly extensively for a hint in the right direction but haven't found anything all that relevant. Any idea/help would be appreciated. Thanks!

Upvotes: 0

Views: 3131

Answers (2)

Natalia
Natalia

Reputation: 385

Ofc to count the average of 8 elements, you need to have the sum of those elements, so start with that. Let's think what indexes those elements would have. If the pixel in the middle is [x][y], than the pixel on it's right would have [x+1][y] and the pixel upon it would have [x][y+1]. Figure out all eight indexes you need and just sum this 8 values. At the end divide the result by 8. Also important thing is to use two different tables (just make a copy of an image to another table) - one you take values from to count the avg, and second in which you save new pixels, because otherwise, using only one table, for counting next pixel you would use the the average of pixel you have already changed.

Upvotes: 0

ford prefect
ford prefect

Reputation: 7388

I think this is homework so I am not gonna write out the code. You can probably use numpy vectorize and here is a pointer How to vectorize this python code? to sum three above and the three below then hard code adding in the two to the side and divide by 8. Then reassign red blue and green in a new three dimensional array which you can preallocate to be the size of the old image.

Upvotes: 1

Related Questions