SQLite数据库图片检索失败:图片识别及文件不存在报错求助
图片检索失败问题排查与解决
错误1:无法识别数据库中的图片文件
原因
录入界面使用tk.StringVar()存储图片字节数据,StringVar会自动将二进制字节转换为字符串格式存入数据库,导致取出的BLOB数据并非原始图片二进制,无法被PIL识别解析。
修复步骤
- 将存储图片数据的变量从
tk.StringVar()改为tk.Variable(),支持存储任意类型数据(包括bytes)。 - 调整
load_photo函数中对图片数据的赋值逻辑。
修改后的录入代码关键片段:
# 替换原有的StringVar为Variable photo_data = tk.Variable() def load_photo(): file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png")]) if file_path: img = Image.open(file_path) img.thumbnail((100, 100)) img = ImageTk.PhotoImage(img) photo_label.config(image=img) photo_label.image = img with open(file_path, 'rb') as file: # 直接存储原始字节数据 photo_data.set(file.read())
错误2:找不到图片文件'Pawa_retrieve.jpg'
原因
capture_and_recognize_face函数使用的是仅文件名的相对路径,但图片实际被保存到了retrieved_images子目录下,路径不匹配导致文件找不到。
修复步骤
- 修改
retrieve_and_save_image函数,让它返回图片的完整路径。 - 在调用
capture_and_recognize_face时传入完整路径,而非仅文件名。
修改后的检索代码关键片段:
def retrieve_and_save_image(name): try: conn = sqlite3.connect('employee_vehicle.db') c = conn.cursor() c.execute("SELECT photo FROM employee_vehicle WHERE name = ?", (name,)) result = c.fetchone() if result and result[0]: photo_blob = result[0] # 兼容旧数据(若之前用StringVar存储过,需要转换回字节) if isinstance(photo_blob, str): photo_blob = photo_blob.encode('latin1') current_dir = os.getcwd() image_dir = os.path.join(current_dir, 'retrieved_images') os.makedirs(image_dir, exist_ok=True) image_path = os.path.join(image_dir, f"{name}_retrieve.jpg") image = Image.open(io.BytesIO(photo_blob)) image.save(image_path) print(f"Image '{name}' retrieved and saved as '{image_path}'.") try: saved_image = Image.open(image_path) saved_image.show() print("Saved image opened successfully.") except Exception as e: print(f"Error opening saved image: {e}") conn.close() return image_path # 返回完整路径 else: print(f"No image found for '{name}'.") conn.close() return None except Exception as e: print(f"Error accessing database: {e}") conn.close() return None
修改process_qr_code中的调用逻辑:
# Retrieve and save employee image image_path = retrieve_and_save_image(name) if image_path: # Capture and recognize face capture_and_recognize_face(image_path) else: print("Failed to retrieve image, skipping facial recognition.")
额外优化:在capture_and_recognize_face开头增加路径检查
def capture_and_recognize_face(image_path): if not os.path.exists(image_path): print(f"Image file not found: {image_path}") print("Employee does not exist. Output: 0") return # 后续原有代码不变
总结
- 修复图片存储格式问题,确保数据库中保存的是原始二进制BLOB数据。
- 统一使用完整文件路径,避免因目录结构差异导致的文件找不到问题。
内容的提问来源于stack exchange,提问作者pawan gogoi
相关产品推荐
相关产品推荐

