def overlay(img1, img2, opacity=1.0, pos=(0,0)):
    """
    Returns an image that is the result of overlaying img2
    on top of img1. Works for both RGB and RGBA images.

    img1 is the background image. img2 is the image to
    put on top of img1. img1 will be modified.

    Note that for opencv images, x is the column, y is the row.
    """
    # Determine the pixels that will be affected
    x_offset, y_offset = pos
    assert 0 <= x_offset < img1.shape[1],\
        "Invalid x offset (%d). Acceptable range [0,%d)" % (x_offset, img1.shape[1])
    assert 0 <= y_offset < img1.shape[0],\
        "Invalid x offset (%d). Acceptable range [0,%d)" % (y_offset, img1.shape[0])
    # img1 region
    xs1, xf1 = x_offset, min(x_offset + img2.shape[1], img1.shape[1])
    ys1, yf1 = y_offset, min(y_offset + img2.shape[0], img1.shape[0])

    xs2, xf2 = 0, min(img2.shape[1], img1.shape[1] - x_offset)
    ys2, yf2 = 0, min(img2.shape[0], img1.shape[0] - y_offset)

    if img2.shape[2] == 4:
        # Get the alpha channel of img2
        alpha = opacity * (img2[ys2:yf2, xs2:xf2, 3] / 255.0)
    else:
        alpha = opacity

    for c in range(3):
        img1[ys1:yf1, xs1:xf1, c] =\
            (alpha * img2[ys2:yf2, xs2:xf2, c]\
             + (1.0-alpha) * img1[ys1:yf1, xs1:xf1, c])
    return img1