ぷろ
import boto3
import cv2
import numpy as np
import matplotlib.pyplot as plt
from io import BytesIO
from botocore.exceptions import NoCredentialsError
import tempfile
import os
# AWSの認証情報を設定
aws_access_key_id = 'YOUR_AWS_ACCESS_KEY_ID'
aws_secret_access_key = 'YOUR_AWS_SECRET_ACCESS_KEY'
region_name = 'YOUR_AWS_REGION'
# S3クライアントを作成
s3 = boto3.client(
's3',
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
region_name=region_name
)
# S3バケット名とファイル名を指定
teacher_bucket_name = 'YOUR_TEACHER_BUCKET_NAME'
teacher_keys = ['path/to/teacher_image1.jpg', 'path/to/teacher_image2.jpg'] # 教師データのパス
video_bucket_name = 'YOUR_VIDEO_BUCKET_NAME'
video_key = 'path/to/your/video/file.mp4'
# 教師データをS3からダウンロードして読み込む
teacher_images = []
for key in teacher_keys:
try:
s3_object = s3.get_object(Bucket=teacher_bucket_name, Key=key)
print(f"Retrieved {key} from S3")
image_stream = BytesIO(s3_object['Body'].read())
image = cv2.imdecode(np.frombuffer(image_stream.read(), np.uint8), cv2.IMREAD_COLOR)
teacher_images.append(image)
except NoCredentialsError:
print("Credentials not available")
except Exception as e:
print(f"Error occurred while retrieving {key}: {e}")
# 動画をS3からダウンロードして一時ファイルに保存
try:
s3_object = s3.get_object(Bucket=video_bucket_name, Key=video_key)
print(f"Retrieved {video_key} from S3")
except NoCredentialsError:
print("Credentials not available")
except Exception as e:
print(f"Error occurred: {e}")
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(s3_object['Body'].read())
temp_video_path = temp_file.name
# 動画をビデオキャプチャとして読み込む
video_stream = cv2.VideoCapture(temp_video_path)
if not video_stream.isOpened():
raise RuntimeError("Error: Could not open video stream")
# 特徴量の抽出とマッチング
def detect_and_compute_features(image):
orb = cv2.ORB_create()
keypoints, descriptors = orb.detectAndCompute(image, None)
return keypoints, descriptors
# 教師データの特徴量を抽出
teacher_descriptors = []
for image in teacher_images:
_, descriptors = detect_and_compute_features(image)
teacher_descriptors.append(descriptors)
# フレームごとの特徴量を抽出して一致度を計算
frame_count = 0
similarity_scores = [[] for _ in range(len(teacher_images))]
best_matches = [-1 for _ in range(len(teacher_images))]
best_frames = [None for _ in range(len(teacher_images))]
while video_stream.isOpened():
ret, frame = video_stream.read()
if ret:
_, frame_descriptors = detect_and_compute_features(frame)
if frame_descriptors is not None:
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
for i, descriptors in enumerate(teacher_descriptors):
matches = bf.match(frame_descriptors, descriptors)
total_matches = len(matches)
similarity_scores[i].append(total_matches)
if total_matches > best_matches[i]:
best_matches[i] = total_matches
best_frames[i] = frame.copy()
else:
for score in similarity_scores:
score.append(0)
frame_count += 1
else:
break
# 動画ストリームをリリースして一時ファイルを削除
video_stream.release()
os.remove(temp_video_path)
# グラフ化と最も一致度の高いフレームの保存
for i, scores in enumerate(similarity_scores):
plt.figure()
plt.plot(scores)
plt.title(f'Similarity Scores for Teacher Image {i+1}')
plt.xlabel('Frame Number')
plt.ylabel('Number of Matches')
plt.show()
if best_frames[i] is not None:
cv2.imwrite(f'best_match_teacher_image_{i+1}.jpg', best_frames[i])
この記事が気に入ったらサポートをしてみませんか?