Skip to content

Instantly share code, notes, and snippets.

@smeschke
Created April 13, 2018 22:40
Show Gist options
  • Select an option

  • Save smeschke/24ba17bbb81054677a742948dee5e8b8 to your computer and use it in GitHub Desktop.

Select an option

Save smeschke/24ba17bbb81054677a742948dee5e8b8 to your computer and use it in GitHub Desktop.
Persist Colors
#import cv2 for computer vision
#import numpy to make blank images
import cv2, numpy as np
#capture source video
cap = cv2.VideoCapture('/home/acer/Desktop/colorspace/bxx.MP4')
#define
#define orange
orange = 0,145,155,255,255,255
#takes and image and color range, returns a mask,
#and an image that has colors only from within the color range
def only_color(imgc, (h,s,v,h1,s1,v1)):
#convert image to hsv
hsv = cv2.cvtColor(imgc, cv2.COLOR_BGR2HSV)
#convert values to arrays
lower, upper = np.array([h,s,v]), np.array([h1,s1,v1])
#find the colors that are within the range of the lower and upper bounds
mask = cv2.inRange(hsv, lower, upper)
#use the bitwise and function to mask origional image
res = cv2.bitwise_and(imgc, imgc, mask=mask)
return res, mask
#create matte image that contains all the orange in the video
orange_bg = np.zeros((720,1280,3), np.uint8)
zeros = np.zeros_like(orange_bg)
#loop that reads each frame of video
while True:
#read image
_, img = cap.read()
#get the orange only parts of the image
orange_parts, mask = only_color(img, orange)
#mask out that part of the orange_bg image
mask = cv2.bitwise_not(mask)
orange_bg = cv2.bitwise_and(orange_bg, orange_bg, mask=mask)
#add the orange back
orange_bg = cv2.add(orange_bg, orange_parts)
#mask out the orange_bg portion of the image
gray = cv2.cvtColor(orange_bg, cv2.COLOR_BGR2GRAY)
_, mask = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)
mask = cv2.bitwise_not(mask)
img = cv2.bitwise_and(img, img, mask=mask)
img = cv2.add(img, orange_bg)
#show the image and wait
cv2.imshow('img', cv2.resize(img, (640,480)))
k=cv2.waitKey(1)
if k==27: break
#release the video to avoid memory leaks, and close the window
cap.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment