我怀疑仅使用 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。
上述脚本的输出如下所示:
希望有帮助!