我正在编写几个函数,第一个将灰度位图图像插入另一个彩色位图图像。现在我的目标基本上是获取灰度像素图像的每个数字(例如 123)并替换每个 RGB 像素的结束数字(244、244、244),所以它基本上会像这样结束(241、242、243) ).本质上,这是用灰度图像为彩色图像加水印。
以下代码是我目前所拥有的,我能够返回列表中的元组值,我只是不知道如何在较大图像中操作较小灰度图像大小的空间。
def add_watermark():
image = Image.open()
pixels = list(image.getdata())
image.putdata()
image.save()
for i in range(img.size[0]):
for j in range(img.size[1]):
pixels[i,j] = (i, j, 100)
有人可以提供一些建议吗?
最佳答案
您走在正确的轨道上。这就是你操作像素的方式,尽管你可以使用 pixel access objects 来更快地完成它。就像我在下面展示的那样。
除了提取和设置正确的数字外,一切都非常简单。在此示例中,我通过除以 10 的幂并使用模运算符来完成此操作,但还有其他方法。希望评论能很好地解释它。
from PIL import Image
def add_watermark(watermark_path, image_in_path, image_out_path):
# Load watermark and image and check sizes and modes
watermark = Image.open(watermark_path)
assert watermark.mode == 'L'
image = Image.open(image_in_path)
assert image.mode == 'RGB'
assert watermark.size == image.size
# Get pixel access objects
watermark_pixels = watermark.load()
image_pixels = image.load()
# Watermark each pixel
for x in range(image.size[0]):
for y in xrange(image.size[1]):
# Get the tuple of rgb values and convert to a list (mutable)
rgb = list(image_pixels[x, y])
for i, p in enumerate(rgb):
# Divide the watermark pixel by 100 (r), then 10 (g), then 1 (b)
# Then take it modulo 10 to get the last digit
watermark_digit = (watermark_pixels[x, y] / (10 ** (2 - i))) % 10
# Divide and multiply value by 10 to zero the last digit
# Then add the watermark digit
rgb[i] = (p / 10) * 10 + watermark_digit
# Convert back to a tuple and store in the image
image_pixels[x, y] = tuple(rgb)
# Save the image
image.save(image_out_path)
关于python - 使用PIL通过在RGB元组中插入灰度值将灰度图像插入RGB图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16474289/