OpenCV Python - 设置背景颜色

时间:2015-04-22 22:32:05

标签: python opencv

我正在尝试从照片中删除灰色背景并将其替换为白色背景

到目前为止,我有这段代码:

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    result = UserManager.AddToRole(user.Id, model.Role.ToString());
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);


                    if (model.Role.ToString() == "Provider")
                    {
                        return RedirectToAction("ProviderPostRegistration", "Account");
                    }
                    else if (model.Role.ToString() == "Receiver")
                    {
                        return RedirectToAction("ReceiverPostRegistration", "Account");
                    }
                }
                AddErrors(result); 
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

问题是图像现在有黑色背景,因为我掩盖了灰色。如何用白色像素替换空像素?

Before After

5 个答案:

答案 0 :(得分:6)

您可以使用蒙版索引数组,并仅将蒙版的白色部分指定为白色:

coloured = resized.copy()
coloured[mask == 255] = (255, 255, 255)

Screenshot

答案 1 :(得分:2)

我真的建议你坚持使用OpenCV,它经过了很好的优化。诀窍是反转蒙版并将其应用到某些背景,你将获得蒙面图像和蒙面背景,然后将两者结合起来。 image1是用原始蒙版掩盖的图像,image2是用反转蒙版掩盖的背景图像,image3是组合图像。 重要。 image1,image2和image3必须具有相同的大小和类型。掩模必须是灰度的。

foreground and background masked then combined

import cv2
import numpy as np

# opencv loads the image in BGR, convert it to RGB
img = cv2.cvtColor(cv2.imread('E:\\FOTOS\\opencv\\zAJLd.jpg'),
                   cv2.COLOR_BGR2RGB)
lower_white = np.array([220, 220, 220], dtype=np.uint8)
upper_white = np.array([255, 255, 255], dtype=np.uint8)
mask = cv2.inRange(img, lower_white, upper_white)  # could also use threshold
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))  # "erase" the small white points in the resulting mask
mask = cv2.bitwise_not(mask)  # invert mask

# load background (could be an image too)
bk = np.full(img.shape, 255, dtype=np.uint8)  # white bk

# get masked foreground
fg_masked = cv2.bitwise_and(img, img, mask=mask)

# get masked background, mask must be inverted 
mask = cv2.bitwise_not(mask)
bk_masked = cv2.bitwise_and(bk, bk, mask=mask)

# combine masked foreground and masked background 
final = cv2.bitwise_or(fg_masked, bk_masked)
mask = cv2.bitwise_not(mask)  # revert mask to original

答案 2 :(得分:2)

首先,您需要获得背景信息。必须使用蒙版图像从原始图像中减去此值。然后将黑色背景更改为白色(或任何颜色)。然后回来添加面具的图像。 看这里OpenCV grabcut() background color and Contour in Python

答案 3 :(得分:1)

首先转换为灰色,然后使用cv2.threshold进行阈值处理,然后使用numpy masking ...

ret, thresh = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 220, 255, cv2.THRESH_BINARY)
img[thresh == 255] = 255

如果需要黑色背景,请将RHS设置为零而不是255

答案 4 :(得分:0)

我会使用

而不是使用bitwise_not
resized.setTo([255, 255, 255], mask)

在此之前,我还会侵蚀和扩张面具,以摆脱面具中您想要保留的图像的规格。 http://docs.opencv.org/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html