Created
January 22, 2022 13:14
-
-
Save InputBlackBoxOutput/d2fccbaecc5e2569bc85a337110da9b0 to your computer and use it in GitHub Desktop.
Perform skin segmentation by combining masks obtained by thresholding an image using multipe colour models
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
# Perform skin segmentation by combining masks obtained by thresholding an image using multipe colour models | |
# Modified from source: https://medium.com/swlh/human-skin-color-classification-using-the-threshold-classifier-rgb-ycbcr-hsv-python-code-d34d51febdf8 | |
import cv2 | |
import numpy as np | |
import matplotlib.pyplot as plt | |
def generate_RGB_mask(img): | |
B_Frame, G_Frame, R_Frame = [img[..., BGR] for BGR in range(3)] | |
BRG_Max = np.maximum.reduce([B_Frame, G_Frame, R_Frame]) | |
BRG_Min = np.minimum.reduce([B_Frame, G_Frame, R_Frame]) | |
# Uniform daylight | |
Rule_1 = np.logical_and.reduce([R_Frame > 95, G_Frame > 40, B_Frame > 20 , BRG_Max - BRG_Min > 15,abs(R_Frame - G_Frame) > 15, R_Frame > G_Frame, R_Frame > B_Frame]) | |
# Flashlight or daylight lateral illumination | |
Rule_2 = np.logical_and.reduce([R_Frame > 220, G_Frame > 210, B_Frame > 170, abs(R_Frame - G_Frame) <= 15, R_Frame > B_Frame, G_Frame > B_Frame]) | |
RGB_Rule = np.logical_or(Rule_1, Rule_2) | |
return RGB_Rule | |
def generate_YCbCr_mask(img): | |
YCrCb_Frame = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb) | |
Y_Frame,Cr_Frame, Cb_Frame = [YCrCb_Frame[...,YCrCb] for YCrCb in range(3)] | |
line1 = 1.5862 * Cb_Frame + 20 | |
line2 = 0.3448 * Cb_Frame + 76.2069 | |
line3 = -1.005 * Cb_Frame + 234.5652 | |
line4 = -1.15 * Cb_Frame + 301.75 | |
YCrCb_Rule = np.logical_and.reduce([line1 - Cr_Frame >= 0, | |
line2 - Cr_Frame <= 0, | |
line3 - Cr_Frame <= 0, | |
line4 - Cr_Frame >= 0]) | |
return YCrCb_Rule | |
def generate_HSV_mask(img): | |
HSV_Frame = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) | |
Hue, Sat, Val = [HSV_Frame[..., i] for i in range(3)] | |
HSV_ = np.logical_or(Hue < 50, Hue > 150) | |
return HSV_ | |
def show_mask(mask, title="Mask"): | |
mask = np.where(mask == False, 0, 255) | |
mask = mask.astype(np.uint8) | |
cv2.imshow(title, mask) | |
cv2.waitKey(0) | |
cv2.destroyAllWindows() | |
if __name__ == "__main__": | |
import glob | |
for img_file in glob.glob("test/*"): | |
print(img_file) | |
img = cv2.imread(img_file) | |
mask_RGB = generate_RGB_mask(img) | |
# show_mask(mask_RGB, "RGB Mask") | |
mask_YCbCr = generate_YCbCr_mask(img) | |
# show_mask(mask_RGB, "YCbCr Mask") | |
mask_HSV = generate_HSV_mask(img) | |
# show_mask(mask_RGB, "HSV Mask") | |
combined_mask = np.logical_and(mask_RGB, mask_YCbCr, mask_HSV) | |
show_mask(combined_mask) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment