Dave
Dave

Reputation: 564

Remove color outside circular region of an image

I use the following code to do two tasks:

  1. Crop the circular eye.
  2. Apply the Gaussian filter.

For instance: When the input image is:

enter image description here

The code below generates:

enter image description here

As you can see, there is still a gray area outside the circular eye itself. I don't know how to remove it or turn it into white color instead of gray. Any help is appreciated.

import cv2
import numpy as np


def crop_from_gray(img):
    img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    img_mask = img_gray > 5
    check_shape = img[:, :, 0][np.ix_(img_mask.any(1), img_mask.any(0))].shape[0]
    if check_shape == 0:
        # Image is too dark, just return to crop everything
        return img
    else:
        i1 = img[:, :, 0][np.ix_(img_mask.any(1), img_mask.any(0))]
        i2 = img[:, :, 1][np.ix_(img_mask.any(1), img_mask.any(0))]
        i3 = img[:, :, 2][np.ix_(img_mask.any(1), img_mask.any(0))]
        img = np.stack([i1, i2, i3], axis=-1)
    return img


def crop_filter(img, sigma):
    img = crop_from_gray(img)
    height, width, depth = img.shape
    x = int(width / 2)
    y = int(height / 2)
    r = np.amin((x, y))

    cir_img = np.zeros((height, width), np.uint8)
    cv2.circle(cir_img, (x, y), int(r), 1, thickness=-1)
    img = cv2.bitwise_and(img, img, mask=cir_img)
    img = crop_from_gray(img)

    # Filtering
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    gau = cv2.GaussianBlur(img, (0, 0), sigma)
    img = cv2.addWeighted(img, 4, gau, -4, 128)
    return img


img = cv2.imread('path/to/image')
img = crop_filter(img, 40)  # Crop and apply filter
img = cv2.resize(img, (128, 128))  # resize
cv2.imwrite('output_filepath', img)

Upvotes: 1

Views: 162

Answers (1)

Vardan Agarwal
Vardan Agarwal

Reputation: 2181

Use your original image for this task as it is black and distinguishable. Apply cv2.thresholding with a very low threshold value and do it using cv2.THRESH_BINARY_INV.

This way the area you want to convert to white would be white in the original image and the area you want to remain the same will be black. Now apply cv2.biwise_or between them and this should do it.

If you are unable to do it let me know I'll write the complete code.

Upvotes: 2

Related Questions