将图片插入框架

2024-09-28 05:27:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个漂亮的相框,需要插入这个相框的图像。你知道吗

Frame

这个框架

Image

这张照片

Python代码

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

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

如何插入由红色轮廓构成的图像。你知道吗

轮廓角已知。(我在photoshop中查看)


Tags: 代码图像image框架saveshowopenframe
1条回答
网友
1楼 · 发布于 2024-09-28 05:27:35

我怀疑这项任务只能通过使用PIL/枕头来完成,至少如果你想自动找到红框等

因此,如果使用OpenCV是一种选择,我建议使用一些颜色阈值和^{}的以下解决方案。例如,这种方法也应适用于略读。你知道吗

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颜色空间,然后使用^{}。有关这方面的介绍,请参见one of my earlier answers。你知道吗

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

Output

希望有帮助!你知道吗

相关问题 更多 >

    热门问题