def mask_image(lower_mask, upper_mask, img, apply_mask=False):
"""" Masks an image according to the upper and lower bounds
Parameters
----------
lower_mask : ndarray
lower mask to apply to image, length must match image channels
upper_mask : ndarray
upper mask to apply to image, length must match image channels
img : ndarray
image to apply mask to
apply_mask : bool
returns the masked image instead of the mask itself
"""
shape = np.array(img.shape).flatten()
if len(np.array(img.shape).flatten()) == 3:
shape_size = shape[-1]
else:
shape_size = 1
assert (len(lower_mask) == shape_size)
assert (len(upper_mask) == shape_size)
color_min = np.array(lower_mask, np.uint8)
color_max = np.array(upper_mask, np.uint8)
new_img = cv2.inRange(img, color_min, color_max)
if apply_mask:
return cv2.bitwise_and(img, img, mask=new_img)
return new_img
python类bitwise_and()的实例源码
def text_mask_img(self):
img = self.img_grey.copy()
mask = np.ones(img.shape[:2], dtype="uint8") * 255
for contour_node in self.contour_nodes:
cv2.drawContours(mask, contour_node.contour, -1, 0, -1)
image = cv2.bitwise_and(img, img, mask=mask)
return img
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
# defining a blank mask to start with
mask = np.zeros_like(img)
# defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
# filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
# returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def extract_bv(image):
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
contrast_enhanced_green_fundus = clahe.apply(image)
# applying alternate sequential filtering (3 times closing opening)
r1 = cv2.morphologyEx(contrast_enhanced_green_fundus, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
R1 = cv2.morphologyEx(r1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
r2 = cv2.morphologyEx(R1, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
R2 = cv2.morphologyEx(r2, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
r3 = cv2.morphologyEx(R2, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
R3 = cv2.morphologyEx(r3, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
f4 = cv2.subtract(R3,contrast_enhanced_green_fundus)
f5 = clahe.apply(f4)
# removing very small contours through area parameter noise removal
ret,f6 = cv2.threshold(f5,15,255,cv2.THRESH_BINARY)
mask = np.ones(f5.shape[:2], dtype="uint8") * 255
im2, contours, hierarchy = cv2.findContours(f6.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt) <= 200:
cv2.drawContours(mask, [cnt], -1, 0, -1)
im = cv2.bitwise_and(f5, f5, mask=mask)
ret,fin = cv2.threshold(im,15,255,cv2.THRESH_BINARY_INV)
newfin = cv2.erode(fin, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
# removing blobs of microaneurysm & unwanted bigger chunks taking in consideration they are not straight lines like blood
# vessels and also in an interval of area
fundus_eroded = cv2.bitwise_not(newfin)
xmask = np.ones(image.shape[:2], dtype="uint8") * 255
x1, xcontours, xhierarchy = cv2.findContours(fundus_eroded.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in xcontours:
shape = "unidentified"
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.04 * peri, False)
if len(approx) > 4 and cv2.contourArea(cnt) <= 3000 and cv2.contourArea(cnt) >= 100:
shape = "circle"
else:
shape = "veins"
if(shape=="circle"):
cv2.drawContours(xmask, [cnt], -1, 0, -1)
finimage = cv2.bitwise_and(fundus_eroded,fundus_eroded,mask=xmask)
blood_vessels = cv2.bitwise_not(finimage)
dilated = cv2.erode(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7)), iterations=1)
#dilated1 = cv2.dilate(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
blood_vessels_1 = cv2.bitwise_not(dilated)
return blood_vessels_1
def extract_bv(image):
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
contrast_enhanced_green_fundus = clahe.apply(image)
# applying alternate sequential filtering (3 times closing opening)
r1 = cv2.morphologyEx(contrast_enhanced_green_fundus, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
R1 = cv2.morphologyEx(r1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
r2 = cv2.morphologyEx(R1, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
R2 = cv2.morphologyEx(r2, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
r3 = cv2.morphologyEx(R2, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
R3 = cv2.morphologyEx(r3, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
f4 = cv2.subtract(R3,contrast_enhanced_green_fundus)
f5 = clahe.apply(f4)
# removing very small contours through area parameter noise removal
ret,f6 = cv2.threshold(f5,15,255,cv2.THRESH_BINARY)
mask = np.ones(f5.shape[:2], dtype="uint8") * 255
im2, contours, hierarchy = cv2.findContours(f6.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt) <= 200:
cv2.drawContours(mask, [cnt], -1, 0, -1)
im = cv2.bitwise_and(f5, f5, mask=mask)
ret,fin = cv2.threshold(im,15,255,cv2.THRESH_BINARY_INV)
newfin = cv2.erode(fin, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
# removing blobs of microaneurysm & unwanted bigger chunks taking in consideration they are not straight lines like blood
# vessels and also in an interval of area
fundus_eroded = cv2.bitwise_not(newfin)
xmask = np.ones(image.shape[:2], dtype="uint8") * 255
x1, xcontours, xhierarchy = cv2.findContours(fundus_eroded.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in xcontours:
shape = "unidentified"
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.04 * peri, False)
if len(approx) > 4 and cv2.contourArea(cnt) <= 3000 and cv2.contourArea(cnt) >= 100:
shape = "circle"
else:
shape = "veins"
if(shape=="circle"):
cv2.drawContours(xmask, [cnt], -1, 0, -1)
finimage = cv2.bitwise_and(fundus_eroded,fundus_eroded,mask=xmask)
blood_vessels = cv2.bitwise_not(finimage)
dilated = cv2.erode(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7)), iterations=1)
#dilated1 = cv2.dilate(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
blood_vessels_1 = cv2.bitwise_not(dilated)
return blood_vessels_1
def skin_filter(cfg, vd):
df = pd.read_csv(vd.photo_csv, index_col=0)
numbers = df.number.tolist()
notface = []
for number in numbers:
lower = np.array([0, 48, 80], dtype = "uint8")
upper = np.array([13, 255, 255], dtype = "uint8")
image = cv2.imread('%s/%d.png' % (vd.photo_dir, number), cv2.IMREAD_COLOR)
converted = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
skinMask = cv2.inRange(converted, lower, upper)
# apply a series of erosions and dilations to the mask
# using an elliptical kernel
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
skinMask = cv2.erode(skinMask, kernel, iterations = 2)
skinMask = cv2.dilate(skinMask, kernel, iterations = 2)
# blur the mask to help remove noise, then apply the
# mask to the frame
skinMask = cv2.GaussianBlur(skinMask, (3, 3), 0)
skin = cv2.bitwise_and(image, image, mask = skinMask)
if len(skin.nonzero()[0]) < cfg.min_skin_pixels:
notface.append(number)
print '%d/%d are faces' % ( len(df) - len(notface), len(df) )
df['face']= 1
df.loc[df.number.isin(notface),'face'] = -99
df.to_csv(vd.photo_csv)
def __add_figure_to_frame(self, frame, figure_location):
"""This function is used to add a file from hard disk to the figure
Algorithm source: http://docs.opencv.org/trunk/d0/d86/tutorial_py_image_arithmetics.html
"""
# Get size of frame
height, width, channels = frame.shape
# Only add icon when the frame is big enough
if height >= 100 and width >= 100:
# Load heart icon
icon_heart = cv2.imread(figure_location)
# Convert to RGB
icon_heart = cv2.cvtColor(icon_heart, cv2.COLOR_BGR2RGB)
# Create ROI
rows, cols, channels = icon_heart.shape
roi = frame[:rows, :cols, :]
# Convert heart to greyscale
icon_heart_gray = cv2.cvtColor(icon_heart, cv2.COLOR_RGB2GRAY)
# Create mask and inverse mask with binary threshold
ret, mask = cv2.threshold(icon_heart_gray, 10, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
# Background: Original frame with inverse mask
frame_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)
# Foreground: Heart with normal mask
icon_heart_fg = cv2.bitwise_and(icon_heart, icon_heart, mask=mask)
# Add heart icon to frame
icon_heart_final = cv2.add(frame_bg, icon_heart_fg)
frame[:rows, :cols, :] = icon_heart_final
return frame
# Setter and getter following
def diffImg(t0, t1, t2):
d1 = cv2.absdiff(t2, t1)
d2 = cv2.absdiff(t1, t0)
return cv2.bitwise_and(d1, d2)
#Form Config
def image_callback(self, msg):
# BEGIN BRIDGE
image = self.bridge.imgmsg_to_cv2(msg)
# END BRIDGE
# BEGIN HSV
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# END HSV
# BEGIN FILTER
lower_yellow = numpy.array([18, 120, 200])
upper_yellow = numpy.array([28, 255, 255])
mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
# END FILTER
masked = cv2.bitwise_and(image, image, mask=mask)
cv2.imshow("window", mask )
cv2.waitKey(3)
Artificial-potential-without-controller.py 文件源码
项目:Artificial-Potential-Field
作者: vampcoder
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def find_robot(im):
hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
lower = np.array([50, 28, 0])
upper = np.array([60, 168, 255])
mask = cv2.inRange(hsv, lower, upper)
result = cv2.bitwise_and(im, im, mask=mask)
blur = cv2.blur(result, (5, 5))
bw = cv2.cvtColor(blur, cv2.COLOR_HSV2BGR)
bw2 = cv2.cvtColor(bw, cv2.COLOR_BGR2GRAY)
ret, th3 = cv2.threshold(bw2, 30, 255, cv2.THRESH_BINARY)
edges = cv2.Canny(th3, 100, 200)
th4 = copy.copy(th3)
perimeter = 0
j = 0
image, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = np.array([])
for i in range(len(contours)):
if (perimeter < cv2.contourArea(contours[i])):
perimeter = cv2.contourArea(contours[i])
j = i;
cnt = contours[j]
x = 0
y = 0
for i in range(len(cnt)):
x = x + cnt[i][0][0]
y = y + cnt[i][0][1]
x = x / len(cnt)
y = y / len(cnt)
#print x, y
x = int(x)
y = int(y)
cv2.circle(im, (x, y), 5, (255, 0, 255), 2)
#show_image(im)
return (int(x), int(y))
Artificial-potential-controller.py 文件源码
项目:Artificial-Potential-Field
作者: vampcoder
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def find_robot(frame):
im = copy.copy(frame)
hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
lower = np.array([50, 28, 0])
upper = np.array([60, 168, 255])
mask = cv2.inRange(hsv, lower, upper)
result = cv2.bitwise_and(im, im, mask=mask)
blur = cv2.blur(result, (5, 5))
bw = cv2.cvtColor(blur, cv2.COLOR_HSV2BGR)
bw2 = cv2.cvtColor(bw, cv2.COLOR_BGR2GRAY)
ret, th3 = cv2.threshold(bw2, 30, 255, cv2.THRESH_BINARY)
edges = cv2.Canny(th3, 100, 200)
th4 = copy.copy(th3)
perimeter = 0
j = 0
image, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = np.array([])
for i in range(len(contours)):
if (perimeter < cv2.contourArea(contours[i])):
perimeter = cv2.contourArea(contours[i])
j = i;
cnt = contours[j]
x = 0
y = 0
for i in range(len(cnt)):
x = x + cnt[i][0][0]
y = y + cnt[i][0][1]
x = x / len(cnt)
y = y / len(cnt)
#print x, y
x = int(x)
y = int(y)
cv2.circle(im, (x, y), 5, (255, 0, 255), 2)
cv2.imshow('img', im)
k = cv2.waitKey(0)
cv2.imwrite('robot.jpg', im)
#show_image(im)
return (int(x), int(y))
def suppress_artifacts(self, img, global_threshold=.05, fill_holes=False,
smooth_boundary=True, kernel_size=15):
'''Mask artifacts from an input image
Artifacts refer to textual markings and other small objects that are
not related to the breast region.
Args:
img (2D array): input image as a numpy 2D array.
global_threshold ([int]): a global threshold as a cutoff for low
intensities for image binarization. Default is 18.
kernel_size ([int]): kernel size for morphological operations.
Default is 15.
Returns:
a tuple of (output_image, breast_mask). Both are 2D numpy arrays.
'''
maxval = self.max_pix_val(img.dtype)
if global_threshold < 1.:
low_th = int(img.max()*global_threshold)
else:
low_th = int(global_threshold)
_, img_bin = cv2.threshold(img, low_th, maxval=maxval,
type=cv2.THRESH_BINARY)
breast_mask = self.select_largest_obj(img_bin, lab_val=maxval,
fill_holes=True,
smooth_boundary=True,
kernel_size=kernel_size)
img_suppr = cv2.bitwise_and(img, breast_mask)
return (img_suppr, breast_mask)
def segment_breast(cls, img, low_int_threshold=.05, crop=True):
'''Perform breast segmentation
Args:
low_int_threshold([float or int]): Low intensity threshold to
filter out background. It can be a fraction of the max
intensity value or an integer intensity value.
crop ([bool]): Whether or not to crop the image.
Returns:
An image of the segmented breast.
NOTES: the low_int_threshold is applied to an image of dtype 'uint8',
which has a max value of 255.
'''
# Create img for thresholding and contours.
img_8u = (img.astype('float32')/img.max()*255).astype('uint8')
if low_int_threshold < 1.:
low_th = int(img_8u.max()*low_int_threshold)
else:
low_th = int(low_int_threshold)
_, img_bin = cv2.threshold(
img_8u, low_th, maxval=255, type=cv2.THRESH_BINARY)
ver = (cv2.__version__).split('.')
if int(ver[0]) < 3:
contours,_ = cv2.findContours(
img_bin.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
else:
_,contours,_ = cv2.findContours(
img_bin.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cont_areas = [ cv2.contourArea(cont) for cont in contours ]
idx = np.argmax(cont_areas) # find the largest contour, i.e. breast.
breast_mask = cv2.drawContours(
np.zeros_like(img_bin), contours, idx, 255, -1) # fill the contour.
# segment the breast.
img_breast_only = cv2.bitwise_and(img, img, mask=breast_mask)
x,y,w,h = cv2.boundingRect(contours[idx])
if crop:
img_breast_only = img_breast_only[y:y+h, x:x+w]
return img_breast_only, (x,y,w,h)
HandRecognition.py 文件源码
项目:hand-gesture-recognition-opencv
作者: mahaveerverma
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def remove_bg(frame):
fg_mask=bg_model.apply(frame)
kernel = np.ones((3,3),np.uint8)
fg_mask=cv2.erode(fg_mask,kernel,iterations = 1)
frame=cv2.bitwise_and(frame,frame,mask=fg_mask)
return frame
# ------------------------ BEGIN ------------------------ #
# Camera
def screen_position():
'''
Returns position of rectangle x,y,w,h if:
- bounding rectangle is big enough (more than 0.2 % of total captured image)
- contour's area is more than 70% of the area of the bounding rectangle
'''
cap = cv2.VideoCapture(0)
nb_max_iterations = int(30*ALLOWED_DETECTION_TIME)
for it in range(nb_max_iterations):
ret, frame = cap.read()
mask = detect_color(frame)
masked_frame = cv2.bitwise_and(frame, frame, mask=mask)
imgray = cv2.cvtColor(masked_frame, cv2.COLOR_BGR2GRAY)
contours, hierarchy = cv2.findContours(imgray,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
contours = sorted(contours, key=lambda x:len(x), reverse=True)
i = 0
while(i < len(contours)):
x,y,w,h = cv2.boundingRect(contours[i])
rect_cnt = np.array([[[x, y]], [[x+w, y]], [[x+w, y+h]], [[x, y+h]]], dtype=np.int32)
rect_cnt_area = cv2.contourArea(rect_cnt)
if(cv2.contourArea(contours[i]) > VALID_AREA_RATIO * rect_cnt_area and \
rect_cnt_area > VALID_MIN_AREA and \
rect_cnt_area < VALID_MAX_AREA):
cap.release()
return x,y,w,h
else:
i += 1
cap.release()
return -1,-1,-1,-1
def main():
'''
Test screen_position
'''
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
mask = detect_color(frame)
cv2.imshow('frame', frame)
cv2.imshow('mask', mask)
masked_frame = cv2.bitwise_and(frame, frame, mask=mask)
imgray = cv2.cvtColor(masked_frame, cv2.COLOR_BGR2GRAY)
contours, hierarchy = cv2.findContours(imgray,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
contours = sorted(contours, key=lambda x:len(x), reverse=True)
i = 0
while(i < len(contours)):
x,y,w,h = cv2.boundingRect(contours[i])
rect_cnt = np.array([[[x, y]], [[x+w, y]], [[x+w, y+h]], [[x, y+h]]], dtype=np.int32)
rect_cnt_area = cv2.contourArea(rect_cnt)
if(cv2.contourArea(contours[i]) > VALID_AREA_RATIO * rect_cnt_area and \
rect_cnt_area > VALID_MIN_AREA and \
rect_cnt_area < VALID_MAX_AREA):
cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
break
else:
i += 1
cv2.imshow('Contours', frame)
if cv2.waitKey(1) & 0xFF == 27:
break
print(get_screen_gray_level(masked_frame))
cap.release()
cv2.destroyAllWindows()
def test_output_as_mask(self):
image = 255 * np.ones((10, 10), np.uint8)
mask = np.zeros(image.shape, np.uint8)
masked = cv2.bitwise_and(image, image, mask=mask)
func = utils.output_as_mask(lambda x: (x, mask))
assert np.array_equal(masked, func(image))
assert np.array_equal(mask, func(image, return_mask=True))
detect_color.py 文件源码
项目:political-ad-classifier
作者: BoudhayanBanerjee
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def checkBluePixel(inputPath):
"""
docstring
"""
im = cv2.imread(inputPath, 1)
# Convert BGR to HSV
hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
# define range of blue color in HSV
lower_blue = np.array([110, 50, 50])
upper_blue = np.array([130, 255, 255])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_blue, upper_blue)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(im, im, mask=mask)
# save temp image
cv2.imwrite(os.path.join(TEMP, 'temp.png'), res)
ct = ColorThief(os.path.join(TEMP, 'temp.png'))
palette = ct.get_palette(color_count=5)
for p in palette:
r = p[0]
g = p[1]
b = p[2]
bgr = np.uint8([[[p[2], p[1], p[0]]]])
hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)
h = hsv[0][0][0]
s = hsv[0][0][1]
v = hsv[0][0][2]
if ((h >= 110 and h <= 130) and (s >= 50 and s <= 255) and (v >= 50 and v <= 255)):
return True
break
detect_color.py 文件源码
项目:political-ad-classifier
作者: BoudhayanBanerjee
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def checkRedPixel(inputPath):
"""
docstring
"""
im = cv2.imread(inputPath, 1)
# Convert BGR to HSV
hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
# define range of red color in HSV
lower_red = np.array([0, 100, 100])
upper_red = np.array([10, 255, 255])
# Threshold the HSV image to get only red colors
mask1 = cv2.inRange(hsv, lower_red, upper_red)
# define range of red color in HSV
lower_red = np.array([170, 100, 100])
upper_red = np.array([180, 255, 255])
# Threshold the HSV image to get only red colors
mask2 = cv2.inRange(hsv, lower_red, upper_red)
mask = mask1 + mask2
# Bitwise-AND mask and original image
res = cv2.bitwise_and(im, im, mask=mask)
# save temp image
cv2.imwrite(os.path.join(TEMP, 'temp.png'), res)
ct = ColorThief(os.path.join(TEMP, 'temp.png'))
palette = ct.get_palette(color_count=5)
for p in palette:
r = p[0]
g = p[1]
b = p[2]
bgr = np.uint8([[[p[2], p[1], p[0]]]])
hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)
h = hsv[0][0][0]
s = hsv[0][0][1]
v = hsv[0][0][2]
if ((h >= 0 and h <= 10) and (s >= 100 and s <= 255) and (v >= 100 and v <= 255)) or ((h >= 170 and h <= 180) and (s >= 100 and s <= 255) and (v >= 100 and v <= 255)):
return True
break
def track_obj(low_hsv, high_hsv):
# Open the "default" camera
vc = cv2.VideoCapture(0)
# Check if we succeeded in opening camera feed
if vc.isOpened():
rval, frame = vc.read()
else:
rval = False
# Display captured frames in a new window
cv2.namedWindow("Camera Video Feed")
# Display filtered object frame in a new window
cv2.namedWindow("Tracking")
result = frame
while rval:
cv2.imshow("Camera Video Feed", frame)
cv2.imshow("Tracking", result)
rval, frame = vc.read()
# Convert to HSV space
frameHSV = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Filter out components with values in selected range
# Threshold HSV image
mask = cv2.inRange(frameHSV, low_hsv, high_hsv)
result = cv2.bitwise_and(frame, frame, mask = mask)
# Wait for ESC key press
key = cv2.waitKey(20)
if key == 27: # User pressed ESC key
break
# Destroy window
cv2.destroyWindow("Camera Video Feed")
# Close VideoCapture feed -- Important!
vc.release()