【发布时间】:2020-09-11 20:53:09
【问题描述】:
所以我使用一个小程序从图像中获取车牌。我通过向谷歌视觉发送图像并搜索我得到的文本来获得类似于正则表达式的牌照。
# -*- coding: utf-8 -*-
"""
Created on Sat May 23 19:42:18 2020
@author: Odatas
"""
import io
import os
from google.cloud import vision_v1p3beta1 as vision
import cv2
import re
# Setup google authen client key
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'client_key.json'
# Source path content all images
SOURCE_PATH = "F:/Radsteuereintreiber/Bilder Temp/"
def recognize_license_plate(img_path):
# Read image with opencv
img = cv2.imread(img_path)
# Get image size
height, width = img.shape[:2]
# Scale image
img = cv2.resize(img, (800, int((height * 800) / width)))
# Save the image to temp file
cv2.imwrite(SOURCE_PATH + "output.jpg", img)
# Create new img path for google vision
img_path = SOURCE_PATH + "output.jpg"
# Create google vision client
client = vision.ImageAnnotatorClient()
# Read image file
with io.open(img_path, 'rb') as image_file:
content = image_file.read()
image = vision.types.Image(content=content)
# Recognize text
response = client.text_detection(image=image)
texts = response.text_annotations
return texts
path = SOURCE_PATH + 'IMG_20200513_173356.jpg'
plate = recognize_license_plate(path)
for text in plate:
# read description
license_plate = text.description
# change all symbols to whitespace.
license_plate = re.sub('[^a-zA-Z0-9\n\.]', ' ', license_plate)
# see if some text matches pattern
test = re.findall('[A-Z]{1,3}\s[A-Z]{1,2}\s\d{1,4}', str(license_plate))
# stop if you found someting
if test is not None:
break
try:
print(test[0])
except Exception:
print("No plate found")
如您所见,我在开始时将环境变量设置为 client_key.json。当我分发我的程序时,我不喜欢将我的密钥发送给每个用户。所以我想直接在程序中包含密钥。
我尝试使用 google 的显式凭据方法,并在程序内部创建一个 json,如下所示:
def explicit():
#creat json
credentials={ REMOVED: INSIDE HER WOULD BE ALL THE INFORMATION FROM THE JSON KEY FILE.
}
json_credentials=json.dumps(credentials)
# Explicitly use service account credentials by specifying the private key
# file.
storage_client = storage.Client.from_service_account_json(
json_credentials)
# Make an authenticated API request
buckets = list(storage_client.list_buckets())
print(buckets)
# [END auth_cloud_explicit]
但我得到了错误。
[Errno 2] 没有这样的文件或目录:我的 json 内容再次被删除
所以我不确定是否必须切换到基于 api 的调用以及如何调用相同的功能?因为我必须上传一张图片,所以我什至认为这不可能通过 api 调用。
所以我有点迷路了。谢谢你的帮助。
【问题讨论】:
-
我有一个解决方案,但我不明白你想做什么?您无需发送服务帐户密钥文件,而是将值硬编码到 Python 文件(纯文本文件)中。你为什么做这个?为了用户方便还是为了安全?
-
用户将程序作为可执行文件获取。所以他没有访问代码的权限。因此,当我将其写入脚本时,它会更安全,就像我只给他钥匙一样。
标签: python-3.x google-cloud-platform google-cloud-vision