首页 > 解决方案 > OpenCV BodyPix 面具

问题描述

我正在尝试在图像上绘制蒙版,蒙版是 body-pix (在 NodeJS 中)完成处理的结果。出于性能原因,我想使用 OpenCV 来绘制蒙版,而不是 htmlcanva。

    const segmentation = await net.segmentPersonParts(img, {
        flipHorizontal: false,
        internalResolution: 'medium',
        segmentationThreshold: 0.7
    });

    //Mask into opencv Mat
    const segmentationMask = new cv.Mat(segmentation.data, segmentation.height, segmentation.width, cv.CV_8UC4);
    const mask = segmentationMask.cvtColor(cv.COLOR_BGRA2BGR);
    //Application of mask
    const result = mat.bitwiseAnd(mask);
    cv.imwrite('mask.jpg', mask);
    cv.imwrite('result.jpg', result);

这完美地工作,并实现了在检测到的人上绘制黑色蒙版(语义分割)的预期结果。但是SegmentPersonParts比方法慢得多SegmentPerson,我希望使用最后一种方法。问题是,面具不起作用。做的时候:

    const segmentation = await net.segmentPerson(img, {
        flipHorizontal: false,
        internalResolution: 'medium',
        segmentationThreshold: 0.7
    });

    //Mask into opencv Mat
    const segmentationMask = new cv.Mat(segmentation.data, segmentation.height, segmentation.width, cv.CV_8UC4);
    const mask = segmentationMask.cvtColor(cv.COLOR_BGRA2BGR);
    //Application of mask
    const result = mat.bitwiseAnd(mask);
    cv.imwrite('mask.jpg', mask);
    cv.imwrite('result.jpg', result);

结果只是一个黑色图像,因为掩码没有正确构建。我该如何解决这个问题?

标签: opencvbodypix

解决方案


我有一个脚本可以使用 OpenCV-Python 在图像中执行此操作:

import cv2

def pixelate(image):
    # Get input size
    height, width, _ = image.shape

    # Desired "pixelated" size
    h, w = (16, 16)

    # Resize image to "pixelated" size
    temp = cv2.resize(image, (w, h), interpolation=cv2.INTER_LINEAR)

    # Initialize output image
    return cv2.resize(temp, (width, height), interpolation=cv2.INTER_NEAREST)

# Load image
image = cv2.imread('1.png')

# ROI bounding box coordinates
x,y,w,h = 122,98,283,240

# Extract ROI
ROI = image[y:y+h, x:x+w]

# Pixelate ROI
pixelated_ROI = pixelate(ROI)

# Paste pixelated ROI back into original image
image[y:y+h, x:x+w] = pixelated_ROI

cv2.imshow('pixelated_ROI', pixelated_ROI)
cv2.imshow('image', image)
cv2.waitKey()

您需要获取boundingboxes坐标并在ROI.


推荐阅读