首页 > 解决方案 > 检测不同背景的身份证(HSV 和 Canny 方法)

问题描述

我目前正在开展一个项目,该项目在某些方面包括卡检测。我为此实现了两种方法;一种带有 Canny 边缘检测,另一种带有在 HSV 图像上调用 inRange 函数。

康尼功能:

void DetectWithCanny(cv::Mat inputImage){
std::vector<std::vector<cv::Point>> contoursVec;
cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(13, 13));
const int lowThresh = 100;
const int ratio=3;
const int kernelSize =3;
cv::Mat detected;
 
 cv::imshow("resized", inputImage);
cv::blur(inputImage, inputImage, cv::Size(3, 3));
cv::imshow("blurred", inputImage);
cv::Canny(inputImage, detected, 100,  300 , kernelSize);
cv::imshow("canny edges", detected);
cv::morphologyEx(detected, detected, cv::MORPH_CLOSE, kernel);
cv::imshow("closed", detected);

cv::findContours(detected, contoursVec, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
contoursVec = removeContours(contoursVec); //Removes unneccesary contours.
cv::drawContours(inputImage, contoursVec, -1, cv::Scalar(0, 255, 0), 2);
cv::imshow("contours", inputImage);

cv::waitKey(0);

HSV功能:

cv::Mat detectCardHsv(cv::Mat inputImage){
cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(13, 13));
std::vector<cv::Vec4i> hierarchy;
std::vector<std::vector<cv::Point>> contoursVec;
cv::Mat resizedImage;
cv::Mat threshold; 
cv::Mat clone = inputImage.clone();
resizedImage = clone;

cv::medianBlur(resizedImage, resizedImage, 15);
cv::imshow("blurred", resizedImage);
cv::Mat hsvMap;
cv::cvtColor(resizedImage, resizedImage, cv::COLOR_BGR2HSV);
cv::Scalar lowerWhite = cv::Scalar(0,0,55);
cv::Scalar upperWhite = cv::Scalar(60,60,255);
cv::inRange(resizedImage, lowerWhite, upperWhite, hsvMap);
cv::imshow("hsv", hsvMap);
cv::threshold(hsvMap, threshold, 10, 255, 1);
cv::imshow("thresh", threshold);
cv::morphologyEx(threshold, threshold, cv::MORPH_CLOSE, kernel);
cv::imshow("closed", threshold);
cv::findContours(threshold, contoursVec, hierarchy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);
std::cout<< "Contours size before elimination: "<<contoursVec.size();
contoursVec = removeContours(contoursVec);
std::cout<< "Contours size after elimination: "<<contoursVec.size();   
cv::drawContours(clone, contoursVec, -1, cv::Scalar(255, 0, 0), 2);
return clone;

(注意:这是我的本地游乐场,仅用于测试,我知道有很多不必要或不足的变量或性能问题,它完全没问题,并且在实施时会消失。)

但是,在某些图像中;HSV 方法失败,end Canny 方法成功。在图像上尝试两种方法似乎不适合我,(即,如果 hsv 方法在一些尝试后没有给出所需的输出,则调用 canny。)我确定我在 HSV 方法中遗漏了一些东西。

这是我第一次使用色调饱和度值(HSV)通道,所以lowerBound = cv::Scalar(0, 0, 55);upperBound = cv::Scalar(60, 60, 50);是完全随机的。

我也很想只使用 HSV 图像的色调通道来实现这种检测,因为它不太依赖于光/亮度,但这是我的下一步。

有我的输入和输出图像,前两个是我的源图像。(中值模糊,内核大小为 15,因为它们是我无法提供原始图像的真实身份证。)最后两个是具有不同输入的 HSV 函数的输出。

输入带有深色背景的图像

输入带有浅色背景的图像

HSV方法的输出

Canny 方法的输出

谢谢你的帮助。保持健康,待在家里:)

标签: c++opencvimage-processingcomputer-vision

解决方案


推荐阅读