简体   繁体   English

从图像 OpenCV Python 中删除蒙版

[英]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基本图像

在此处输入图片说明

The mask utilizing hsv bounds then inverting it to show it better利用 hsv 边界的掩码然后反转它以更好地显示它

在此处输入图片说明

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使用 hsv 边界的掩码然后反转它

在此处输入图片说明

Darkening it变暗

在此处输入图片说明

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:或者,您可以使用 OpenCV 的内置减法,它执行逐元素减法:

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.最后,您还应该尝试absdiff ,因为它将负结果转换为零,这可能是您想要的。

diff_im = cv2.absdiff(im, im2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM