0

I want to overlay several small pictures of shapes over a larger picture of a red background. I implemented a function to do this and it works fine when I first call the function to overlay the triangle. However, when I try calling it again with a square image, the "ROI" image is of the triangle instead of the background by itself. This is my code:

import cv2

background = cv2.imread('red.jpg')
triangle = cv2.imread('triangle.jpg')
square = cv2.imread('square.jpg')

# Resize the images
b_w = 1000
b_h = 500
dim = (b_w, b_h)
background = cv2.resize(background, dim, interpolation=cv2.INTER_AREA)

t_w = 300
t_h = 300
dim = (t_w, t_h)
triangle = cv2.resize(triangle, dim, interpolation=cv2.INTER_AREA)

s_w = 300
s_h = 300
dim = (s_w, s_h)
square = cv2.resize(square, dim, interpolation=cv2.INTER_AREA)


def topper (background, shape):
    offset_x = 400
    offset_y = 170

    roi = background[offset_y:470, offset_x:700]
    cv2.imshow('ROI', roi)
    cv2.waitKey()
    cv2.destroyAllWindows()

    grey = cv2.cvtColor(shape, cv2.COLOR_RGB2GRAY)
    cv2.imshow('gray', grey)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    ret, mask = cv2.threshold(grey, 145, 255, cv2.THRESH_BINARY)
    cv2.imshow('mask', mask)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    bg = cv2.bitwise_or(roi, roi, mask=mask)
    cv2.imshow('bg', bg)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    background[offset_y: offset_y + grey.shape[0], offset_x: offset_x + grey.shape[1]] = bg
    cv2.imshow('final_roi', background)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

topper(background, triangle)
topper(background, square)

These are the outputs: The triangle outputs are fine - this is what I want. enter image description here

Here is the square and as you can see, it overlays the square on top of the triangle. I'm not sure why it does this. enter image description here

peru_45
  • 330
  • 3
  • 16
  • your "rock" image is higher that your "playground"! – Miki Feb 25 '22 at 16:12
  • Does this help? https://stackoverflow.com/questions/70352659/cv2-warpperspective-produces-black-dotted-edges/70355007#70355007 – fmw42 Feb 25 '22 at 17:10
  • @Miki I have resized it to be smaller – peru_45 Feb 25 '22 at 17:17
  • 3
    I’m not sure what are you doing with your code, but you are processing shallow copies of the matrices. These copies share data across the variables you use, so if you indirectly modify one you are modifying all the shared data. You need deep copies, which are new matrices with their own allocated space in memory. These are not shared. In python, you create deep copies of a `Numpy` array using the `copy` method: https://numpy.org/doc/stable/reference/generated/numpy.ndarray.copy.html – stateMachine Feb 26 '22 at 01:41

0 Answers0