将白色背景更改为特定颜色

时间:2019-10-12 12:53:32

标签: python python-imaging-library

您好,我想为黑白照片提供彩色背景,首先将像素转换为白色或黑色,然后将白色替换为特定颜色(148,105,39),然后保存。

>

这是我正在logo1.jpg上工作的图像

到目前为止,这是我的功能,它不会改变颜色(也不会产生错误)

def binary_image(img):
    gray = img.convert('L')
    bw = gray.point(lambda x: 0 if x<128 else 255, '1')
    img = bw.convert('RGBA')
    pixdata = img.load()
    for y in range(img.size[1]):
        for x in range(img.size[0]):
            if pixdata[x, y] == (255, 255, 255, 255): #white color
                pixdata[x, y] = (148,105,39,255)
    return full_4
img=Image.open('logo.jpg')
bg_fps = binary_image(img)
bg_fps.show()

1 个答案:

答案 0 :(得分:0)

您确实非常想避免PIL图片出现for循环,尝试使用Numpy,这样会更容易编写和运行。

我会这样:

import numpy as np
from PIL import image

# Load image and ensure greyscale
im = Image.open('U6IhW.jpg').convert('L')

# Make Numpy version for fast, efficient access
npim = np.array(im)

# Make solid black RGB output image, same width and height but 3 channels (RGB)
res = np.zeros((npim.shape[0],npim.shape[1],3), dtype=np.uint8)

# Anywhere the grey image is >127, make result image new colour
res[npim>127] = [148,105,39]

# Convert back to PIL Image and save to disk
Image.fromarray(res).save('result.png')

enter image description here


您同样可以使用PIL的ImageOps.colorize()

from PIL import Image, ImageOps

im = Image.open('U6IhW.jpg').convert('L')                                                                                                           

# Threshold to pure black and white
bw = im.point(lambda x: 0 if x<128 else 255)                                                                                                        

# Colorize
result = ImageOps.colorize(bw, (0,0,0), (148,105,39))