python - OpenCV 图像转换为 PIL 后无法解码二维码

标签 python opencv python-imaging-library zbar

我一直在使用 OpenCV 方法从我的相机获取图像。我想使用 zbar 库从这些图像中解码 QR 码,但是在我将图像转换为 PIL 以供 zbar 处理后,解码似乎不起作用。

import cv2.cv as cv
import zbar
from PIL import Image


cv.NamedWindow("camera", 1)

capture = cv.CaptureFromCAM(0)

while True:
    img = cv.QueryFrame(capture)
    cv.ShowImage("camera", img)
    if cv.WaitKey(10) == 27:
        break

    # create a reader
    scanner = zbar.ImageScanner()

    # configure the reader
    scanner.parse_config('enable')

    # obtain image data
    pil = Image.fromstring("L", cv.GetSize(img), img.tostring())
    width, height = pil.size
    raw = pil.tostring()

    # wrap image data
    image = zbar.Image(width, height, 'Y800', raw)

    # scan the image for barcodes
    scanner.scan(image)

    # extract results
    for symbol in image:
        # do something useful with results
        print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data


cv.DestroyAllWindows()

最佳答案

您无需将 OpenCV 图像转换为 PIL 图像即可将其与 zbar 一起使用...您可以直接从 OpenCV 图像转换为 zbar 并避免完全使用 PIL。

现在我不知道当图像源来自相机时你是怎么做到的,但是如果你从磁盘加载图像,你所要做的就是:

cv_img = cv.LoadImageM(image, cv.CV_LOAD_IMAGE_GRAYSCALE)
width = cv_img.width
height = cv_img.height
raw = cv_img.tostring()

# wrap image data
image = zbar.Image(width, height, 'Y800', raw)

# scan the image for barcodes
scanner.scan(image)

# extract results
for symbol in image:
    # do something useful with results
    print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data

看来您基本上必须执行以下操作才能使其工作:

  • 使用 LoadImageM 而不是 LoadImage
  • 确保图像是灰度的,所以使用 cv.CV_LOAD_IMAGE_GRAYSCALE

关于python - OpenCV 图像转换为 PIL 后无法解码二维码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13577302/

相关文章:

c++ - 有没有办法从一组图像中识别出不太相似的区域?

python - 对中间有数据的字符串列表进行排序

python - 基准测试 - posix-aio 与 libaio

qt - 为什么在处理 jpeg 图像时不能链接到 opencv 和 qt?

使用 OpenCV 在 Linux 上为 Windows 交叉编译 C 代码

python - 在 Python 中为形状赋值

python - qpython android IOError : [Erno 2] No such file or directory

python - 使用 PIL 通过 Python 加载、旋转和替换图像

python - 正则表达式向后匹配任何内容,直到字符串第一次出现

python - python 中的星号艺术