The following lists are the rows of an image file which includes the RGB value in the first 3 numbers and the last 2 numbers are the x and y coordinate of the pixel. the whole idea behind this is to reduce the number of items that I need to iterate through a file, by converting identical consecutive pixels into a range, it would drastically reduce the size (up to 50%), especially if the image has a solid color border.
I want to create an algorithm that does the following:
#converts these rows:
#[(63, 72, 204, 1, 3), (63, 72, 204, 2, 3), (63, 72, 204, 3, 3), (234, 57, 223, 4, 3)]
#[(255, 242, 0, 1, 2), (255, 242, 44, 2, 2), (255, 242, 44, 3, 2), (255, 242, 44, 4, 2)]
#[(255, 174, 200, 1, 1), (136, 0, 27, 2, 1), (136, 0, 27, 3, 1), (111, 125, 33, 4, 1)]
#into something like this:
#[(63, 72, 204, 1,3, 3,3), (234, 57, 223, 4, 3)]
#[(255, 242, 0, 1,2, 3,2), (255, 242, 44, 4, 2)]
#[(255, 174, 200, 1, 1), (136, 0, 27, 2,1, 3,1), (111, 125, 33, 4, 1)]
#This is what I have so far:
from PIL import Image
import numpy as np
def pic(name=str):
with Image.open('file_name.png') as png: #opens the image file
width, height = png.size #gets the dimensions
for y in range(height): #iterates through each pixel grabbing RGB and xy position
row = []
for x in range(width):
r,g,b = png.getpixel((x, y))
to_append = (r,g,b,x+1,abs(y-height)) #to flip the y values (unrelated reason)
row.append(tuple((to_append)))
print(row)
I want to create an algorithm
Use the groupby()
function from itertools. Example code:
import itertools
L = [("a", 1), ("a", 2), ("b", 3), ("b", 4)]
# Key function
key_func = lambda x: x[0]
for key, group in itertools.groupby(L, key_func):
print(key + " :", list(group))
a : [('a', 1), ('a', 2)]
b : [('b', 3), ('b', 4)]
I want to create an algorithm
Set a counter to 0 and loop over each pixel.
When you encounter a new pixel I would add the current pixel with the counter to a list. Reset the counter to 0.
When you are done you would have all the pixels plus the amount of each.
The only only thing you need to save is the width of the image.
When you reconstruct the image all you gotta do is loop over the list and add the appropriate amount of pixels using the count. The width of the image ie how many pixels that need to be on each row is of course the width variable that was also saved.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.