大图像轮廓上的Python开放式CV叠加图像

2024-05-20 00:00:14 发布

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

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

我有这张图片enter image description here

我有一个控制器,它检测图像的形状和颜色

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

代码不起作用猴子被印在左上角


Tags: and代码图像imgif颜色图片blue
1条回答
网友
1楼 · 发布于 2024-05-20 00:00:14

我有一个可行的解决方案。希望这就是你想要的。在

代码:

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

相关问题 更多 >