iT邦幫忙

1

[AWS]用Lambda與S3實作車牌辨識

ccc 2024-05-01 08:40:37544 瀏覽
  • 分享至 

  • xImage
  •  

架構圖及功能說明


架構圖
https://ithelp.ithome.com.tw/upload/images/20240430/20166874DZXvQE8H0H.jpg
功能說明

  1. 將要辨識的圖片上傳到s3上
  2. 能將辨識到車牌框出來

操作流程說明


  • 開啟S3並新增儲存貯體

https://ithelp.ithome.com.tw/upload/images/20240430/20166874QJeBmdwXJZ.jpg

  • 輸入儲存貯體名稱並勾選'ACL已啟用'

https://ithelp.ithome.com.tw/upload/images/20240430/20166874PNLPtpFsII.jpg

  • 取消'封鎖所有公開存取權'並勾選警示框訊息

https://ithelp.ithome.com.tw/upload/images/20240430/20166874mL8P6QMQX5.jpg

  • 下面選項無需做更動直接建立即可

https://ithelp.ithome.com.tw/upload/images/20240430/20166874Vvfh4IFXcX.jpg

  • 建立好後進入儲存貯體內,即可將要辨識的圖片上傳

https://ithelp.ithome.com.tw/upload/images/20240430/20166874GtisNT7CeV.jpg
https://ithelp.ithome.com.tw/upload/images/20240430/20166874wYVlGn4wwt.jpg

  • 上傳成功後即可在儲存貯體中看到剛剛上傳完的檔案

https://ithelp.ithome.com.tw/upload/images/20240430/201668748LtaasoZAk.jpg

  • 以同樣的步驟將opencv函式庫上傳

https://ithelp.ithome.com.tw/upload/images/20240430/20166874LKkPWnmWkM.jpg

  • 打開Lambda並建立函式

https://ithelp.ithome.com.tw/upload/images/20240430/20166874X705jeay3v.jpg
https://ithelp.ithome.com.tw/upload/images/20240430/20166874KSBtRdCauR.jpg

  • 建立好函式並進入後,在旁邊選單點選層並點選建立layer

https://ithelp.ithome.com.tw/upload/images/20240430/20166874vEVnswJMp5.jpg

  • s3連結要到剛剛在s3中上傳的opencv包中複製URL

https://ithelp.ithome.com.tw/upload/images/20240430/20166874mRpohwcNEc.jpg

  • 接下來回到Lambda頁面並新增層

https://ithelp.ithome.com.tw/upload/images/20240430/20166874qg3yZeLRoR.jpg

  • 點選自訂Layer並選擇剛剛建立的Layer

https://ithelp.ithome.com.tw/upload/images/20240430/20166874xQnDTQZtIG.jpg

  • 新增好層後來到程式碼部分,將以下程式碼貼到上面並壓下'Deploy'

https://ithelp.ithome.com.tw/upload/images/20240430/20166874heip3BN4Ju.jpg

import json
import boto3
import cv2
import numpy as np

def lambda_handler(event, context):
   s3 = boto3.client('s3')

   # Get the bucket name and the uploaded file name
   bucket_name = event['Records'][0]['s3']['bucket']['name']
   file_name = event['Records'][0]['s3']['object']['key']

   print('Bucket name: {}'.format(bucket_name))
   print('Upload file name: {}'.format(file_name))

   # OCR
   client = boto3.client('rekognition')
   response = client.detect_text(Image={'S3Object':{'Bucket':bucket_name,'Name':file_name}})
   print(json.dumps(response))

   # Get detected text
   detected_text = response['TextDetections']
   print("Congratulations! You just fetched text from the image successfully. Total number of responses fetched from the given image {}".format(len(detected_text)))

   # Get the bounding box of each character
   bounding_boxes = [text['Geometry']['BoundingBox'] for text in detected_text if text['Type'] == 'WORD']

   # Load image from S3
   s3_resource = boto3.resource('s3')
   s3_object = s3_resource.Object(bucket_name, file_name)
   s3_object_response = s3_object.get()
   image_content = s3_object_response['Body'].read()
   nparr = np.frombuffer(image_content, np.uint8)
   image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

   # Draw bounding boxes on the image
   image_with_boxes = draw_boxes_on_image(image, bounding_boxes)

   # Encode the modified image back to bytes
   _, encoded_image = cv2.imencode('.jpg', image_with_boxes)
   modified_image_content = encoded_image.tobytes()

   # Upload the modified image back to S3
   modified_file_name = f"c110112109_{file_name}"  //輸出檔案名稱
   s3.put_object(Bucket=bucket_name, Key=modified_file_name, Body=modified_image_content)

   return {
       'statusCode': 200,
       'body': json.dumps('Hello from Lambda!')
   }

def draw_boxes_on_image(image, bounding_boxes):
   # Draw bounding boxes on the image
   for box in bounding_boxes:
       left = int(box['Left'] * image.shape[1])
       top = int(box['Top'] * image.shape[0])
       width = int(box['Width'] * image.shape[1])
       height = int(box['Height'] * image.shape[0])
       cv2.rectangle(image, (left, top), (left+width, top+height), (0, 255, 0), 2)
   return image
  • 接下來到'測試'並撰寫JSON檔,寫好後壓下'測試',如果正確就可以回到程式碼並壓下'Test'執行程式
    https://ithelp.ithome.com.tw/upload/images/20240430/20166874eK4p6uGCJD.jpg
{
 "Records": [
   {
     "eventVersion": "2.1",
     "eventSource": "aws:s3",
     "awsRegion": "us-east-1", //地區
     "eventTime": "1970-01-01T00:00:00.000Z",
     "eventName": "ObjectCreated:Put",
     "userIdentity": {
       "principalId": "EXAMPLE"
     },
     "requestParameters": {
       "sourceIPAddress": "127.0.0.1"
     },
     "responseElements": {
       "x-amz-request-id": "EXAMPLE123456789",
       "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH"
     },
     "s3": {
       "s3SchemaVersion": "1.0",
       "configurationId": "testConfigRule",
       "bucket": {
         "name": "car-scan0",  //寫s3名子
         "ownerIdentity": {
           "principalId": "EXAMPLE"
         },
         "arn": "arn:aws:s3:::car-scan0"  //寫s3名子
       },
       "object": {
         "key": "car.jpg",  //要辨識的照片
         "size": 1024,
         "eTag": "0123456789abcdef0123456789abcdef",
         "sequencer": "0A1B2C3D4E5F678901"
       }
     }
   }
 ]
}
  • 執行成功後,辨識結果就會儲存在s3
    https://ithelp.ithome.com.tw/upload/images/20240430/20166874TA5WGLJMea.jpg
  • 辨識結果
    https://ithelp.ithome.com.tw/upload/images/20240430/20166874MaiRcgCJAw.jpg

參考資料
https://ithelp.ithome.com.tw/articles/10282533?sc=iThomeR


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言