Insert The Picture Into The Frame
I have a beautiful frame, and the image that needs to be inserted into this frame. This frame This image Python code frame = Image.open('pathToFirstImage') image = Image.open('pa
Solution 1:
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.
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()
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.
The output of the above script looks like this:
Hope that helps!
Post a Comment for "Insert The Picture Into The Frame"