简体   繁体   中英

I'm recoloring an image and I don't want to recolor the transparent background

def recoltest():
    filenamusda = filedialog.askdirectory()
    print(filenamusda)
    global entry
    string = entry.get()
    label1.configure(text=string)
    path = filenamusda + "/*png"
    for file in glob.glob(path):
        img = Image.open(file).convert("L")
        img = ImageOps.grayscale(img)
        img = ImageOps.colorize(img, black=string, white="white")
        img = img.convert("RGBA")
        text = ScrolledText(root, width=50, height=30,padx=10,pady=8)
        text.pack()

        for i in range(30):
            cb = tk.Checkbutton(text=file, bg='white', anchor='w')
            text.window_create('end', window=cb)
            text.insert('end', '\n')
        datas = img.getdata()

        newData = []
        for item in datas:
            if item[0] == 154 and item[1] == 154 and item[2] == 154:
                newData.append((255, 255, 255, 0))
                if item[0] == 175 and item[1] == 95 and item[2] == 175:
                    newData.append((255, 255, 255, 0))

How do I make it so it only recolors the actual image but not the transparent background?

you can getpixel to r, g, b, a, then restore a back when putpixel .

Example code

r, g, b, a = img.getpixel((x, y))
if (r, g, b) in [(154, 154, 154), (175, 95, 175)]:
    new_img.putpixel((x, y), (255, 255, 255, a))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM