Skip to content

Instantly share code, notes, and snippets.

@zelinskiy
Last active August 16, 2019 11:00
Show Gist options
  • Save zelinskiy/4bcabb26aad0c8866ee89f39cb198217 to your computer and use it in GitHub Desktop.
Save zelinskiy/4bcabb26aad0c8866ee89f39cb198217 to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
import itertools
import random as rnd
# TODO:
# swap so that img1 always over img2
def fix_overlap(res, img1, x1, y1, img2, x2, y2):
h1, w1, _ = img1.shape
h2, w2, _ = img2.shape
if y2 < y1:
x1, y1, w1, h1, x2, y2, w2, h2 = x2, y2, w2, h2, x1, y1, w1, h1
if x1 < x2:
for y in range(y2, y1 + h1):
for x in range(x2, x1 + w1):
w, h = x1 + w1 - x2, y1 + h1 - y2
x_, y_ = x - x2, y - y2
if x_ < (w * (h - y_)) / h - 1:
px = tuple(int(c) for c in img1[y_, x_])
else:
px = tuple(int(c) for c in img2[y_, x_])
res[y, x] = px
else:
for y in range(y2, y1 + h1):
for x in range(x1, x2 + w2):
w, h = x2 + w2 - x1, y1 + h1 - y2
x_, y_ = x - x1, y - y2
if x_ < (y_ * w) / h + 1:
px = tuple(int(c) for c in img1[y_, x_])
else:
px = tuple(int(c) for c in img2[y_, x_])
res[y, x] = px
def fix_overlaps(res, imgs):
imgs.sort(key=lambda r: r[1])
for (i1, i2) in itertools.combinations(imgs, 2):
fix_overlap(res, i1[0], i1[1], i1[2], i2[0], i2[1], i2[2])
if __name__ == "__main__":
height, width = 800, 1200
x1, y1 = 100, 200
w1, h1 = 200, 300
x2, y2 = 200, 300
w2, h2 = 300, 300
x3, y3 = 350, 50
w3, h3 = 300, 400
x4, y4 = 550, 000
w4, h4 = 150, 250
img1 = np.full((h1, w1, 3), (0, 0, 255), np.uint8) # red
img2 = np.full((h2, w2, 3), (0, 255, 0), np.uint8) # green
img3 = np.full((h3, w3, 3), (255, 0, 0), np.uint8) # blue
img4 = np.full((h4, w4, 3), (0, 127, 127), np.uint8) # brown
res = np.zeros((height, width, 3), np.uint8)
res[y4:y4 + h4, x4:x4 + w4] = img4
res[y3:y3 + h3, x3:x3 + w3] = img3
res[y2:y2 + h2, x2:x2 + w2] = img2
res[y1:y1 + h1, x1:x1 + w1] = img1
imgs = [(img1, x1, y1), (img2, x2, y2), (img3, x3, y3), (img4, x4, y4)]
for _ in range(3):
rnd.shuffle(imgs)
fix_overlaps(res, imgs)
cv2.imshow('frame', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment