将图片插入相框 [英] Insert the picture into the frame

查看:92
本文介绍了将图片插入相框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个漂亮的框架,需要将图像插入此框架.

I have a beautiful frame, and the image that needs to be inserted into this frame.

此框架

此图片

Python代码

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

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

如何插入以红色轮廓框住的图像.

How to Insert an image, framed by the red outline.

轮廓角是已知的. (我在photoshop中看过)

The contour angles are known. (I looked in photoshop)

推荐答案

我怀疑只能通过使用PIL/Pillow来实现此任务,至少在您想要自动查找红色框等时如此.

I'm skeptical that this task can be achieved by only using PIL/Pillow, at least if you want some automatic finding of the red frame, etc.

因此,如果可以选择使用OpenCV,我建议使用一些颜色阈值和

So, if using OpenCV is an option, I would suggest the following solution using some color thresholding and cv2.findContours. This approach should be also transferable to skimage for example.

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 .有关此内容的介绍,请参见我以前的答案之一.

As stated in the comment, color thresholding in this example is done by simply checking for the specific BGR value of the frame. A more sophisticated solution would be converting the frame to the HSV/HSL color space, and then using cv2.inRange. For an introduction on that, please see one of my earlier answers.

以上脚本的输出如下:

希望有帮助!

这篇关于将图片插入相框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆