python-3.x - 只显示边界框区域而忽略其他部分
问题描述
我有这个 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]
解决方案
我会尝试裁剪 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')
输入图像:
推荐阅读
- proxy - 编译 bazel,但主机在 SQUID 代理后面
- android - AppsFlyer 与 ProGuard 一起使用时构建失败
- docker - Docker 使用 flink socketwordcount 示例 [apache-flink]
- kubernetes - CronJob pod 状态为 ImagePullBackOff
- c# - 从属性读取意外的 StackOverflowException
- mysql - 年初至今计算
- autofac - Autofac的JSON配置中同一个接口的两种实现
- reactjs - React + Typescript 问题与“......不可分配给类型'IntrinsicAttributes & RefAttributes
’。” - javascript - 寻找子字符串替代javascript
- angular - Angular 6-将数据从模板传递到控制器的最佳方式?