OpenCV中感兴趣区域的模糊处理

3

我正在尝试在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)

{btsdaf} - api55
{btsdaf} - Pulkit
{btsdaf} - Pulkit
{btsdaf} - api55
{btsdaf} - Pulkit
{btsdaf} - api55
1个回答

12

要使其工作,您需要做几件事情。首先,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)

同样的方法,您可以将其更改为矩形、多边形或任何其他形状。


{btsdaf} - Pulkit
{btsdaf} - Pulkit
{btsdaf} - Pulkit
{btsdaf} - api55
{btsdaf} - api55
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接