Skip to content

Instantly share code, notes, and snippets.

@Umraiz
Created July 2, 2017 05:19
Show Gist options
  • Save Umraiz/5b9ed75d6210721f923f776d2b4da917 to your computer and use it in GitHub Desktop.
Save Umraiz/5b9ed75d6210721f923f776d2b4da917 to your computer and use it in GitHub Desktop.
Photo Collage from Webcam
import cv2
import numpy as np
import random
import math
#capture webcam
cap = cv2.VideoCapture(0)
#mmm determines the size of the collage.
#mmm must be >3000
mmm = 3000
b = mmm/8
global mmm
#create background for collage
collage = np.zeros((mmm,mmm,3), np.uint8)
#overlays a picture onto the collage
def overlay(img, bg):
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
_ ,mask = cv2.threshold(imgray,2,255,0)
mask_inv = 255-mask
img1_bg = cv2.bitwise_and(bg,bg,mask = mask_inv)
img2_fg = cv2.bitwise_and(img,img,mask = mask)
res = cv2.add(img1_bg,img2_fg)
return res
#rotates an image
def rotate(img):
global mmm
bg = np.zeros((mmm,mmm,3), np.uint8)
scale = random.random()*2
h,w = img.shape[:2]
if scale<.1: scale = .5
img = cv2.resize(img, (int(w*scale), int(h*scale)))
h,w = img.shape[:2]
xxx = mmm/4
a,b = random.randint(-xxx,xxx),random.randint(-xxx,xxx)
try: bg[mmm/2+a-mmm/10:mmm/2+h+a-mmm/10, mmm/2+b-mmm/10:mmm/2+w+b-mmm/10] = img
except: pass
img = bg
h,w = img.shape[:2]
M = cv2.getRotationMatrix2D((w/2, h/2), random.randint(-50,50), 1)
dst = cv2.warpAffine(img, M, (w,h))
if random.random>.5: dst = cv2.flip(dst, 1)
return dst
#main loop
while True:
_, img = cap.read()
cv2.imshow('img', cv2.resize(img, (300,300)))
cv2.imshow('collage', cv2.resize(collage[b:mmm-b, b:mmm-b], (600,600)))
k = cv2.waitKey(1)
if k == 115:
img = rotate(img)
collage = overlay(img, collage)
if k == 27: break
cv2.destroyAllWindows()
cap.release()
cv2.imwrite('collage.png', collage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment