首页 > 解决方案 > 只显示边界框区域而忽略其他部分

问题描述

我有这个 haarcascade 代码,它检测面部并在其周围绘制边界框。我只想在原始图像的原始位置显示边界框区域,并将所有其他部分涂黑,就像我们在 opencv 的颜色检测中所做的那样。有什么办法吗?

cascPath = "haarcascade_frontalface_default.xml"
image = cv2.imread(imagePath)

faceCascade = cv2.CascadeClassifier(cascPath)


gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
=
faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30),
    flags = cv2.CASCADE_SCALE_IMAGE
)

print("Found {0} faces!".format(len(faces)))

for ((x, y, w, h),i) in zip(faces,range(len(faces))):
    a=cv2.rectangle(image, (x, y), (x+w, y+h), 2)
    roi_color=image[y:y+h, x:x+w]

标签: python-3.xopencv

解决方案


我会尝试裁剪 ROI,然后将其放入一个全黑矩形的 img 中。在Pillow中,这很容易做到。

因为我没有面部图像,所以很难重现您的代码。我将使用一些随机图像,但它应该看起来像这样:

我放蓝色只是为了突出背景,但只需将其更改为您想要的任何颜色即可

from PIL import Image
img = Image.open('watch.jpeg', 'r')
img_w, img_h = img.size


left = img_w/8
top = img_h/8
right = 3 * img_w/8
bottom = 3 * img_h/8
cropped_img = img.crop((left, top, right, bottom))
cropped_img.save("cropped.png")
background = Image.new('RGB', (1440, 900), (0, 0, 255))
bg_w, bg_h = background.size
offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)
background.paste(cropped_img, offset)
background.save('out.png')

输入图像

在此处输入图像描述

输出图像在此处输入图像描述


推荐阅读