Kyle
Kyle

Reputation: 793

Remove Mask from Image OpenCV Python

I may be overshooting a bit but I'm trying to use a mask generated from my image and subtract it from the main image. I'm quite open to instead extracting the characters but am not sure how to collect the entire blue sample, I haven't that correct balance yet.

The page here demonstrates the inverse of what I'm trying to achieve.

Base image

enter image description here

The mask utilizing hsv bounds then inverting it to show it better

enter image description here

Darkening it

I wish to now take that mask and remove it from the main image.

import cv2
import numpy as np
import random as rng

from PIL import Image
from PIL import ImageOps
from utils import helper

image_name = 'capt13.jpg'

img = cv2.imread(image_name)

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower_red = np.array([0,120,70]) 
upper_red = np.array([10,255,255]) 
lower_mask = cv2.inRange(hsv, lower_red, upper_red) 

lower_red = np.array([160,120,70]) 
upper_red = np.array([180,255,255]) 
upper_mask = cv2.inRange(hsv, lower_red, upper_red) 
'''
lower_blue = np.array([80,40,30]) 
upper_blue = np.array([140,255,255]) 
lower_mask = cv2.inRange(hsv, lower_blue, upper_blue) 

lower_blue = np.array([240,220,200]) 
upper_blue = np.array([360,255,255]) 
upper_mask = cv2.inRange(hsv, lower_blue, upper_blue) 
'''
mask = lower_mask + upper_mask

res_lines = cv2.bitwise_and(img,img, mask= mask) 

# Keep the inverted
image = Image.fromarray(res_lines)
image.save('res.png')
inverted = ImageOps.invert(image)
inverted = inverted.convert('L')
inverted.save('inverted.png')

binary = np.array(inverted)
for row in range(len(binary)):
    for col in range(len(binary[row])):
        if binary[row][col] != 255:
            binary[row][col] = 0
binary_image = Image.fromarray(binary)
binary_image.save('binary.png')

Extracting the Blue (As stated above that I'm open to a better solution for this)

The mask utilizing hsv bounds then inverted it

enter image description here

Darkening it

enter image description here

Upvotes: 0

Views: 10146

Answers (1)

Salvatore
Salvatore

Reputation: 12094

Straight subtraction works, provided both images are the same size:

im = cv2.imread("image.png")
mask = cv2.imread("mask.png")

diff_im = im - im2

Alternatively, you can use OpenCV's built in subtract, which does an element-wise subtraction:

diff_im = cv2.subtract(im, im2)

As a final thought, you should also try absdiff, as it will convert negative results to zeroes, which may be what you want.

diff_im = cv2.absdiff(im, im2)

Upvotes: 2

Related Questions