I am applying filter. By using OpenCv live webcam is open and it detect face and apply filter. 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?
I am applying filter. By using OpenCv live webcam is open and it detect face and apply filter. 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?
The idea is to create a black mask then draw the desired region to crop out in white using cv2.circle()
. From there we can use cv2.bitwise_and()
with the original image and the mask. To crop the result, we can use cv2.boundingRect()
on the mask to obtain the ROI then use Numpy slicing to extract the result. For this example I used the center point as (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()