Robert Axe
Robert Axe

Reputation: 404

How to blackout area outside circle with OpenCV Python?

I have an image and I am trying to black out all the area that is outside the circle with opencv.

Source image

Goal image

Upvotes: 3

Views: 5320

Answers (1)

fmw42
fmw42

Reputation: 53081

Here is one way in Python/OpenCV.

  • Read the input
  • Get the dimensions and divide by 2 to use a center and radius
  • Create a filled white circle on a black background as a mask
  • Apply the mask to the image
  • Save the results

Input:

enter image description here

import cv2
import numpy as np

# read image
img = cv2.imread('jeep.jpg')
hh, ww = img.shape[:2]
hh2 = hh // 2
ww2 = ww // 2

# define circles
radius = hh2
yc = hh2
xc = ww2

# draw filled circle in white on black background as mask
mask = np.zeros_like(img)
mask = cv2.circle(mask, (xc,yc), radius, (255,255,255), -1)

# apply mask to image
result = cv2.bitwise_and(img, mask)

# save results
cv2.imwrite('jeep_mask.png', mask)
cv2.imwrite('jeep_masked.png', result)

cv2.imshow('image', img)
cv2.imshow('mask', mask)
cv2.imshow('masked image', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Mask Image:

enter image description here

Result Image:

enter image description here

Upvotes: 7

Related Questions