簡體   English   中英

使用 Python 將 RGB 值轉換為彩虹的基本 Colors

[英]Turning RGB Values Into The Basic Colors Of The Rainbow Using Python

我又來了,我猜。 這是我到目前為止得到的:

from PIL import Image
from tkinter import filedialog as fd
from webcolors import rgb_to_name
from pyautogui import press, typewrite, hotkey
import time

filename = fd.askopenfilename()
im = Image.open(filename, 'r')
pix_val = list(im.getdata())

def GetColor(R, G, B):
    Final = ""
    named_color = rgb_to_name((R, G, B), spec='css3') # Here
    return Final

for i in pix_val:
    press('q')
    press('t')
    typewrite('.give ' + GetColor(i[0], i[1], [2]))
    press('enter')
    time.sleep(3)

現在的目標是讓腳本自動將 RGB 值轉換為簡單的 colors,如黑色、紅色、白色、橙色、藍色、紫色、綠色……你知道的。 沒有像耐火磚那樣強烈的 colors。 我敢肯定有一種方法可以做到這一點,只需制作一個簡單的 map 並且如果 colors 在該顏色附近匹配,那么它會說它是該顏色。 例子:

XYZ = {["Red", 255, 0, 0], ["Blue", 0, 0, 255], ["Green", 0, 255, 0]...}

但是,我想要一個已經編碼的簡單小導入:/非常感謝任何幫助。

這樣做的問題是,一般來說,沒有好的捷徑。 您必須確定調色板中每個像素到每種顏色的距離,並保持這些距離中的最小距離。

這是映射到 HTML4 標准集中的 16 colors 的一個:

import math
from PIL import Image

colors = [
    ("black", (0, 0, 0)),
    ("silver", (192, 192, 192)),
    ("gray", (128, 128, 128)),
    ("white", (255, 255, 255)),
    ("maroon", (128, 0, 0)),
    ("red", (255, 0, 0)),
    ("purple", (128, 0, 128)),
    ("fuchsia", (255, 0, 255)),
    ("green", (0, 128, 0)),
    ("lime", (0, 255, 0)),
    ("olive", (128, 128, 0)),
    ("yellow", (255, 255, 0)),
    ("navy", (0, 0, 128)),
    ("blue", (0, 0, 255)),
    ("teal", (0, 128, 128)),
    ("aqua", (0, 255, 255))
]

def distance(a,b):
    dx = a[0]-b[0]
    dy = a[1]-b[1]
    dz = a[2]-b[2]
    return math.sqrt(dx*dx+dy*dy+dz*dz)

def findclosest(pixel):
    mn = 999999
    for name,rgb in colors:
        d = distance(pixel, rgb)
        if d < mn:
            mn = d
            color = name
    return color

im = Image.open("pacmanmaze.png", 'r')
pix_val = im.getdata()

for i in pix_val:
    print(findclosest(i))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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