大图像轮廓上的Python Open CV覆盖图像

时间:2018-07-31 05:34:06

标签: python opencv

我有一个很大的形状图像,我希望在基于轮廓的形状上重叠图像

我有这张图片enter image description here

我在此Contur中检测图像的形状和颜色

enter image description here

我要在此形状上放置图片

我要自定义调整图片大小

enter image description here

需要的输出权:-

enter image description here

代码:-

if color == "blue" and shape == "pentagon":
    A_img = cv2.imread("frame.png")
    print(A_img)
    x_offset=y_offset=50
    B_img[y_offset:y_offset+A_img.shape[0], x_offset:x_offset+A_img.shape[1]] = A_img

该代码不起作用,猴子被打印在左上方

1 个答案:

答案 0 :(得分:2)

我有一个可行的解决方案。希望它就是您想要的。

代码:

import cv2
import numpy as np

image = cv2.imread('C:/Users/524316/Desktop/shapes.png', 1)
monkey = cv2.imread('C:/Users/524316/Desktop/monkey.png', 1)

image2 = image.copy()
image3 = image.copy()

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
#cv2.imshow('thresh', thresh)

_, cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for c in cnts:

    #---- making sure to avoid small unwanted contours ---
    if cv2.contourArea(c) > 150:

        #--- selecting contours having 5 sides ---
        if len(cv2.approxPolyDP(c, 0.04 * cv2.arcLength(c, True), True)) == 5:


            cv2.drawContours(image2, [c], -1, (0, 255, 0), 2)

            #--- finding bounding box dimensions of the contour ---
            x, y, w, h = cv2.boundingRect(c)
            print(x, y, w, h)

            #--- overlaying the monkey in place of pentagons using the bounding box dimensions---
            image3[y:y+h, x:x+w] = cv2.resize(monkey, (np.abs(x - (x+w)), np.abs(y - (y+h))))


cv2.imshow('image2', image2)
cv2.imshow('image3', image3) 

cv2.waitKey(0)
cv2.destroyAllWindows()

结果:

enter image description here

enter image description here