我正在尝试使用 OpenCV 2.4.5 和 Visual Studio 2010 Express 创建简单的一维条码阅读器。
到目前为止,这是我的代码:
//define Image path:
char* imageName = "D:\\Barcode Reader\\test3.jpg";
cv::Mat src = cv::imread(imageName);
if( !src.data )
{ return -1; }
//convert image to grayscale img:
cv::Mat gray_image;
cvtColor (src, gray_image, CV_BGR2GRAY);
unsigned char color;
unsigned char next_black_color = 0;
unsigned char next_white_color = 0;
int buffer[500];
float factor = (float)gray_image.cols / (float)required_width;
//start to search for pixels from left to right (in the middle of the img):
unsigned char *position = gray_image.ptr(gray_image.rows/2,0);
//iterate through the whole image length:
for (int col = 1; col <= gray_image.cols; col++)
{
//...and store the pixel value in color variable for possible output (which would be like 0-127 for black colors and 127-255 for white colors:
color = *position;
position++;
//check the pixel value ( < 127 everything bellow has dark color):
if (color < 127)
{
//...and after each position checked, go to next pixel and save the number of occurences of black pixels:
next_black_color++;
buffer[col] = next_black_color;
std::cout << col << ": " << buffer[col] << " ";
}
else
{
//set the counter variable to null for the next occurence of black pixel:
next_black_color = 0;
}
//the same goes for white pixels:
if (color > 127)
{
next_white_color++;
buffer[col] = next_white_color;
std::cout << col << ": " << buffer[col] << " ";
}
else
{
next_white_color = 0;
}
}
//show the results:
std::cout<<" Number of pixels in width = " << src.cols << std::endl <<
"Number of pixels in height = " << src.rows << std::endl;
cv::imshow("Normal Image", src);
cv::imshow("Gray Image", gray_image);
cv::waitKey(0);
return 0;
测试图像是 100x100px 图像,具有以下顺序的黑白像素(描述为二进制代码以便更好地理解:1=黑色,0=白色) 10100<..白色像素..>00101
我做这个的原因很简单...
假设我有一个 81 像素长的 UPC 条形码。但是,我加载的图像长度超过 1000 像素。
要应用检测并将加载的图像与 UPC 模式进行比较,我必须先缩放加载的图像以正确的像素值。(我使用“缩放”这个词......因为如果我只是“调整”我的图像......它会切断 919 个像素,使得检测变得不可能。)
我知道加载的图像是 UPC 模式的 12,34 因子(接近 12 ......我现在不关心正确的值......我只关心此刻的实现...... )
- 因此,为了实现缩放,我必须计算每个黑白像素的出现次数,将其保存在一个数组中,然后将其除以我的因子以获得缩放值。
使用此实现时,我面临以下问题:
事件将按以下方式存储:
____[Array]____
Position | Occurence
1 ......... 1 (First position with first black pixel)
2 ......... 1 (white)
3 ......... 1 (black)
4 ......... 1 (white pixels until next black pixel appears..)
5 ......... 2 (___Problem here!___ ... should be 94!)
6 ......... 3 .
. ......... . .
100 ....... 100(end)
但它应该是:
____[Array]____
Position | Occurence
1 ......... 1 (First position with first black pixel)
2 ......... 1 (white)
3 ......... 1 (black)
4 ......... 94 (count all white pixels until black appears again)
5 ......... 1 (black)
6 ......... 1 (white)
7 ......... 1 (black) -> end
我希望我提供答案所需的足够信息。
请帮我纠正我的代码。最好的问候 Ondrej