【问题标题】:Insert the picture into the frame将图片插入相框
【发布时间】:2020-02-21 16:29:54
【问题描述】:

我有一个漂亮的框架,以及需要插入到这个框架中的图像。

这个框架

这张图片

Python 代码

frame = Image.open("pathToFirstImage")
image = Image.open("pathToSecondImage")

frame.paste(image, (0,0))
frame.show()
frame.save("output image path")

如何插入由红色轮廓框起来的图像。

轮廓角是已知的。 (我在 Photoshop 中查看)

【问题讨论】:

    标签: python image python-imaging-library


    【解决方案1】:

    我怀疑仅使用 PIL/Pillow 就可以完成此任务,至少如果您想自动查找红框等。

    因此,如果可以选择使用 OpenCV,我建议使用一些颜色阈值和cv2.findContours 的以下解决方案。例如,这种方法也应该可以转移到 skimage。

    import cv2
    import numpy as np
    from skimage import io      # Only needed for web grabbing images; use cv2.imread(...) for local images
    
    # Read images
    frame = cv2.cvtColor(io.imread('https://i.stack.imgur.com/gVf0a.png'), cv2.COLOR_RGB2BGR)
    image = cv2.cvtColor(io.imread('https://i.stack.imgur.com/Vw5Rc.jpg'), cv2.COLOR_RGB2BGR)
    
    # Color threshold red frame; single color here, more sophisticated solution would be using cv2.inRange
    mask = 255 * np.uint8(np.all(frame == [36, 28, 237], axis=2))
    
    # Find inner contour of frame; get coordinates
    contours, _ = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    cnt = min(contours, key=cv2.contourArea)
    (x, y, w, h) = cv2.boundingRect(cnt)
    
    # Copy appropriately resized image to frame
    frame[y:y+h, x:x+w] = cv2.resize(image, (w, h))
    
    cv2.imshow('frame', frame)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    如评论中所述,此示例中的颜色阈值是通过简单地检查帧的特定 BGR 值来完成的。更复杂的解决方案是将帧转换为 HSV/HSL 颜色空间,然后使用cv2.inRange。相关介绍请见one of my earlier answers

    上述脚本的输出如下所示:

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 2017-11-15
      • 2010-11-25
      相关资源
      最近更新 更多