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

Time:12-05

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?

CodePudding user response:

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))
  • Related