Created
June 30, 2019 01:55
-
-
Save ramazanpolat/bcedca0111debcc04e8ca649af52fa46 to your computer and use it in GitHub Desktop.
background extraction with opencv
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import copy | |
class Copyable: | |
__slots__ = 'a', '__dict__' | |
def __init__(self, a, b): | |
self.a, self.b = a, b | |
def __copy__(self): | |
return type(self)(self.a, self.b) | |
def __deepcopy__(self, memo): # memo is a dict of id's to copies | |
id_self = id(self) # memoization avoids unnecesary recursion | |
_copy = memo.get(id_self) | |
if _copy is None: | |
_copy = type(self)( | |
copy.deepcopy(self.a, memo), | |
copy.deepcopy(self.b, memo)) | |
memo[id_self] = _copy | |
return _copy | |
def rescale_by_height(image, target_height, method=cv2.INTER_LANCZOS4): | |
"""Rescale `image` to `target_height` (preserving aspect ratio).""" | |
w = int(round(target_height * image.shape[1] / image.shape[0])) | |
return cv2.resize(image, (w, target_height), interpolation=method) | |
def rescale_by_width(image, target_width, method=cv2.INTER_LANCZOS4): | |
"""Rescale `image` to `target_width` (preserving aspect ratio).""" | |
h = int(round(target_width * image.shape[0] / image.shape[1])) | |
return cv2.resize(image, (target_width, h), interpolation=method) | |
def apply_mask(frame, mask): | |
"""Apply binary mask to frame, return masked image. | |
""" | |
return cv2.bitwise_and(frame, frame, mask=mask) | |
def main(): | |
cap = cv2.VideoCapture(0) | |
history = 10 | |
first_sub = cv2.createBackgroundSubtractorMOG2(history=history, varThreshold=50, detectShadows=False) | |
# learning | |
while True: | |
_, frame = cap.read() | |
frame_blurred = cv2.blur(frame, (10, 10)) | |
mask = first_sub.apply(frame_blurred) | |
cv2.imshow("Frame", rescale_by_height(frame, 240)) | |
cv2.imshow("Mask", rescale_by_height(mask, 240)) | |
cv2.imshow("Masked Frame", rescale_by_height(apply_mask(frame, mask), 240)) | |
cv2.imshow('BG', rescale_by_height(first_sub.getBackgroundImage(), 240)) | |
key = cv2.waitKey(30) | |
if key == 27: | |
break | |
cap.release() | |
cv2.destroyAllWindows() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment