Skin Detection Using OpenCV in Python

In this tutorial, you will learn. How to detect human skin in the images using the OpenCV library in Python.

Installing Important Library

Install OpenCV library by fired following command. Remember that you don’t need to install NumPy it will installed by default with OpenCV

 pip install opencv-python

Python Program For Skin Detection

First, we import essential libraries to perform some actions on our image.  Numpy used for mathematical operation performed on the image whereas  cv2  used to perform basic image processing operations.

Next, we collect the maximum and minimum range of skin colour in our maxRange and minRange variable. After that, we read our image from its source(you can also pass full address like ” c:\\..\\”). Don’t forget to apply double slashes otherwise python treat as a string.

# Import all essential libraries
import cv2
import numpy as np


# minRange for min skin color Rnage
# maxRange for maximum skin color Range
minRange = np.array([0,133,77],np.uint8)
maxRange = np.array([235,173,127],np.uint8)
image = cv2.imread("imageForTest.jpg")

Now, we have to perform some operations on the image. For the better output, we convert our image from BGR to YCR format. In the next line, determine the skin area in the image using cv2.inRange() method by passing arguments  YCRimage, minRange and maxRange. Another method is cv2.bitwise_and which detect the skin from the image on a new image passing three arguments src1, src2 and skinArea.

# change our image bgr to ycr using cvtcolor() method 
YCRimage = cv2.cvtColor(image,cv2.COLOR_BGR2YCR_CB)

# apply min or max range on skin area in our image
skinArea = cv2.inRange(YCRimage,minRange,maxRange)
detectedSkin = cv2.bitwise_and(image, image, mask = skinArea)

At the last, we write our image in our system using imwrite() method by passing arguments destination(where to image store) and image source. You noticed that we use np.hstack() method which helps to concatenate our real image or detected image in a single image.

cv2.imwrite("C:\\Users\\rahul singh\\Pictures\\Pixabay\\detectedImage.png", 
            np.hstack([image,detectedSkin]))
Code :
# Import all essential libraries
import cv2
import numpy as np

# minRange for min skin color Rnage
# maxRange for maximum skin color Range
minRange = np.array([0,133,77],np.uint8)
maxRange = np.array([235,173,127],np.uint8)
image = cv2.imread("imageForTest.jpg")

# change our image bgr to ycr using cvtcolor() method 
YCRimage = cv2.cvtColor(image,cv2.COLOR_BGR2YCR_CB)

# apply min or max range on skin area in our image
skinArea = cv2.inRange(YCRimage,minRange,maxRange)
detectedSkin = cv2.bitwise_and(image, image, mask = skinArea)

cv2.imwrite("C:\\Users\\rahul singh\\Pictures\\Pixabay\\detectedImage.png", 
            np.hstack([image,detectedSkin]))

Also read: Language Detector In Python

Leave a Reply

Your email address will not be published. Required fields are marked *