如何扫描二进制图像中像素的每个水平行并获取每组黑色或白色像素的宽度

时间:2018-10-20 22:55:58

标签: python opencv barcode

示例图片:

barcode

因此,我想逐行转到水平,并获得白色或黑色像素的每个连续集的像素宽度和顺序。

想法是将每行中的数据发送到解码器,一旦解码成功,扫描将停止。有点像是要在损坏的条形码上运行激光条形码扫描仪,直到读取为止。

1 个答案:

答案 0 :(得分:1)

好的,我自己解决了这个问题:

#get height and width of image 
height, width = possible_barcode_img.shape[:2]

#prepare list for rows
barcode_rows = []

for i in range(height):

    # set variables and list for beginning of row
    white_bar_width = 0
    black_bar_width = 0
    barcode_row = []

    for j in range(width):
        if possible_barcode_img[i,j] == 0:
            #add to count
            black_bar_width = black_bar_width +1

            #ensure last bar is gotten if there was one
            if white_bar_width > 0:
                #add bar to row
                barcode_row.append(["white", white_bar_width])
                white_bar_width = 0

        elif possible_barcode_img[i,j] > 0:
            #add to width
            white_bar_width = white_bar_width +1

            #ensure last bar is gotten if there was one
            if black_bar_width > 0:
                #add bar to row
                barcode_row.append(["black", black_bar_width])
                black_bar_width = 0

    #ensure last bar is gotten since a row just finished
    if white_bar_width > 0:
        #add bar to row
        barcode_row.append(["white", white_bar_width])

    elif black_bar_width > 0:
        #add bar to row
        barcode_row.append(["black", black_bar_width])

    #add entire row to rows
    barcode_rows.append(barcode_row)

打印问题print(barcode_rows[50])中图片的第50行:

[['black', 3], ['white', 7], ['black', 4], ['white', 6], ['black', 4], ['white', 6], ['black', 13], ['white', 5], ['black', 4], ['white', 15], ['black', 4], ['white', 5], ['black', 5], ['white', 5], ['black', 13], ['white', 15], ['black', 13], ['white', 5], ['black', 13], ['white', 6], ['black', 3], ['white', 15], ['black', 5], ['white', 4], ['black', 4], ['white', 14], ['black', 13], ['white', 6], ['black', 4], ['white', 14], ['black', 13], ['white', 14], ['black', 5], ['white', 5], ['black', 4], ['white', 5], ['black', 4], ['white', 14], ['black', 4], ['white', 5], ['black', 4], ['white', 5], ['black', 13], ['white', 14], ['black', 13], ['white', 5], ['black', 14], ['white', 4], ['black', 5], ['white', 4]]
在图片中找到

50条,准备解码。

如果其他人知道更快的方法会很有帮助。