Search code examples
c++opencvimage-processingbarcode-scannerthreshold

Opencv C++ Thresholding not working after absdiff, Barcode Detection


I am trying to detect barcode from an image using OpenCv, I am using the gradient method: http://www.pyimagesearch.com/2014/11/24/detecting-barcodes-images-python-opencv/ With help from the following question: How to find the location of red region in an image using MATLAB?

Code:

Mat imgco,img,imgx,imgy,thresh;
imgco = imread("/Users/a/Desktop/barcode_01.jpg");

//### Convert image to grayscale ###
cvtColor(imgco,img,CV_BGR2GRAY);
imshow("img", img);
waitKey(0);

//### Finding horizontal and vertical gradient ###

Sobel(img,imgx,CV_16S,1,0,-1,50,0,BORDER_DEFAULT);
imgx = abs(imgx);
imshow("img", imgx);
waitKey(0);

Sobel(img,imgy,CV_16S,0,1,-1,50,0,BORDER_DEFAULT);
imgy = abs(imgy);
imshow("img", imgy);
waitKey(0);

absdiff(imgx, imgy, img);
imshow("img", img);
waitKey(0);

//### Low pass filtering ###
GaussianBlur(img, img, Size(9,9), 0);
imshow("img", img);
waitKey(0);

//### Applying Threshold ###
threshold(img,thresh,225,255,CV_THRESH_BINARY);
imshow("img", thresh);
waitKey(0);

Now the program works correctly upto gaussian blur, Somehow trying to threshold the image gives a blank output. Can anyone suggest what could be the issue?

Gaussian Output: Threshold Output:

Thank You.

UPDATE: Applying the threshold operation before AbsDiff, Results in thresholding correctly. Hence there is something related to using AbsDiff, that is messing up with thresholding. Any help?

UPDATE 2: Comparing my output with the following: http://www.pyimagesearch.com/wp-content/uploads/2014/11/barcode_gradient_and_detection.jpg I realize that I am getting a grey image while the author is getting a crisp black bacground? Even when we are performing the same operations. Thank you.


Solution

  • Okay the solution:

    1) No need to use scaling in the gradient operations.

    2) Use of convertScaleAbs method to convert the image to 8bit is necessary.

    img.convertTo(img, CV_8U, 0.00390625);
    

    Does not work. Solves the problem! :) Helped by the author of pyimage!