基于opencv的信用卡号切割(c++)
目标:
原理图:
源码:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
Mat src = imread("E:/opencv/card_1 .jpg");
//imshow("src",src);
//灰度化
Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY);
//imshow("gray", gray);
//二值化
Mat binary;
threshold(gray, binary, 75, 255, THRESH_BINARY);
imshow("binary", binary);
Mat dst;
Mat element = getStructuringElement(MORPH_RECT, Size(9, 1), Point(-1, -1));
Mat element1 = getStructuringElement(MORPH_RECT, Size(9, 1), Point(-1, -1));
morphologyEx(~binary, dst, MORPH_DILATE, element);
//imshow("dst", dst);
morphologyEx(dst, dst, MORPH_ERODE, element1);
//imshow("dst1", dst);
//提取轮廓
vector<vector<Point>> contours;
Rect rect;
findContours(dst, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
Mat out_image = Mat::zeros(gray.size(), gray.type());
//轮廓分析
for (size_t i = 0; i < contours.size(); i++)
{
double length = arcLength(contours[i], true);
double area = contourArea(contours[i]);
if (length < 130) {
continue;
}
if (area<800)
{
continue;
}
cout << "周长 length:" << length << endl;
cout << "面积 area:" << area << endl;
rect = boundingRect(contours[i]);
cout << "rect::" << rect << endl;
cout << "圆点 x:" << rect.x << endl;
cout << "圆点 y:" << rect.y << endl;
drawContours(out_image, contours, i, Scalar(255), 2, 8);
}
// imshow("out_image", out_image);
Mat imageROI;
imageROI = src(Range((rect.y - 5), (rect.y+rect.height + 5)),Range((rect.x - 5), (rect.x +rect.width + 5)) );
imshow("imageROI", imageROI);
rectangle(src, rect, Scalar(0, 0, 255), 1, 8, 0);
imshow("result", src);
waitKey(0);
return 0;
}