python - 在opencv python中创建一个掩码并删除内部轮廓
问题描述
这是我从代码中得到的结果: 在此处输入图像描述
正如我在代码中显示的那样,我已经使用轮廓在我的脸上制作了这个面具。
该项目的最终结果是删除人脸并显示背景我尚未定义的背景。
我的问题是:有没有办法用这个计数器制作一个面具,所以我可以使用这样的东西cv2.imshow('My Image',cmb(foreground,background,mask))
来显示背景面具下的前景?(这里的问题是我必须将掩码作为这种形式的视频,但我希望它是实时的)
或者可能是另一种方式,我可以以某种方式删除我的计数器中(或下方)的帧像素吗?
这是我的代码:
from imutils.video import VideoStream
from imutils import face_utils
import datetime
import argparse
import imutils
import time
import dlib
import cv2
import numpy as np
# path to facial landmark predictor
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--shape-predictor", required=True)
print("[INFO] loading facial landmark predictor...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(args["shape_predictor"])
# grab the indexes of the facial landmarks
(lebStart, lebEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eyebrow"]
(rebStart, rebEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eyebrow"]
(jawStart, jawEnd) = face_utils.FACIAL_LANDMARKS_IDXS["jaw"]
# initialize the video stream and allow the cammera sensor to warmup
print("[INFO] camera sensor warming up...")
vs = VideoStream(usePiCamera=args["picamera"] > 0).start()
time.sleep(2.0)
# loop over the frames from the video stream
while True:
# grab the frame from the threaded video stream, resize it to
# have a maximum width of 400 pixels, and convert it to
# grayscale
frame = vs.read()
frame = imutils.resize(frame, width=400)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# detect faces in the grayscale frame
rects = detector(gray, 0)
# loop over the face detections
for rect in rects:
shape = predictor(gray, rect)
shape = face_utils.shape_to_np(shape)
# extract the face coordinates, then use the
faceline = shape[jawStart:lebEnd]
# compute the convex hull for face, then
# visualize each of the face
facelineHull = cv2.convexHull(faceline)
mask = np.zeros(frame.shape,dtype='uint8')
cv2.drawContours(frame, [facelineHull], -1, (0, 0, 0),thickness=cv2.FILLED)
cv2.drawContours(frame, [facelineHull], -1, (0, 255, 0))
# show the frame
cv2.imshow("Frame", frame)
# cv2.imshow("Frame", mask)
key = cv2.waitKey(1) & 0xFF
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
# do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()
解决方案
假设您的掩码是二进制掩码,您可以执行以下操作:
def cmb(foreground,background,mask):
result = background.copy()
result[mask] = foreground[mask]
return result
我没有测试这段代码,但我希望这个想法能得到解决。您将蒙版反转为背景,将蒙版单独保留为前景。你把它应用到每一帧,瞧,你有你的蒙版图像。
编辑:根据评论调整代码。当然,这个解决方案比我最初写的要清楚得多。不过,功能保持不变。
推荐阅读
- ms-access - 访问宏 IsNull 多个变量
- reactjs - 电子包装器产生 ENOTDIR
- docker - 无法从远程主机访问 Dockerized NiFi UI
- excel - 从已关闭的 Excel 工作簿中读取数据
- svg - 中心轴上的 SVG 旋转
- java - Google Cloud Vision API 在应用引擎中使用时挂起
- intellij-idea - 有没有办法在 IntelliJ Idea 中导入谷歌脚本库?
- python - pyqt5不显示窗口
- python - python中的交叉过滤器
- xamarin.forms - Xamarin.forms - 自定义 ViewCell 中的 BoxView