# This Python code uses OpenCV to create a circular disk at the centre of an # image. The radius of the disk is the minimum of width and height of image. #-------------- ----------------- ---------------- ----------------- ---------- # References: # stackoverflow.com/.../how-to-use-opencv-to-crop-circular-image # stackoverflow.com/.../what-does-bitwise-and-operator-exactly-do-in-opencv import numpy as np import cv2 image = 'image.png' out = 'maskedImg.png' # Read image as coloured channels: w x h x 3 uint8 img = cv2.imread(image) # Create white but coloured image that is with 3 channels: w x h x 3 uint8 mask_w = np.full_like(img, fill_value=(255,255,255)) # Get height and width of the image, define centre and radius of the disk h = img.shape[0] w = img.shape[1] centre = (w//2, h//2) #Note 'Centre' is ordered in image coordinate system radius = min(centre) # Create black but coloured image that is with 3 channels: w x h x 3 uint8 mask_b = np.zeros_like (img[:,:], dtype='uint8') # Create a white disk at the centre of the black image created in previous step img_x = cv2.circle(mask_b, centre, radius, [255]*3, thickness=cv2.FILLED) cv2.imwrite("maskIntermediate1.png", img_x) # Create white image with single channels: w x h x 0 uint8. This is the mask, # note that mask has to be 8-bit single channel array. Image created next is # same as previous image (img_x) except it has single channel. mask_b_1_chan = img_x[:,:,0] # Extract pixels disk using white disk single channel. This will result in a # black image with cropped disk at the centre. This is the desired image but # with black background beyond circular disk at the centre masked = cv2.bitwise_and(img, mask_w, mask=mask_b_1_chan) cv2.imwrite("maskIntermediate2.png", masked) # Invert the black mask to white mask: image with white background and black # disk at the centre mask_b_inv = ~mask_b # Add white background to the original image. Note that with bitwise_or: # white + anycolour = white, black + anycolour = anycolour result = cv2.bitwise_or(img, mask_b_inv) # Save the output image cv2.imwrite(out, result)