2

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:

enter image description here

to this enter image description here

How can i implement in python?

nathancy
  • 42,661
  • 14
  • 115
  • 137
Maryam Anwer
  • 43
  • 1
  • 9
  • 2
    Welcome to StackOverflow. This site does not serve as general problem solving portal. The community will help you to get a working solution, but you should share your code with images showing what you have done already that did not work. Read "How to create a Minimal, Reproducible Example" (https://stackoverflow.com/help/minimal-reproducible-example), "What are good topics" (https://stackoverflow.com/help/on-topic) and "How do I ask a good question" (https://stackoverflow.com/help/how-to-ask)? Please identify what data you have for the location and size of the face, so we can show cropping – fmw42 Feb 07 '20 at 18:05
  • 2
    If you have the center coordinates you can do this [How to create a circular thumbnail using python pillow and overlap on background image](https://stackoverflow.com/questions/42991713/how-to-create-a-circular-thumbnail-using-python-pillow-and-overlap-on-background) or this [cropping an image in a circular way, using python](https://stackoverflow.com/questions/51486297/cropping-an-image-in-a-circular-way-using-python) – Daniel Anton Feb 07 '20 at 18:08
  • 1
    See also: [How can I create a circular mask for a numpy array?](https://stackoverflow.com/questions/44865023/circular-masking-an-image-in-python-using-numpy-arrays) – alkasm Feb 07 '20 at 21:35

1 Answers1

3

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.

enter image description here

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()
nathancy
  • 42,661
  • 14
  • 115
  • 137