簡體   English   中英

從 opencv 上傳圖片到 s3 bucket

[英]Upload image from opencv to s3 bucket

在使用 opencv 檢測到人臉后,我正在嘗試將圖像上傳到 s3。jpg 文件已上傳到 s3,但我無法打開圖像。

我可以通過先將圖像保存到本地磁盤然后將其上傳到 s3 來正確上傳,但我想在檢測到人臉后直接進行。 知道怎么做嗎?

# import the necessary packages

# capture frames from the camera

for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    # grab the raw NumPy array representing the image, then initialize the timestamp
    # and occupied/unoccupied text
    image = frame.array

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.CASCADE_SCALE_IMAGE
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # cv2.imwrite('newobama.png', image)

    if len(faces):
        imageName = str(time.strftime("%Y_%m_%d_%H_%M")) + '.jpg'
        #This is not working
        s3.put_object(Bucket="surveillance-cam", Key = imageName, Body = bytes(image), ContentType= 'image/jpeg')   

    # show the frame
    cv2.imshow("Frame", image)
    key = cv2.waitKey(1) & 0xFF

    # clear the stream in preparation for the next frame
    rawCapture.truncate(0)

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break

我相信image對象不是JPEG編碼的二進制表示形式。 這是出於數學目的的NumPy對象

您應該檢查Python OpenCV是否將圖像轉換為字節字符串?

imencode

將圖像編碼到內存緩沖區中。 生成S3可以拍攝的對象

點安裝枕頭

from PIL import Image
from io import BytesIO

img = Image.fromarray(image)
out_img = BytesIO()
img.save(out_img, format='png')
out_img.seek(0)
s3.put_object(Bucket="Bucket Name", Key = imageName, Body = local_image, ContentType= 'image/png')  

這段代碼對我有用,但是它使上傳的圖像略帶藍色。 所以我決定先將圖像保存到本地磁盤,然后再上傳到S3

cv2.imwrite(imageName, image)
local_image = open('./'+imageName, 'rb')
s3.put_object(Bucket="Bucket Name", Key = imageName, Body = local_image, ContentType= 'image/png')  

替換此行:

    s3.put_object(Bucket="surveillance-cam", Key = imageName, Body = bytes(image), ContentType= 'image/jpeg')   

通過

image_string = cv2.imencode('.jpg', image)[1].tostring()
s3.put_object(Bucket="surveillance-cam", Key = imageName, Body=image_string)

它應該工作。

import boto3
import cv2


s3 = boto3.resource('s3')
client = boto3.client('s3')
bucket = s3.Bucket('my-bucket-name')
src_dir = 'target_directory_on_aws/'


image = cv2.imread(image_path)
image_string = cv2.imencode('.png', image)[1].tostring()

client.put_object(
    Bucket='my-bucket-name',
    Key=target_aws_path,  # format: '/my_image.png'
    Body=image_string
)
is_success, buffer = cv2.imencode('.jpg', img)
io_buf = BytesIO(buffer)
s3.upload_fileobj(io_buf, "bucket-name", "file_name")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM