PIL过滤像素并粘贴 [英] PIL filter pixels and paste

查看:78
本文介绍了PIL过滤像素并粘贴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像粘贴到另一幅图像上.我实际上正在使用约瑟夫的第二个答案

I am trying to paste an image onto another one. I am actually using the second answer by Joseph here because I am trying to do something very similar: resize my foregroud to the background image, and then copy only the black pixels in the foreground onto the background. My foreground is a color image with black contours, and I want only the contours to be pasted on the background. The line

mask = pixel_filter(mask, (0, 0, 0), (0, 0, 0, 255), (0, 0, 0, 0))

返回错误图像索引超出范围".

returns the error "image index out of range".

当我不执行此过滤过程以查看是否至少可以粘贴时,我会收到错误的蒙版透明性错误".我将背景和前景都设置为RGB和RGBA,以查看是否有任何组合可以解决问题,但事实并非如此.

When I don't do this filtering process to see if pasting at least works, I get a "bad mask transparency error". I have set the background and foreground to RGB and RGBA both to see if any combination solves the problem, it doesn't.

mask()行中我在做什么错?粘贴过程中我缺少什么?感谢您的帮助.

What am I doing wrong in the mask() line, and what am I missing about the paste process? Thanks for any help.

推荐答案

您正在引用的pixel filter函数似乎有一个小错误.它正在尝试将一维列表索引向后转换为二维索引.它应该是(x,y) => (index/height, index%height)(请参阅此处).以下是函数(完整)被重写.

The pixel filter function you are referencing has a slight bug it seems. It's trying to convert a 1 dimensional list index into a 2d index backwards. It should be (x,y) => (index/height, index%height) (see here). Below is the function (full attribution to the original author) rewritten.

def pixel_filter(image, condition, true_colour, false_colour):
    filtered = Image.new("RGBA", image.size)
    pixels = list(image.getdata())
    for index, colour in enumerate(pixels):
        if colour == condition:
            filtered.putpixel((index/image.size[1],index%image.size[1]), true_colour)
        else:
            filtered.putpixel((index/image.size[1],index%image.size[1]), false_colour)
    return filtered

这篇关于PIL过滤像素并粘贴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆