[英]How can I replace identical consecutive RGB values with a range?
以下列表是图像文件的行,其中前 3 个数字中包含 RGB 值,后 2 个数字是像素的 x 和 y 坐标。 这背后的整个想法是减少我需要遍历文件的项目数量,通过将相同的连续像素转换为一个范围,它会大大减小大小(最多 50%),特别是如果图像有一个实体颜色边框。
我想创建一个执行以下操作的算法:
#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)
使用来自 itertools 的groupby()
function。 示例代码:
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)]
我想创建一个算法
将计数器设置为 0 并循环遍历每个像素。
当您遇到新像素时,我会将带有计数器的当前像素添加到列表中。 将计数器重置为 0。
完成后,您将拥有所有像素加上每个像素的数量。
您唯一需要保存的是图像的宽度。
当您重建图像时,您所要做的就是遍历列表并使用计数添加适当数量的像素。 图像的宽度,即每行需要多少像素,当然也是保存的宽度变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.