c++ - 如何在 dlib 的 array2d<rgb_pixel> 图像上从 dlib::rectangle 创建 cv::Mat?

标签 c++ opencv dlib

我使用 dlib 的 hog 检测器,因为它发现人脸比 opencv haarcascades 好得多。但它无法检测脸上的情绪(或者可以???)。我需要从带有面部的 dlib::rectangle 中提取一个“子图像”,并从中创建 cv::Mat 以使用预加载的“haarcascade_smile.xml”调用 c​​v::detectMultiScale()。

如何执行此提取/转换?

下面的代码示例...

int DetectionProc(void * param){ // async operation
    auto instance =(Detector *)param;
    const unsigned int delay = 1000 / instance->OPS;
    std::vector<dlib::rectangle> detects;
    array2d<rgb_pixel> sample;

    while(instance->OPS){
        unsigned int elapsed = GetTickCount();

        EnterCriticalSection(&instance->cs_buf);
        assign_image(sample,instance->buffer);
        instance->buffer.clear();
        LeaveCriticalSection(&instance->cs_buf);

        if (sample.size()){
            detects = instance->face_detector(sample);
            if (!detects.empty()){
                detection res(GetTickCount());
                if (!instance->smile_detector.empty()){
                    // TODO
                    // extract subimage from detects.front() on sample to cv::Mat face;
                    // instance->smile_detector.detectMultiScale(); on face
                    // set res.smiled to true on success
                }
                EnterCriticalSection(&instance->cs_result);
                instance->result = res;
                LeaveCriticalSection(&instance->cs_result);
            }
        }
        elapsed = GetTickCount() - elapsed;
        Sleep((elapsed < delay) ? (delay - elapsed) : 0);
    }
    return 0;
}

最佳答案

有两种方法可以实现这一点,要么通过 extract_image_chips dlib 中的功能(docs)或通过从包装中提取子图像 cv::Mat使用相应的 OpenCV API。您将使用哪一个取决于选择对其余处理管道的方便程度。

从您的样本得出结论,OpenCV 路径似乎是最方便的(但再次请检查设计和 API 选项):

// 1.) Wrap your "sample" dlib-image in cv::Mat
//     dlib::toMat() is available through #include <dlib/opencv.h>
cv::Mat sample_mat = dlib::toMat(sample);

// 2.) Iterate through your detections
for (const auto& rect: detects) 
{
    // 3.) Extract the rectangle sub-image using OpenCV
    cv::Mat rect_sub = sample_mat(
        cv::Rect(rect.left(), rect.top(), rect.width(), rect.height()));

    // 4.) Process the sub-image
}

关于c++ - 如何在 dlib 的 array2d<rgb_pixel> 图像上从 dlib::rectangle 创建 cv::Mat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57595274/

相关文章:

c# - opencv_imgproc.dll 抛出 BadImageFormatException

python - 为什么我的 dlib.get_frontal_face_detector() 的输出(矩形[])是空的?

c++ - 在 dlib 图像中写入文本

c++ - 倒排索引 : Find a phrase in a set of documents

c++ - 分析波头

c++ - 如何打印数字列表,输出格式根据输入而不同?

python - 使用 opencv 在数字和单词周围放置边界框

c++ - 字符数组中的奇怪字符

opencv - 将 Cv::Mat 的数据存储在 std::vector 中

c++ - Qt Windows 上的 dlib。程序意外结束