来自OpenCV感兴趣区域的模糊

时间:2017-10-23 06:33:23

标签: python numpy opencv

我正在尝试创建一个圆圈并模糊OpenCV中的内容。但是,我能够制作圆圈,但我无法模糊那一部分。我的代码如下。请帮帮我

import io
import picamera
import cv2
import numpy as np
import glob
from time import sleep
from PIL import ImageFilter


image = cv2.imread('/home/pi/Desktop/cricle-test/output_0020.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faceCascade = cv2.CascadeClassifier('/home/pi/Desktop/Image-Detection-test/haarcascade_frontalface_alt.xml')

faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.2,
    minNeighbors=5,
    minSize=(30, 30),
    flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)
print "Found {0} faces!".format(len(faces))

# Draw a circle around the faces and blur
for (x, y, w, h) in faces:

    sub = cv2.circle(image, ( int((x + x + w )/2), int((y + y + h)/2 )), int (h / 2), (0, 255, 0), 5)
    cv2.blur(image(x,y,w,h),(23,23), 40000)
    cv2.imwrite("/home/pi/Desktop/cricle-test/output_0020.jpg" ,image)

1 个答案:

答案 0 :(得分:8)

要使它工作,你需要做一些事情,首先cv2.blur需要目的地而不是数字。这可以通过以下方式实现:

image[y:y+h, x:x+w] = cv2.blur(image[y:y+h, x:x+w] ,(23,23))

由于您在每个循环中将图像保存到同一文件,因此您可以在循环后将其保存。

由于你需要一个圆形刻录,你需要创建一个圆形蒙版,然后将它应用到图像,这是你的代码的样子(只有循环部分):

# create a temp image and a mask to work on
tempImg = image.copy()
maskShape = (image.shape[0], image.shape[1], 1)
mask = np.full(maskShape, 0, dtype=np.uint8)
# start the face loop
for (x, y, w, h) in faces:
  #blur first so that the circle is not blurred
  tempImg [y:y+h, x:x+w] = cv2.blur(tempImg [y:y+h, x:x+w] ,(23,23))
  # create the circle in the mask and in the tempImg, notice the one in the mask is full
  cv2.circle(tempImg , ( int((x + x + w )/2), int((y + y + h)/2 )), int (h / 2), (0, 255, 0), 5)
  cv2.circle(mask , ( int((x + x + w )/2), int((y + y + h)/2 )), int (h / 2), (255), -1)

# oustide of the loop, apply the mask and save
mask_inv = cv2.bitwise_not(mask)
img1_bg = cv2.bitwise_and(image,image,mask = mask_inv)
img2_fg = cv2.bitwise_and(tempImg,tempImg,mask = mask)
dst = cv2.add(img1_bg,img2_fg)

cv2.imwrite("/home/pi/Desktop/cricle-test/output_0020.jpg" ,dst)

这似乎有效,至少在我的测试中,你可以尝试调整内核大小(模糊中的这个(23,23))以获得更少或更多模糊的图像,例如,尝试使用(7, 7)它将有更多细节。

更新

如果您想使用省略号而不是圆圈,只需将圆圈指令更改为:

cv2.ellipse(mask , ( ( int((x + x + w )/2), int((y + y + h)/2 )),(w,h), 0), 255, -1)

您可以将其更改为矩形,多边形或任何其他形状。