matlab - 在Matlab中计算条形码每条的宽度

标签 matlab image-processing barcode

我有一个条形码,我想在 matlab 中处理它并计算一维条形码中每个条的宽度(以像素为单位)。

我已经尝试通过灰度阈值将图像转换为灰度,并将其也转换为二进制。

%read the image code3
barz=imread('barcode1.jpg');
grayBarz=rgb2gray(barz);

binImage = imbinarize(barz,graythresh(barz));

s = regionprops(binImage == 0,'Area','PixelIdxList');
imshow(barz);

我想要条形码中每个条的宽度(以像素为单位)。

Barcode Image

最佳答案

有时不需要完整的图像处理工具箱就能做事很有趣。

下面的解决方案允许您计算每个黑条的像素宽度,而不需要任何额外的工具箱:

%% Read the image
barz=imread('barcode.jpg');
grayBarz=rgb2gray(barz);

%% Extract an horizontal line in the middle
sz = size(grayBarz) ;
idxMidLine = round(sz(1)/2) ; % index of a line roughly in the middle
eline = grayBarz(idxMidLine,:) ;    % extract a line
eline(eline<128) = 0 ;              % sharpen transitions
eline = ~logical(eline) ;           % convert to logical (0=white / 1=black)

%% Now count the pixels
npts = numel(eline) ;   % number of points in the line

% Find every transition:
    % high to low   => -1
    % no change     =>  0
    % low to high   => +1
idd = find( diff(eline) ) ;

% this contain the start and end indices of every interval
ddd = [ 1 , idd ; ...
        idd , npts ] ;

% This contains the width of every bar (white and black),
% in order from left to right
barWidth = diff(ddd) ;

if ~eline(1)
    % The first interval is 0 (is white)
    pixBarWhite = barWidth( 1:2:end ) ;
    pixBarBlack = barWidth( 2:2:end ) ;
else
    % The first interval is 1 (is black)
    pixBarBlack = barWidth( 1:2:end ) ;
    pixBarWhite = barWidth( 2:2:end ) ;
end

nBarWhite = numel(pixBarWhite) ;
nBarBlack = numel(pixBarBlack) ;

%% Display results
fprintf('Found a total of %d black pixels along the horizontal,\n',sum(pixBarBlack))
fprintf('spread over %d black bars,\n',nBarBlack)
fprintf('Individual bar pixel thickness:\n')
for k=1:nBarBlack
    fprintf('Bar %02d : Thickness: %02d pixels\n',k,pixBarBlack(k))
end

对于您的图片,它将返回:

Found a total of 599 black pixels along the horizontal,
spread over 49 black bars,
Individual bar pixel thinchness:,
Bar 01 : Thickness: 13 pixels
Bar 02 : Thickness: 07 pixels
Bar 03 : Thickness: 20 pixels
% [edited to keep it short]
Bar 47 : Thickness: 20 pixels
Bar 48 : Thickness: 07 pixels
Bar 49 : Thickness: 13 pixels

请注意,变量 pixBarWhite 还包含黑条之间所有白色间隔的像素厚度。以后可能会派上用场...

关于matlab - 在Matlab中计算条形码每条的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58389961/

相关文章:

python - 在这种情况下进行直方图比较是否安全?

javascript - 将带有 ASCII 控制字符的条形码扫描到输入字段中

matlab - 如何设置绘图的不透明度?

arrays - 如何从两个向量元素的所有可能组合中获取单个数组?

matlab - 允许在没有管理员权限的情况下安装 MCR 的最新 Matlab 版本是哪个?

image-processing - 如何判断图片中最明显的物体是否是形状?

c# - 用白色替换黑色区域

java - 从 Swing 中的条形码扫描仪读取

java - Java 中的条形码图像

matlab - 在 MATLAB 中使用多重计算优化三个嵌套循环