In: Computer Science
Write a python function image compress() that takes one argument called filename, which is the name of a file that contains a N × N (N-pixel by N-pixel) “grayscale bitmap image”.
A “grayscale bitmap image” is an image of the following form where every pixel contains a grayscale color value between 0 − 255 (inclusive). Colour value 0 means that pixel should appear completely black and color value 255means completely white. Any other value in between stands for different shades of gray.
The bitmap representation of the above 5 × 5 image would be a text file as follows:
255 255 125 200 000 255 255 255 255 255 125 255 255 255 255 200 255 255 255 255 000 255 255 255 255
The function compresses the image by storing information about only those pixels which have color values other than 255 by storing only those pixels which are not white. It returns a list of tuples such that each tuple contains three elements: (the row of the pixel, the column of the pixel, the colour value)
For this example,for the above image,the returned list would be[(0, 2, 125), (0, 3, 200), (0, 4, 0), (2, 0, 125), (3, 0, 200), (4, 0, 0)].
Additional Examples:
Input file: image1.txt
255 255 125 200 000 255 125 255 255 255 125 255 000 255 255 200 255 255 000 255 000 255 255 255 000
Return value of image compress ("image1.txt"):[(0, 2, 125), (0,
3, 200), (0, 4, 0), (1, 1, 125), (2, 0, 125), (2, 2, 0), (3, 0,
200), (3, 3, 0), (4, 0, 0),
(4, 4, 0)]
Input file: image2.txt
255 255 255 000 255 255 255 000 255 255 255 000
Return value of image compress("image2.txt"): [(1, 0, 0), (2, 1, 0), (3, 2, 0)]
Input file: image3.txt
128 255 255 255 192 128 000 255 255 180 000 255 000 255 149 076 255 255 000 134
Return value of image compress("image3.txt"):[(0, 0, 128), (0,
4, 192), (1, 0, 128), (1, 1, 0), (1, 4, 180), (2, 0, 0), (2, 2, 0),
(2, 4, 149), (3, 0, 76),
(3, 3, 0), (3, 4, 134)]
filename=input("Enter filename: ")
data=[]
with open(filename,"r") as f:
data=f.read().split('\n')
result=[]
for i in range(0,len(data)):#loop through data got from file
ref=data[i].split(' ')#split the data using
space
for j in range(0,len(ref)):
if ref[j]!="255":#compare with 255
then make a note of it
t1=tuple((i,j,int(ref[j])))
result.append(t1)
print(result)
f.close()
Note:please follow indentation if everything correct give me rating