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.
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.