再使用libdmtx的时候,发现很多比较清晰的码居然无法识别,当时感觉特别奇怪,在调试的时候发现,它是能识别到L边的,但是解码的时候失败了。
后来在使用扫码枪的时候突然看到要设置镜像码这一项,就突然明白了,libdmtx是不能识别镜像码的!!
然后我在逻辑里面随手修改了一下,如果检测到L边,依旧识别失败的话,就将码沿Y方向镜像一下,然后再来识别,发现之前不能识别的码现在都可以识别了。
参考代码:
Mat src = imread(imageName);
if(src.empty())
return -1 ;
Mat thord,gray;
cvtColor(src,gray,COLOR_BGR2GRAY);//转灰
//bitwise_not(gray,gray);
qDebug()<<"src channle"<<src.type();
//imshow("gray",gray);
threshold(gray,thord,40,255,THRESH_BINARY);//2值化
///imshow("thord",thord);
//flip(thord,thord,0);
Mat structureElement = getStructuringElement(MORPH_RECT, Size(29,29), Point(-1, -1));//13
erode(thord, thord, structureElement, Point(-1, -1), 1);//腐蚀
//dilate(thord, thord, structureElement, Point(-1, -1), 1);
imshow("last",thord);
//imwrite("E:\\korol\\CODE\\DMCode\\d.png",thord);
qDebug()<<"src channle"<<thord.type();
int pack = DmtxPack8bppK;//DmtxPack24bppRGB
DmtxImage* img = dmtxImageCreate(thord.data, thord.cols, thord.rows, pack);//DmtxPack32bppRGBX,DmtxPack24bppRGB
if (!img) {
fprintf(stderr, "dmtx image create fail\n");
return -1;
}
DmtxDecode *dec = dmtxDecodeCreate(img, 1);
DmtxRegion *reg = Q_NULLPTR;
DmtxMessage *msg = Q_NULLPTR;
DmtxTime dmtxTime;
dmtxTime.sec = 3;
reg = dmtxRegionFindNext(dec,Q_NULLPTR);
if (reg) //如果检测到存在DM码区域
{
msg = dmtxDecodeMatrixRegion(dec, reg, DmtxUndefined); //解析DM码
if (msg) //如果DM码解析成功
{
QString result = uncharToQstring(msg->output,msg->outputSize);
qDebug()<< "DataMatrix Decode Result: " << result;
qDebug()<<reg->finalPos.X<<reg->finalPos.Y<<reg->boundMax.X<<reg->boundMax.Y;
dmtxMessageDestroy(&msg);
rectangle(src,Point(reg->topLoc.X,reg->topLoc.Y),Point(reg->rightLoc.X,reg->rightLoc.Y),Scalar(0,0,255),2);
putText(src, result.toStdString(), Point(reg->topLoc.X,reg->topLoc.Y), 2, 0.5, cv::Scalar(0,255,0), 1, 2, 0);
imshow("src",src);
}
else
{
flip(thord,thord,0);
img = dmtxImageCreate(thord.data, thord.cols, thord.rows, pack);
if (!img) {
fprintf(stderr, "dmtx image create fail\n");
return -1;
}
dec = dmtxDecodeCreate(img, 1);
imshow("again",thord);
reg = dmtxRegionFindNext(dec,Q_NULLPTR);//write timeStruce Program flash back
if (reg) //如果检测到存在DM码区域
{
qDebug()<<"second reg not found";
}
msg = dmtxDecodeMatrixRegion(dec, reg, DmtxUndefined); //解析DM码
if (msg) //如果DM码解析成功
{
QString result = uncharToQstring(msg->output,msg->outputSize);
qDebug()<< "DataMatrix Decode Result: " << result;
qDebug()<<reg->finalPos.X<<reg->finalPos.Y<<reg->boundMax.X<<reg->boundMax.Y;
dmtxMessageDestroy(&msg);
rectangle(src,Point(reg->topLoc.X,reg->topLoc.Y),Point(reg->rightLoc.X,reg->rightLoc.Y),Scalar(0,0,255),2);
putText(src, result.toStdString(), Point(reg->topLoc.X,reg->topLoc.Y), 2, 0.5, cv::Scalar(0,255,0), 1, 2, 0);
imshow("src",src);
}
else
qDebug()<<"!!!!!!!!! decode failed again";
}
dmtxRegionDestroy(®);
}
else
{
qDebug()<<"not found dmCode";
}
dmtxDecodeDestroy(&dec);
dmtxImageDestroy(&img);
return 0;
如果你发现更好的方法,欢迎一起交流。