Вставьте изображение на подложку - PullRequest
0 голосов
/ 29 октября 2019

, пожалуйста, помогите мне, мне нужно вставить изображение на подложку.

подложка:

enter image description here

Это png, ив области, не содержащей городов, необходимо вставить изображение от края до края рамки.

Проблема в том, что я не могу найти пример того, как вставить изображение в известные точки координатуглов данной подложки.

Пожалуйста, помогите))

Мой тестовый образ

enter image description here


import cv2
import numpy as np
from skimage import io      

frame = cv2.cvtColor(io.imread('as.png'), cv2.COLOR_RGB2BGR)
image = cv2.cvtColor(io.imread("Vw5Rc.jpg"), cv2.COLOR_RGB2BGR)

mask = 255 * np.uint8(np.all(frame == [0, 0, 0], axis=2))

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.imwrite('frame.png', frame)

Я пытаюсь найти область, в которую можно вставить изображение по цвету, красный цвет области, которую я могу найти, и если цвет отсутствует?

Статическая рамка имеет постоянный размер.

1 Ответ

2 голосов
/ 29 октября 2019

Вот один из способов сделать это в Python / OpenCV, если я понимаю, что вы хотите.

Read the substrate and trees images

Extract the alpha channel from the substrate

Extract the substrate image without the alpha channel

Use the alpha channel to color the base substrate image white where the alpha channel is black to correct a flaw in the base image

Threshold the alpha channel and invert it

Use morphology to remove the grid lines so that there is only one "outer" contour.

Extract the contour and its bounding box

Resize the trees image to the size of the bounding box.

Use numpy indexing and slicing to multiply the region of the substrate with the resized trees image.

Save the results.

Optionally, display the various images.


Изображение подложки:

enter image description here

Деревья Изображение:

enter image description here

import cv2
import numpy as np

# load substrate with alpha channel
substrate = cv2.imread("substrate.png", cv2.IMREAD_UNCHANGED)
hh, ww, cc = substrate.shape

# load colored image
trees = cv2.imread("trees.jpg")

# make img white where alpha is black to merge the alpha channel with the image
alpha = substrate[:,:,3]
img = substrate[:,:,0-2]
img[alpha==0] = 255
img = cv2.merge((img,img,img))

# threshold the img
ret, thresh = cv2.threshold(alpha,0,255,0)

# invert thresh
thresh = 255 - thresh

# make grid lines white in thresh so will get only one contour
kernel = np.ones((9,9), np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# find one outer contour
cntrs = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]

# get bounding box of contour of white rectangle in thresh
for c in cntrs:
    x,y,w,h = cv2.boundingRect(c)
    #cv2.rectangle(img, (x,y), (x+w,y+h),(0, 0, 255), 2)

# resize trees
trees = cv2.resize(trees,(w,h),0,0)

# generate result
result = img.copy()
result[y:y+h, x:x+w] = img[y:y+h, x:x+w]/255 * trees

# write result to disk
cv2.imwrite("substrate_over_trees.jpg", result)

cv2.imshow("ALPHA", alpha)
cv2.imshow("IMG", img)
cv2.imshow("THRESH", thresh)
cv2.imshow("TREES", trees)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()


Результат:

enter image description here

Обратите внимание, что существует искажение изображения деревьев, поскольку его соотношение сторон не соответствует области изображения подложки, соответствующей рамке, ограничивающей контур. Это можно изменить, чтобы сохранить соотношение сторон, но тогда изображение необходимо будет добавить к белому или другому цвету, чтобы заполнить оставшуюся область ограничивающей рамки.

...