Python OpenCV中如何在大图像上叠加小图像?

86
嗨,我正在创建一个程序,用于将图像中的一张脸替换为其他人的脸。但是,我卡在了尝试将新脸插入原始、更大的图像上。我已经研究了 ROI 和 addWeight(需要图像大小相同),但我没有找到用 Python 实现这个功能的方法。任何建议都是很好的,我是 OpenCV 新手。
我正在使用以下测试图像:
小图片: enter image description here 大图片: enter image description here 以下是迄今为止的代码...其他示例的混合:
import cv2
import cv2.cv as cv
import sys
import numpy

def detect(img, cascade):
    rects = cascade.detectMultiScale(img, scaleFactor=1.1, minNeighbors=3, minSize=(10, 10), flags = cv.CV_HAAR_SCALE_IMAGE)
    if len(rects) == 0:
        return []
    rects[:,2:] += rects[:,:2]
    return rects

def draw_rects(img, rects, color):
    for x1, y1, x2, y2 in rects:
        cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)

if __name__ == '__main__':
    if len(sys.argv) != 2:                                         ## Check for error in usage syntax

    print "Usage : python faces.py <image_file>"

else:
    img = cv2.imread(sys.argv[1],cv2.CV_LOAD_IMAGE_COLOR)  ## Read image file

    if (img == None):                                     
        print "Could not open or find the image"
    else:
        cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
        gray = cv2.cvtColor(img, cv.CV_BGR2GRAY)
        gray = cv2.equalizeHist(gray)

        rects = detect(gray, cascade)

        ## Extract face coordinates         
        x1 = rects[0][3]
        y1 = rects[0][0]
        x2 = rects[0][4]
        y2 = rects[0][5]
        y=y2-y1
        x=x2-x1
        ## Extract face ROI
        faceROI = gray[x1:x2, y1:y2]

        ## Show face ROI
        cv2.imshow('Display face ROI', faceROI)
        small = cv2.imread("average_face.png",cv2.CV_LOAD_IMAGE_COLOR)  
        print "here"
        small=cv2.resize(small, (x, y))
        cv2.namedWindow('Display image')          ## create window for display
        cv2.imshow('Display image', small)          ## Show image in the window

        print "size of image: ", img.shape        ## print size of image
        cv2.waitKey(1000)              
9个回答

176

实现你想要的简单方法:

import cv2
s_img = cv2.imread("smaller_image.png")
l_img = cv2.imread("larger_image.jpg")
x_offset=y_offset=50
l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img

结果图像

更新

我想您也希望处理该alpha通道。这是一种快速而简单的实现方法:

s_img = cv2.imread("smaller_image.png", -1)

y1, y2 = y_offset, y_offset + s_img.shape[0]
x1, x2 = x_offset, x_offset + s_img.shape[1]

alpha_s = s_img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s

for c in range(0, 3):
    l_img[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
                              alpha_l * l_img[y1:y2, x1:x2, c])

带alpha通道的结果图片


11
我知道这是一个古老的问题,但你能否解释一下阿尔法通道示例中正在发生的事情?我开始学习cv2和Python,这些东西对我来说仍然是个巨大的问号。 - Jonathan Crowe
3
赞同Jonathan的请求。我想知道这个数学计算在做什么,以便更好地调试问题。 - Adib
1
@JonathanCrowe 将image1叠加在image2上,[result-image::rgb通道] = [image1::rgb通道] * [image1::alpha通道] + [image2::rgb通道] * (1.0-[image1::alpha通道])。 - fireant
1
@Adib,请查看上面的评论。 - fireant
2
嘿,在更新中你的代码被截断了: l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1], c] = 你那里的意思是什么? - GuySoft
没有被切断,剩下的在下一行。完美运作。 :) @GuySoft - Olezt

27

借鉴@fireant的想法,我编写了一个处理覆盖层的函数。这对于任何位置参数(包括负位置)都有效。

def overlay_image_alpha(img, img_overlay, x, y, alpha_mask):
    """Overlay `img_overlay` onto `img` at (x, y) and blend using `alpha_mask`.

    `alpha_mask` must have same HxW as `img_overlay` and values in range [0, 1].
    """
    # Image ranges
    y1, y2 = max(0, y), min(img.shape[0], y + img_overlay.shape[0])
    x1, x2 = max(0, x), min(img.shape[1], x + img_overlay.shape[1])

    # Overlay ranges
    y1o, y2o = max(0, -y), min(img_overlay.shape[0], img.shape[0] - y)
    x1o, x2o = max(0, -x), min(img_overlay.shape[1], img.shape[1] - x)

    # Exit if nothing to do
    if y1 >= y2 or x1 >= x2 or y1o >= y2o or x1o >= x2o:
        return

    # Blend overlay within the determined ranges
    img_crop = img[y1:y2, x1:x2]
    img_overlay_crop = img_overlay[y1o:y2o, x1o:x2o]
    alpha = alpha_mask[y1o:y2o, x1o:x2o, np.newaxis]
    alpha_inv = 1.0 - alpha

    img_crop[:] = alpha * img_overlay_crop + alpha_inv * img_crop

使用示例:

import numpy as np
from PIL import Image

# Prepare inputs
x, y = 50, 0
img = np.array(Image.open("img_large.jpg"))
img_overlay_rgba = np.array(Image.open("img_small.png"))

# Perform blending
alpha_mask = img_overlay_rgba[:, :, 3] / 255.0
img_result = img[:, :, :3].copy()
img_overlay = img_overlay_rgba[:, :, :3]
overlay_image_alpha(img_result, img_overlay, x, y, alpha_mask)

# Save result
Image.fromarray(img_result).save("img_result.jpg")

结果:

img_result.jpg

如果您遇到错误或异常输出,请确保:

  • img不应包含alpha通道。(例如,如果是RGBA,请先转换为RGB。)
  • img_overlay具有与img相同的通道数。

9
使用此代码会出现“IndexError: index 3 is out of bounds for axis 2 with size 3”错误提示。 - Schütze
1
我该如何将大图像的质心与小图像的质心叠加?我已经有了两个图像的质心。我使用了上面的函数,但是小图像最左边的像素会自动叠加在大图像上。 - Alok Subedi
4
@Schütze 的源图像需要转换为 RGBA 格式,可以使用以下代码:img = cv2.cvtColor(img, cv2.COLOR_RGB2RGBA).copy() - lcapra
如果img不应该具有alpha通道,那么该函数也许可以从检查中受益?同样的情况也适用于它们必须具有相同数量的通道吗?假设有一种标准化的检查方式。 - Lifeweaver

11

基于Fireant上面出色的回答,这里是Alpha混合但更容易理解。根据您要合并的方向,您可能需要交换1.0-alphaalpha(我的与Fireant的答案相反)。

o* == s_img.* b* == b_img.*

for c in range(0,3):
    alpha = s_img[oy:oy+height, ox:ox+width, 3] / 255.0
    color = s_img[oy:oy+height, ox:ox+width, c] * (1.0-alpha)
    beta  = l_img[by:by+height, bx:bx+width, c] * (alpha)

    l_img[by:by+height, bx:bx+width, c] = color + beta

8

这是它:

def put4ChannelImageOn4ChannelImage(back, fore, x, y):
    rows, cols, channels = fore.shape    
    trans_indices = fore[...,3] != 0 # Where not transparent
    overlay_copy = back[y:y+rows, x:x+cols] 
    overlay_copy[trans_indices] = fore[trans_indices]
    back[y:y+rows, x:x+cols] = overlay_copy

#test
background = np.zeros((1000, 1000, 4), np.uint8)
background[:] = (127, 127, 127, 1)
overlay = cv2.imread('imagee.png', cv2.IMREAD_UNCHANGED)
put4ChannelImageOn4ChannelImage(background, overlay, 5, 5)

fore[...,3] 实际上是做什么的? - SIslam

5

这是一个简单的函数,它将图像front贴到另一张图像back上并返回结果。该函数适用于3通道和4通道图像,并处理了alpha通道。它也能正确地处理重叠区域。

输出图像与back图像大小相同,但始终具有4个通道。
输出的alpha通道由(u+v)/(1+uv)给出,其中u、v为前景图和背景图的alpha通道,-1 <= u,v <= 1。如果没有与前景图重叠的区域,则使用背景图中的alpha值。

import cv2

def merge_image(back, front, x,y):
    # convert to rgba
    if back.shape[2] == 3:
        back = cv2.cvtColor(back, cv2.COLOR_BGR2BGRA)
    if front.shape[2] == 3:
        front = cv2.cvtColor(front, cv2.COLOR_BGR2BGRA)

    # crop the overlay from both images
    bh,bw = back.shape[:2]
    fh,fw = front.shape[:2]
    x1, x2 = max(x, 0), min(x+fw, bw)
    y1, y2 = max(y, 0), min(y+fh, bh)
    front_cropped = front[y1-y:y2-y, x1-x:x2-x]
    back_cropped = back[y1:y2, x1:x2]

    alpha_front = front_cropped[:,:,3:4] / 255
    alpha_back = back_cropped[:,:,3:4] / 255
    
    # replace an area in result with overlay
    result = back.copy()
    print(f'af: {alpha_front.shape}\nab: {alpha_back.shape}\nfront_cropped: {front_cropped.shape}\nback_cropped: {back_cropped.shape}')
    result[y1:y2, x1:x2, :3] = alpha_front * front_cropped[:,:,:3] + (1-alpha_front) * back_cropped[:,:,:3]
    result[y1:y2, x1:x2, 3:4] = (alpha_front + alpha_back) / (1 + alpha_front*alpha_back) * 255

    return result

这是我能够执行的唯一事情,但由于某种原因,它混合得非常糟糕,前景图像颜色似乎与背景或其他东西混合在一起。 - ch4rl1e97
等一下,我在自己的代码中做了一些更改,我会看一下。 - Jonas De Schouwer
但这里的重点是混合,当alpha_front<255时,前景图像会有点透明。 - Jonas De Schouwer
这是我遇到的问题:点击此处 最终,我合并了大约12种不同的方法,并针对此问题使用了addWeighted()函数,并在编辑器中将我的背景图像修改为黑色,以便放置在顶部的图像。在我的情况下,前/顶部图像没有任何透明度(或者更确切地说,我不关心它是否有透明度),所以这对我起作用了。请看这里的结果 - ch4rl1e97
我编辑了这个答案以包含我的更改。重要的是,倒数第二行的 alpha_back * back_cropped [:,:,:3] 更改为 (1-alpha_front) * back_cropped [:,:,:3]。 因为背景 alpha 通道已经在结果图像的 alpha 通道中考虑到了。 - Jonas De Schouwer

3
尝试使用上述任何答案写入目标图像时,如果出现以下错误:
ValueError: assignment destination is read-only

一个快速的潜在解决方案是将WRITEABLE标志设置为true。
img.setflags(write=1)

3

要给s_img添加alpha通道,我只需在以下这行代码之前使用cv2.addWeighted:

s_img=cv2.addWeighted(l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]],0.5,s_img,0.5,0)

以上是实现的方法。


1

我重新设计了@fireant的概念,允许使用可选的alpha掩码,并允许任何x或y值,包括超出图像边界的值。它将裁剪到边界。

def overlay_image_alpha(img, img_overlay, x, y, alpha_mask=None):
    """Overlay `img_overlay` onto `img` at (x, y) and blend using optional `alpha_mask`.

    `alpha_mask` must have same HxW as `img_overlay` and values in range [0, 1].
    """

    if y < 0 or y + img_overlay.shape[0] > img.shape[0] or x < 0 or x + img_overlay.shape[1] > img.shape[1]:
        y_origin = 0 if y > 0 else -y
        y_end = img_overlay.shape[0] if y < 0 else min(img.shape[0] - y, img_overlay.shape[0])

        x_origin = 0 if x > 0 else -x
        x_end = img_overlay.shape[1] if x < 0 else min(img.shape[1] - x, img_overlay.shape[1])

        img_overlay_crop = img_overlay[y_origin:y_end, x_origin:x_end]
        alpha = alpha_mask[y_origin:y_end, x_origin:x_end] if alpha_mask is not None else None
    else:
        img_overlay_crop = img_overlay
        alpha = alpha_mask

    y1 = max(y, 0)
    y2 = min(img.shape[0], y1 + img_overlay_crop.shape[0])

    x1 = max(x, 0)
    x2 = min(img.shape[1], x1 + img_overlay_crop.shape[1])

    img_crop = img[y1:y2, x1:x2]
    img_crop[:] = alpha * img_overlay_crop + (1.0 - alpha) * img_crop if alpha is not None else img_overlay_crop

1
一个简单的4对4粘贴函数,可以正常工作-
def paste(background,foreground,pos=(0,0)):
    #get position and crop pasting area if needed
    x = pos[0]
    y = pos[1]
    bgWidth = background.shape[0]
    bgHeight = background.shape[1]
    frWidth = foreground.shape[0]
    frHeight = foreground.shape[1]
    width = bgWidth-x
    height = bgHeight-y
    if frWidth<width:
        width = frWidth
    if frHeight<height:
        height = frHeight
    # normalize alpha channels from 0-255 to 0-1
    alpha_background = background[x:x+width,y:y+height,3] / 255.0
    alpha_foreground = foreground[:width,:height,3] / 255.0
    # set adjusted colors
    for color in range(0, 3):
        fr = alpha_foreground * foreground[:width,:height,color]
        bg = alpha_background * background[x:x+width,y:y+height,color] * (1 - alpha_foreground)
        background[x:x+width,y:y+height,color] = fr+bg
    # set adjusted alpha and denormalize back to 0-255
    background[x:x+width,y:y+height,3] = (1 - (1 - alpha_foreground) * (1 - alpha_background)) * 255
    return background

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接