【问题标题】:I'm recoloring an image and I don't want to recolor the transparent background我正在为图像重新着色,但不想重新着色透明背景
【发布时间】:2022-01-09 15:06:33
【问题描述】:
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))

如何使它只重新着色实际图像而不是透明背景?

【问题讨论】:

  • 您可以跳过alpha通道值为0的原始图像的像素。
  • 请确保您的问题minimalcompleterunabble。这意味着它应该包含必要的import 语句来运行它,您应该删除所有不相关的tk 内容并提供有代表性的输入图像和预期结果。谢谢你。这也意味着您将更有可能得到答案,而且可能会更快。

标签: python image tkinter python-imaging-library


【解决方案1】:

您可以将getpixel 转换为r、g、b、a,然后将a 恢复为putpixel

示例代码

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

【讨论】:

    猜你喜欢
    • 2017-12-13
    • 2021-07-02
    • 2021-04-08
    • 2015-07-02
    • 2021-10-31
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    相关资源
    最近更新 更多