簡體   English   中英

如何用范圍替換相同的連續 RGB 值?

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

我想創建一個算法

  • 對於每一行/行
    • 按像素的 rgb 值對線條進行分組
    • 使用每組的第一項創建一個新行

itertools.groupby

使用來自 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM