Python 处理RGB和RGBA图像,有透明图像部分的粘贴,paste->mask参数

from PIL import Image
import numpy as np

def trans(img):
# *********** Begin **********#
# 编写函数依次处理每个像素点
# 要求:若r、g、b、的均值大于230 则表示该像素的颜色接近白色,属于背景中的像素点,将其背景色设置为透明。否则将该像素的颜色替换为黑色。
    img = img.convert('RGBA')

    x, y = img.size

    for i in range(x):
        for j in range(y):
            color = img.getpixel((i, j))
            Mean = np.mean(list(color[:-1]))
            if Mean > 230:
                color = color[:-1] + (0, )
            else:
                color = (0, 0, 0, 255)
            img.putpixel((i, j), color)

    return img
# *********** End **********#

def img_replace(path):
    # *********** Begin **********#
    img = Image.open(path)
    # 根据如下像素点从图像img中提取所需物体并调用函数处理每个像素点。

    # 0, 0, 823, 633
    # 1134, 0, 1555, 331
    # 1543, 211, 1650, 428

    # 裁剪图片 img.crop
    background = img.crop((0, 0, 823, 633))
    img1 = img.crop((1134, 0, 1555, 331))
    img2 = img.crop((1543, 211, 1650, 428))

    img1 = trans(img1)
    img2 = trans(img2)
    # 根据如下像素点将原图中的物体替换成所需物体
    # 400,0
    # 4,95
    background.paste(img1, (400, 0), mask=img1.split()[3])
    background.paste(img2, (4, 95), mask=img2.split()[3])
    # 将结果保存至 './Image_body_cold/结果/d.jpg'
    background.save("./images/d.jpg")
    # *********** End **********#
    return True

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值