OpenCV-Python Development Guide (9) ---HSV marking skin color and achieving artistic effects

Mark skin tone

Earlier, we extracted the effective red area on the picture by marking the red on the H channel. So in the same way, we can limit the range of skin color and extract the face to achieve the effect of matting.

First of all, skin color should not only pay attention to the H channel, but also the S channel. Therefore, we first need to introduce a function: split(), defined as follows:

img = cv2.imread("4.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)

As shown in the code above, we can use the cv2.splite() function to get the values ​​of all channels on the HSV image.

First of all, we assume that the approximate range of human skin color, its hue is between [5,170], and its saturation is between [25,166]. In this way, we can obtain images within a limited range according to the content of the previous section, the code is as follows:

import cv2

img = cv2.imread("4.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
hmask=cv2.inRange(h,5,170)
smask=cv2.inRange(s,25,166)
mask=hmask & smask
result=cv2.bitwise_and(img,img,mask=mask)
cv2.imshow("img",img)
cv2.imshow("result", result)
cv2.waitKey()
cv2.destroyAllWindows()

After running, as long as the image is similar to the skin color, it will be extracted, and the other parts will become black.
1

Achieve artistic effects

Earlier, we introduced the application of various HS channels, and there has been no single or emphasis on the importance of V. Here, let's use the value of the V channel to achieve some interesting artistic effects.

import cv2

img = cv2.imread("9.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
v[:,:]=255
newHSV=cv2.merge([h,s,v])
result=cv2.cvtColor(newHSV,cv2.COLOR_HSV2BGR)
cv2.imshow("img",img)
cv2.imshow("result", result)
cv2.waitKey()
cv2.destroyAllWindows()

After running, it feels a bit non-mainstream.
non-mainstream

Guess you like

Origin blog.csdn.net/liyuanjinglyj/article/details/113796117