[英]How to calculate pixel area of an image in Lambda from an S3 bucket?
我正在嘗試計算上傳到 S3 中存儲桶的圖像的像素區域。 到目前為止,我已經成功地觸發了我的 Lambda function 以響應 S3 中的圖像上傳,我還成功地添加了所有必要的庫。
為了讀取加載到存儲桶中的圖像,我使用了cv2.imread()
中的key
,但在這樣做時我收到了路徑完整性警告。
警告
[ WARN:0@0.470] global /io/opencv/modules/imgcodecs/src/loadsave.cpp
(239) findDecoder imread_('public/IMG-10.jpg'):
can't open/read file: check file path/integrity
lambda_函數.py
import boto3
import base64
import numpy as np
import cv2
s3_client = boto3.client('s3')
def lambda_handler(event, context):
print(event)
# getting bucket and object key from event object
source_bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
# taking image from bucket to calculate pixel area
image = cv2.imread(key)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray,0,255,cv2.THRESH_OTSU + cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
total = 0
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
mask = np.zeros(image.shape, dtype=np.uint8)
cv2.fillPoly(mask, [c], [255,255,255])
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
pixels = cv2.countNonZero(mask)
total += pixels
cv2.putText(image, '{}'.format(pixels), (x,y - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255,255), 2)
print(total)
我的問題是如何通過opencv正確訪問要讀取的圖片路徑。
需要先建立到S3的連接,然后下載圖像數據,最后用OpenCV解碼數據。
完整示例代碼:
from io import BytesIO
import boto3
import base64
import numpy as np
import cv2
s3_client = boto3.client('s3')
def lambda_handler(event, context):
print(event)
# getting bucket and object key from event object
source_bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
img_file = BytesIO()
s3_client.download_fileobj(source_bucket, key, img_file)
np_1d_array = np.frombuffer(img_file.getbuffer(), dtype="uint8")
image = cv2.imdecode(np_1d_array, cv2.IMREAD_COLOR)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray,0,255,cv2.THRESH_OTSU + cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
total = 0
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
mask = np.zeros(image.shape, dtype=np.uint8)
cv2.fillPoly(mask, [c], [255,255,255])
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
pixels = cv2.countNonZero(mask)
total += pixels
cv2.putText(image, '{}'.format(pixels), (x,y - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255,255), 2)
print("ÁREA EM PIXEL:", total)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.