模糊图像的特定部分

时间:2018-09-17 10:01:21

标签: python opencv tensorflow image-processing scipy

我有一张图片。像这样:

enter image description here

我检测到一个主体(在这种情况下是一个人),并掩盖了这样的图像:

enter image description here

我希望主体的背景模糊。像这样:

enter image description here

下面是我尝试过的代码。以下代码只会模糊

import cv2
import numpy as np
from matplotlib import pyplot as plt
import os


path = 'selfies\\'
selfImgs = os.listdir(path)


for image in selfImgs:

    img = cv2.imread(path+image)
    img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    blur = cv2.blur(img,(10,10))
    #canny = cv2.Canny(blur, 10, 30)

    #plt.imshow(canny)
    plt.imshow(blur)

    j=cv2.cvtColor(blur, cv2.COLOR_BGR2RGB)
    print(image)
    cv2.imwrite('blurred\\'+image+".jpg",j)

有什么方法可以仅模糊图像的特定部分。

该项目基于https://github.com/matterport/Mask_RCNN

如果需要,我可以提供更多信息。

我在numpy中有一种方法:-

final_image = original * mask + blurred * (1-mask)

2 个答案:

答案 0 :(得分:6)

您可以使用Join方法选择想要模糊值的像素,然后将其替换为:

np.where()

enter image description here

答案 1 :(得分:2)

ZdaR说:

import cv2
import numpy as np

img = cv2.imread("/home/user/Downloads/lena.png")
blurred_img = cv2.GaussianBlur(img, (21, 21), 0)

mask = np.zeros((512, 512, 3), dtype=np.uint8)
mask = cv2.circle(mask, (258, 258), 100, np.array([255, 255, 255]), -1)

out = np.where(mask==np.array([255, 255, 255]), img, blurred_img)

cv2.imwrite("./out.png", out)

这是个好主意,但我遇到了与penta相同的错误:

@ZdaR,我收到TypeError:参数'color'的标量值不是数字

简单的解决方案是在创建Circle时修改颜色值:

mask = cv2.circle(mask, (258, 258), 100, (255, 255,255), -1)

只需将np,array([255,255,255])更改为(255,255,255)