python识别条形码_用 Python 和 OpenCV 检测图片上的条形码(转载)
时间: 2024-05-13 17:17:14 浏览: 109
以下是用 Python 和 OpenCV 检测图片上的条形码的步骤:
1. 导入必要的库:OpenCV 和 pyzbar。
```python
import cv2
from pyzbar.pyzbar import decode
```
2. 加载图片并将其转换为灰度图像。
```python
img = cv2.imread('barcode.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
3. 使用 pyzbar 库检测图像中的条形码。
```python
barcodes = decode(gray)
```
4. 遍历检测到的条形码并在图像上绘制矩形框。
```python
for barcode in barcodes:
x, y, w, h = barcode.rect
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
```
5. 显示带有检测到的条形码的图像。
```python
cv2.imshow('Barcode Detection', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
完整代码如下:
```python
import cv2
from pyzbar.pyzbar import decode
img = cv2.imread('barcode.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
barcodes = decode(gray)
for barcode in barcodes:
x, y, w, h = barcode.rect
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow('Barcode Detection', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,pyzbar 库需要额外安装。在使用之前,请确保已安装该库。
阅读全文
相关推荐


















