将白色背景更改为特定颜色 [英] change white background to a specifc color

查看:60
本文介绍了将白色背景更改为特定颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试为黑白照片设置彩色背景,首先我将像素转换为白色或黑色,然后我想用特定颜色 (148,105,39) 替换白色,然后保存.

Hello I am trying to give a black and white photo a colored background, first I convert pixels to either white or black then I would like to replace the white with a specific color (148,105,39) then save it.

这是我正在处理的图像

here is the image I am working on

到目前为止,这是我的函数,它不会改变颜色(也不会出错)

here is my function so far it doesn't change the color (also doesn't give error)

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

推荐答案

你真的,真的很想避免使用 PIL 图像的 for 循环,尝试使用 Numpy,它会更容易编写和更快运行.

You really, really want to avoid for loops with PIL images, try to use Numpy and it will be easier to write and faster to run.

我会这样做:

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

你也可以像这样使用 PIL 的 ImageOps.colorize():

You could equally use PIL's ImageOps.colorize() like this:

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

这篇关于将白色背景更改为特定颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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