这是一个结合智能视觉技术的图书馆书籍归位辅助工具代码实现,采用模块化设计,包含图像采集、OCR识别、封面匹配、位置映射等核心功能。
代码实现(Python 3.8+)
import cv2
import pytesseract
import numpy as np
from PIL import Image
import os
import json
# 配置Tesseract路径(需先安装Tesseract OCR引擎)
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' # Windows示例路径,Linux/macOS需调整
class BookRecognizer:
"""书籍识别模块:OCR识别编号+封面图像匹配"""
def __init__(self, cover_db_path='covers_db'):
self.cover_db = self._load_cover_db(cover_db_path) # 加载封面数据库
def _load_cover_db(self, db_path):
"""加载封面样本库(键:书籍编号,值:封面图像路径)"""
db = {}
for file in os.listdir(db_path):
if file.endswith(('.jpg', '.png')):
book_id = os.path.splitext(file)[0] # 假设文件名即编号
db[book_id] = os.path.join(db_path, file)
return db
def ocr_book_id(self, img):
"""OCR识别书籍编号(假设编号为图像中清晰数字)"""
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
text = pytesseract.image_to_string(thresh, config='--psm 6 outputbase digits')
return ''.join(filter(str.isdigit, text)) # 提取纯数字编号
def match_cover(self, img):
"""封面图像匹配(SIFT特征点匹配)"""
sift = cv2.SIFT_create()
kp_img, des_img = sift.detectAndCompute(img, None)
best_match_id = None
max_good = 0
for book_id, cover_path in self.cover_db.items():
cover = cv2.imread(cover_path, cv2.IMREAD_GRAYSCALE)
kp_cover, des_cover = sift.detectAndCompute(cover, None)
if des_cover is None or des_img is None:
continue
# FLANN匹配器
flann = cv2.FlannBasedMatcher({'algorithm': 1, 'trees': 5}, {'checks': 50})
matches = flann.knnMatch(des_img, des_cover, k=2)
# 筛选优质匹配点
good = [m for m, n in matches if m.distance < 0.7 * n.distance]
if len(good) > max_good:
max_good = len(good)
best_match_id = book_id
return best_match_id if max_good > 10 else None # 匹配阈值设为10个特征点
class LocationMapper:
"""书架位置映射模块(编号→位置)"""
def __init__(self, map_file='location_map.json'):
with open(map_file, 'r') as f:
self.map = json.load(f) # 加载JSON映射表
def get_location(self, book_id):
"""查询书籍位置"""
return self.map.get(book_id, "未找到该书籍位置记录")
def capture_image(source=0):
"""图像采集(摄像头/本地文件)"""
if isinstance(source, int): # 摄像头
cap = cv2.VideoCapture(source)
ret, frame = cap.read()
cap.release()
return frame if ret else None
else: # 本地文件
return cv2.imread(source)
def main():
# 初始化模块
recognizer = BookRecognizer()
mapper = LocationMapper()
# 采集图像(示例:调用摄像头)
print("正在启动摄像头...(按Q退出)")
img = capture_image() # 实际使用时可改为capture_image('test_book.jpg')读取本地图
if img is None:
print("图像采集失败")
return
# 识别书籍编号(优先OCR,失败则用封面匹配)
book_id = recognizer.ocr_book_id(img)
if not book_id:
book_id = recognizer.match_cover(img)
if not book_id:
print("无法识别书籍编号或封面")
return
# 查询位置并提示
location = mapper.get_location(book_id)
print(f"识别结果:书籍编号 {book_id}")
print(f"应归位至:{location}")
if __name__ == "__main__":
main()
配套文件说明
1. README.md(项目说明)
# 图书馆书籍归位辅助工具
## 功能
通过智能视觉识别书籍编号/封面,自动提示正确书架位置,减轻管理员工作量。
## 安装依赖
1. 安装Python 3.8+
2. 安装Tesseract OCR引擎(https://github.com/tesseract-ocr/tesseract)
3. 安装Python库:
bash
pip install opencv-python pytesseract pillow numpy
## 目录结构
- `main.py`:主程序
- `covers_db/`:封面样本库(存放书籍封面图片,文件名=书籍编号)
- `location_map.json`:位置映射表({"编号": "书架位置"})
- `README.md`:本说明文件
## 使用方法
1. 将待归位书籍放在摄像头前(或修改`main.py`读取本地图片)
2. 运行`python main.py`
3. 程序输出识别结果及应归位位置
2. location_map.json(位置映射表示例)
{
"9787111636644": "A区3排2层",
"9787302518451": "B区1排5层",
"9787121383721": "C区2排1层"
}
核心知识点卡片
- 智能视觉技术:OCR(Tesseract库)识别文字编号,SIFT特征匹配实现封面图像检索
- 模块化设计:拆分
"BookRecognizer"(识别)、
"LocationMapper"(映射)、
"capture_image"(采集)独立模块
- 异常处理:图像采集失败、OCR/匹配无结果时的容错提示
- 依赖管理:明确Tesseract引擎+Python库的协同工作(需手动安装OCR引擎)
- 轻量化部署:命令行交互降低使用门槛,支持摄像头/本地图片双输入
使用注意
1. 需提前采集书籍封面样本存入
"covers_db"(文件名=编号)
2. 位置映射表需管理员维护更新(
"location_map.json")
3. 光线充足环境下识别准确率更高,模糊图像可能导致匹配失败
代码已按移动端阅读习惯精简,关键逻辑加注释,可直接复制运行(需配置Tesseract路径)。
关注我,有更多实用程序等着你!