動画を挿入するとエラーが出てしまい、読み取ることができない
Show older comments
動画を読み取り、1フレームごとに分け画像として保存するプログラムを書いたのですが、まず動画を読み込むことができずエラーが出てしまいます。どこが間違っているかご教授お願い致します。
video_path = '読み込む動画ファイルのパス';
video = VideoReader(video_path);
output_dir = '出力先のパス';
output_file_prefix = 'frame_';
frame_idx = 1;
centroid_data = [];
% 画像保存用フォルダの作成
image_folder = fullfile(output_dir, 'frames');
if ~isfolder(image_folder)
mkdir(image_folder);
end
while hasFrame(video)
frame = readFrame(video);
gray_frame = rgb2gray(frame);
[height, width] = size(gray_frame);
total_weight = 0;
cX_sum = 0;
cY_sum = 0;
for y = 1:height
for x = 1:width
pixel_value = double(gray_frame(y, x));
weight = pixel_value;
total_weight = total_weight + weight;
cX_sum = cX_sum + x * weight;
cY_sum = cY_sum + y * weight;
end
end
cX = cX_sum / total_weight;
cY = cY_sum / total_weight;
fprintf('フレーム %d: 輝度重心の座標: (%.2f, %.2f)\n', frame_idx, cX, cY);
output_file_path = fullfile(image_folder, strcat(output_file_prefix, num2str(frame_idx), '.jpg'));
imwrite(gray_frame, output_file_path);
centroid_data(frame_idx, :) = [cX, cY];
frame_idx = frame_idx + 1;
end
csv_file_path = fullfile(output_dir, 'centroid_data.csv');
csvwrite(csv_file_path, centroid_data);
% 輝度重心の座標の軌跡の画像生成
figure;
plot(centroid_data(:, 1), centroid_data(:, 2), 'b-', 'LineWidth', 2);
title('輝度重心の座標の軌跡');
xlabel('x座標');
ylabel('y座標');
grid on;
% 標準偏差の計算と表示
std_x = std(centroid_data(:, 1));
std_y = std(centroid_data(:, 2));
std_text = sprintf('標準偏差\nx座標: %.2f\ny座標: %.2f', std_x, std_y);
text(0.1, 0.9, std_text, 'Units', 'normalized', 'FontSize', 12);
% 画像ファイルとして保存
image_file_path = fullfile(output_dir, 'centroid_trajectory.png');
saveas(gcf, image_file_path);
3 Comments
どんなエラーが出ましたか?入出力のパスを適当に設定するとエラー無く結果が出力されますよ。
video_path = '読み込む動画ファイルのパス';
video = VideoReader(video_path);
颯太
on 7 Nov 2023
Atsushi Ueno
on 7 Nov 2023
ファイル名に含まれる全角スペースが問題の原因だと思います。
原因を知るにはVideoReaderのソースコードを調べていく必要があります。何度か試してみた事がありますが、内部のコードを追えなかったりブラックボックスに突き当ったりして上手くいきません。
Answers (1)
Kojiro Saito
on 7 Nov 2023
追加コメントにあるスクリーンショットを見ると、video_pathが空の文字列になってしまっています。

スクリーンショットではコードの先頭部分が見えないのですが、動画ファイルを指定するところで、
video_path = 'ヒーター 光のみ.avi';
のようにaviファイルを指定できていないように見受けられます。
Categories
Find more on Video Formats and Interfaces in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!