【问题标题】:How can I replace identical consecutive RGB values with a range?如何用范围替换相同的连续 RGB 值?
【发布时间】:2021-05-06 18:36:07
【问题描述】:

以下列表是图像文件的行,其中前 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)

【问题讨论】:

    标签: python algorithm image numpy


    【解决方案1】:

    我想创建一个算法

    • 对于每一行/每一行
      • 按像素的 rgb 值对线条进行分组
      • 使用每组的第一项创建一个新行

    itertools.groupby

    【讨论】:

      【解决方案2】:

      使用来自 itertools 的 groupby() 函数。示例代码:

      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)]
      

      【讨论】:

      • 它是否适用于问题中的示例数据?
      • 相同的概念,不同的数据。通过示例学习比复制粘贴更好。
      【解决方案3】:

      我想创建一个算法

      将计数器设置为 0 并循环遍历每个像素。

      当您遇到新像素时,我会将当前像素与计数器一起添加到列表中。将计数器重置为 0。

      完成后,您将拥有所有像素加上每个像素的数量。

      您唯一需要保存的是图像的宽度。

      当您重建图像时,您所要做的就是遍历列表并添加 使用计数的适当数量的像素。图像的宽度,即 每行需要多少像素当然是宽度变量 也被保存了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-01
        • 1970-01-01
        • 2021-10-25
        • 2019-11-06
        • 2019-09-06
        • 2021-11-21
        • 1970-01-01
        相关资源
        最近更新 更多