Question: Can you give me another example that does the same thing as this code? It's a compression algorithm that takes an image and compresses it

Can you give me another example that does the same thing as this code? It's a compression algorithm that takes an image and compresses it by taking every 5th row and/or collumn and takes the average of the surrounding RGB elements.
from typing import List
def get_grid(x, y, row, col):
return [
[r, c]
for r, c in [
[x -1, y -1],[x -1, y],[x -1, y +1],
[x, y -1],[x, y],[x, y +1],
[x +1, y -1],[x +1, y],[x +1, y +1]
]
if 0<= r < row and 0<= c < col
]
def get_average(locations, image):
r = sum(image[i][j][0] for i, j in locations)/ len(locations)
g = sum(image[i][j][1] for i, j in locations)/ len(locations)
b = sum(image[i][j][2] for i, j in locations)/ len(locations)
return [int(r), int(g), int(b)]
def compress(image):
col = len(image)
row = len(image[0])
new_image =[]
for x in range(0, row, 5):
new_row =[]
for y in range(0, col, 5):
adjacent_locations = get_grid(x, y, row, col)
new_color = get_average(adjacent_locations, image)
new_row.append(new_color)
new_image.append(new_row)
return new_image
# Test case
test_image =[[[255,255,255] if (r %2== c %2) else [0,0,0] for c in range(25)] for r in range(25)]
print(f"Original image size: {len(test_image)}x{len(test_image[0])}")
compressed_image = compress(test_image)
print(f"Compressed image size: {len(compressed_image)}x{len(compressed_image[0])}
")
print(f"This is the test image:
{test_image}
")
print(f"This is the compressed image:
{compressed_image}")

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!