您的位置:首页 > 编程语言 > Python开发

Detecting Skin in Images & Video Using Python and OpenCV皮肤检测

2017-08-20 18:58 531 查看

简介

使用video或者摄像头,检测皮肤区域,我们可以获得区域内的皮肤图像。

skindetector.py

# import the necessary packages
from pyimagesearch import imutils
import numpy as np
import argparse
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video",
help = "path to the (optional) video file")
args = vars(ap.parse_args())

# define the upper and lower boundaries of the HSV pixel
# intensities to be considered 'skin'
lower = np.array([0, 48, 80], dtype = "uint8")
upper = np.array([20, 255, 255], dtype = "uint8")


这里,我们定义了HSV的颜色空间,最低为[0, 48, 80],最高为[20, 255, 255],注意不是RGB的。

选择的设备或video

# if a video path was not supplied, grab the reference
# to the gray
if not args.get("video", False):
camera = cv2.VideoCapture(0)

# otherwise, load the video
else:
camera = cv2.VideoCapture(args["video"])


在第20行有“–video”表示选择用video做检测,如果使用cv2.VideoCapture=0的参数,表示采用了摄像头设备。

开始读取每一帧图像

# keep looping over the frames in the video
while True:
# grab the current frame
(grabbed, frame) = camera.read()

# if we are viewing a video and we did not grab a
# frame, then we have reached the end of the video
if args.get("video") and not grabbed:
break

# resize the frame, convert it to the HSV color space,
# and determine the HSV pixel intensities that fall into
# the speicifed upper and lower boundaries
frame = imutils.resize(frame, width = 400)
converted = cv2.cvtColor(frame, 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(frame, frame, mask = skinMask)

# show the skin in the image along with the mask
cv2.imshow("images", np.hstack([frame, skin]))

# if the 'q' key is pressed, stop the loop
if cv2.waitKey(1) & 0xFF == ord("q"):
break

# cleanup the camera and close any open windows
camera.release()
cv2.destroyAllWindows()


camera.read() 函数 返回的是元组数据格式,包含两个变量 grabbed 和 frame . grabbed是boolean逻辑值,表示是否读取到最后结束了,表明当前这一帧图像是否成功读取。imutils.resize是将当前帧图片在不压缩的情况下,缩小到width = 400。GaussianBlur进行了高斯滤波,cv2.erode与cv2.dilate是腐蚀与膨胀操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐