[英]How to crop circle image from webcam OpenCV and remove background
I am applying filter.我正在应用过滤器。 By using OpenCv live webcam is open and it detect face and apply filter.
通过使用 OpenCv 实时网络摄像头是开放的,它可以检测人脸并应用过滤器。 But i want to crop the face in circle and removed the extra background and save the image.
但是我想将脸部裁剪成圆形并删除额外的背景并保存图像。
for example:例如:
How can i implement in python?我如何在python中实现?
The idea is to create a black mask then draw the desired region to crop out in white using cv2.circle()
.这个想法是创建一个黑色蒙版,然后使用
cv2.circle()
绘制所需的区域以白色裁剪。 From there we can use cv2.bitwise_and()
with the original image and the mask.从那里我们可以将
cv2.bitwise_and()
与原始图像和掩码一起使用。 To crop the result, we can use cv2.boundingRect()
on the mask to obtain the ROI then use Numpy slicing to extract the result.为了裁剪结果,我们可以在掩码上使用
cv2.boundingRect()
来获取 ROI,然后使用 Numpy 切片来提取结果。 For this example I used the center point as (335, 245)
.在这个例子中,我使用了中心点
(335, 245)
。 You can adjust the circle radius to increase or decrease the size of the circle.您可以调整圆半径以增大或减小圆的大小。
Code代码
import cv2
import numpy as np
# Create mask and draw circle onto mask
image = cv2.imread('1.jpg')
mask = np.zeros(image.shape, dtype=np.uint8)
x,y = 335, 245
cv2.circle(mask, (x,y), 110, (255,255,255), -1)
# Bitwise-and for ROI
ROI = cv2.bitwise_and(image, mask)
# Crop mask and turn background white
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
x,y,w,h = cv2.boundingRect(mask)
result = ROI[y:y+h,x:x+w]
mask = mask[y:y+h,x:x+w]
result[mask==0] = (255,255,255)
cv2.imshow('result', result)
cv2.waitKey()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.