import cv2 import os import numpy as np from pyzbar.pyzbar import decode from fastapi import FastAPI, File, UploadFile from typing import List import shutil from logging import getLogger, StreamHandler, DEBUG logger = getLogger(__name__) handler = StreamHandler(); handler.setLevel(DEBUG) logger.setLevel(DEBUG) logger.addHandler(handler) logger.propagate = False def qrdec_zbar(image_path): # load image image = cv2.imread(image_path) # QRコードをデコードする dec_infos = decode(image) result_data = "" readable = False if dec_infos: for dec_info in dec_infos: if not dec_info =="": result_data = dec_info.data.decode("utf-8") readable = True break else: pass return {"data": result_data, "readable": readable} # ----------------------------------------------------------- # initial # ----------------------------------------------------------- font = cv2.FONT_HERSHEY_SIMPLEX # ----------------------------------------------------------- # function_qr_dec # ----------------------------------------------------------- def qrdec_cv2(img_bgr): # QRCodeDetectorインスタンス生成 qrd = cv2.QRCodeDetector() # QRコードデコード retval, dec_infos, _, _ = qrd.detectAndDecodeMulti(img_bgr) result_data = "" readable = False if retval: for dec_info in dec_infos: if not dec_info=="": result_data = dec_info readable = True break else: pass return {"data": result_data, "readable": readable} # ----------------------------------------------------------- # sample program # ----------------------------------------------------------- def qrdec(file_path): img_BGR = cv2.imread(file_path, cv2.IMREAD_COLOR) cv2_result = qrdec_cv2(img_BGR) zbar_result = qrdec_zbar(file_path) is_safe_to_read = cv2_result["readable"] and zbar_result["readable"] readable = cv2_result["readable"] or zbar_result["readable"] decoded = "" if cv2_result["readable"]: decoded = cv2_result["data"] elif zbar_result["readable"]: decoded = zbar_result["data"] return {"is_safe_to_read": is_safe_to_read, "readable": readable, "decoded": decoded} app = FastAPI() @app.post("/") async def upload_image(image: UploadFile = File(...)): temp_file_path = os.path.join('/tmp', image.filename) # 画像ファイルの内容を保存または処理する with open(temp_file_path, "wb") as buffer: shutil.copyfileobj(image.file, buffer) # logger.info(f"target file : {temp_file_path}") result = qrdec(temp_file_path) # logger.info(f"response : {result}") return result