【问题标题】:OpenCV Python: How to overlay an image into the centre of another imageOpenCV Python:如何将图像叠加到另一个图像的中心
【发布时间】:2020-02-03 11:37:05
【问题描述】:

如何将较小的图片粘贴到另一张图片的中心?两张图片的高度相同,但较小的图片的宽度总是更小。

生成的图像应该是较小的图像,周围有黑条,所以它是方形的。

resizedImg = cv2.resize(img, (newW, 40))
blankImg = np.zeros((40, 40, 1), np.uint8)

resizedImg

blankImg

【问题讨论】:

    标签: python opencv


    【解决方案1】:
    import cv2
    import numpy as np
    back = cv2.imread('back.png')
    overlay = cv2.imread('overlay.png')
    h, w = back.shape[:2]
    print(h, w)
    h1, w1 = overlay.shape[:2]
    print(h1, w1)
    # let store center coordinate as cx,cy
    cx, cy = (h - h1) // 2, (w - w1) // 2
    # use numpy indexing to place the resized image in the center of 
    # background image
    
    back[cy:cy + h1, cx:cx + w1] = overlay
    
    # view result
    cv2.imshow('back with overlay', back)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    观看此video 以了解有关叠加层的更多信息

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    这是一种方法。您计算调整后图像左上角的 x 和 y 偏移量,当调整后的图像在背景图像中居中时。然后使用 numpy 索引将调整大小的图像放置在背景的中心。

    import cv2
    import numpy as np
    
    
    # load resized image as grayscale
    img = cv2.imread('resized.png', cv2.IMREAD_GRAYSCALE)
    h, w = img.shape
    print(h,w)
    
    # load background image as grayscale
    back = cv2.imread('background.png', cv2.IMREAD_GRAYSCALE)
    hh, ww = back.shape
    print(hh,ww)
    
    # compute xoff and yoff for placement of upper left corner of resized image   
    yoff = round((hh-h)/2)
    xoff = round((ww-w)/2)
    print(yoff,xoff)
    
    # use numpy indexing to place the resized image in the center of background image
    result = back.copy()
    result[yoff:yoff+h, xoff:xoff+w] = img
    
    # view result
    cv2.imshow('CENTERED', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    # save resulting centered image
    cv2.imwrite('resized_centered.png', result)
    


    【讨论】:

    • 但它总是保存为灰色图像,我想要 RGB 输出。
    • 然后不要将图像转换为灰度。让它们保持 3 通道 RGB。从 cv2.imread() 命令中删除 cv2.IMREAD_GRAYSCALE
    • 是的,我删除了 cv2.imread_grayscale 但输出仍然不是 RGB,我在 jupyter notebook 中测试。我删除了输入和背景图像的灰度。
    • 您是否将其从两者中删除?您是从磁盘读取这两个图像还是从其他处理中获取它们?如果是后者,则使用 cv2.merge() 或 cv2.cvtColor() 将任何灰度图像转换为 3 通道
    • 是的,我正在从磁盘读取图像..我将检查该代码并再次更新谢谢。
    猜你喜欢
    • 2021-06-25
    • 2021-10-28
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    相关资源
    最近更新 更多