PIL处理图片融合问题:从opencv读图片,变成4通道的numpy.array类型,再变成PIL.Image.Image类型,最后是两个png格式图片融合

1.从opencv读图片为彩色图片backgound,
2.此时的backgound存储格式是BGR,而PIL图片格式是RGB,把backgound变成RGB格式cv2.cvtColor(backgound,cv2.COLOR_BGR2RGB);

3.把backgound变成png图片,增加一层透明度值为255,img为numpy.array类型 
img[:, :, :3] = backgound
img[:, :, 3] = np.full(gray.shape, 255)

4.通过Image.fromarray(np.uint8(img),"RGBA")  把numpy.array变成PIL.Image.Image对象
Image.fromarray(np.uint8(img),"RGBA")

5.通过PIL的Image.alpha_composite函数进行两个png格式图片融合
具体代码如下


import cv2
from PIL import Image
import numpy as np

def blend_two_images2(src,dst):
    """

    :param src: 源图片
    :param dst: 目标图片
    :return: 源图片和目标图片融合的结果,重叠的部分源图片在上,目标图片在下
    """
    if src.mode != 'RGBA':
        src = src.convert('RGBA')
    if dst.mode != 'RGBA':
        dst = dst.convert('RGBA')
    img = Image.alpha_composite(dst, src)
    return img


def generate_chart(gray, back):

    #产生纯色的背景图,位于图片的最底层
    b = 0
    g = 0
    r = 255
    a = 255
    background = np.zeros((gray.shape[0],gray.shape[1],4))
    # background[:, :, 0] = np.full(gray.shape, r)
    # background[:, :, 1] = np.full(gray.shape, g)
    # background[:, :, 2] = np.full(gray.shape, b)
    background[:, :, :3] = back
    background[:, :, 3] = np.full(gray.shape, a)

    #产生图块
    block_img = np.zeros((gray.shape[0],gray.shape[1],4))
    b = np.random.randint(0, 255)
    g = np.random.randint(0, 255)
    r = np.random.randint(0, 255)
    block_img[:, :, 0] = np.full(gray.shape, r)
    block_img[:, :, 1] = np.full(gray.shape, g)
    block_img[:, :, 2] = np.full(gray.shape, b)
    block_img[:,:,3] = gray

    background = Image.fromarray(np.uint8(background),"RGBA")
    block_img = Image.fromarray(np.uint8(block_img),"RGBA")
    # background.show()
    # block_img.show()
    # background = Image.open("back.png")
    img = blend_two_images2(block_img, background)
    img.show()
    # img.save("result.png")

def process():
    filename = "img1.jpg"
    backgound = cv2.imread("img2.jpg")
    backgound = cv2.cvtColor(backgound,cv2.COLOR_BGR2RGB)
    gray = cv2.imread(filename,0)
    generate_chart(gray, backgound)


if __name__ == "__main__":
    process()

你可能感兴趣的:(数据挖掘)