#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui_c.h>
#include<zbar.h>
using namespace cv;
using namespace std;
int main(int argc,char**argv)
{
Mat src, dst,gdst,mdst,xdst,ydst,bidst,pengdst;
src= imread("F:\\条形码.jpg", IMREAD_ANYCOLOR);
if (src.empty()) {
printf("not pitcure");
return -1;
}
imshow("input", src);
cvtColor(src, dst, CV_BGR2GRAY);//灰度图
imshow("huidutu", dst);
GaussianBlur(dst, gdst, Size(3, 3), 0);//高斯滤波
medianBlur(gdst, mdst, 3);//中值滤波
imshow("gao+zhong", mdst);
Scharr(mdst, xdst, -1, 1, 0);//
Scharr(mdst, ydst, -1, 0, 1);
imshow("x梯度图", xdst);
imshow("y梯度图", ydst);
int width = xdst.cols;
int height = ydst.rows;
Mat xydst =Mat (xdst.size(), xdst.type());
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
int xg = xdst.at<char>(row, col);
int yg = ydst.at<char>(row, col);
int xy = xg + yg;
xydst.at<char>(row, col) = xy;
}
}
imshow("final resule", xydst);
threshold(xydst,xydst,100,255,THRESH_BINARY);//二值化100分割线
Mat kernel = getStructuringElement(MORPH_RECT,Size(3,3),Point(-1,-1));
morphologyEx(xydst, bidst, MORPH_CLOSE, kernel);//闭操作
for (int i = 0; i < 3; i++) {
dilate(bidst, pengdst, kernel);
}//膨胀三次
imshow("膨胀图", pengdst);
Mat huodst;
vector<vector<Point>>contours;
vector<vector<Vec4i>>hierachy;
findContours(pengdst, contours, hierachy, CV_RETR_EXTERNAL,CHAIN_APPROX_NONE,Point(0,0));//获得轮廓
huodst = Mat::zeros(pengdst.size(), CV_8UC1);
RNG rng(12345);
for (size_t z = 0; z < contours.size(); z++) {
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(huodst, contours,z, color, 2,8, hierachy, 0,Point(0,0));//绘制图像
};
imshow("二维码",huodst);
waitKey(0);
return 0;
}