Error using horzcat Dimensions of arrays.

1 次查看(过去 30 天)
Hi,
Can anyone please help me to solve this error? Thanks!
clc;
% Load the video
video = VideoReader('test1.mp4');
% Initialize the background model
background = read(video, 1);
for i = 2:video.NumberOfFrames
frame = read(video, i);
background = imlincomb(0.5, background, 0.5, frame);
end
% Initialize variables to store the vehicle count and position
vehicle_count = 0;
vehicle_positions = [];
% Loop through each frame in the video
for i = 1:video.NumberOfFrames
frame = read(video, i);
% Subtract the background
difference = abs(frame - background);
difference = imbinarize(rgb2gray(difference), 0.1);
% Remove small objects
difference = bwareaopen(difference, 500);
% Find connected components
components = bwconncomp(difference);
% Loop through each connected component
for j = 1:components.NumObjects
% Get the pixels of the current component
pixels = components.PixelIdxList{j};
% Calculate the bounding box of the component
[rows, cols] = ind2sub(components.ImageSize, pixels);
bbox = [min(cols), min(rows), max(cols) - min(cols), max(rows) - min(rows)];
% Check if the component is a vehicle
if bbox(3) * bbox(4) > 50000
% Increment the vehicle count
vehicle_count = vehicle_count + 1;
% Store the position of the vehicle
vehicle_positions = [vehicle_positions; bbox(1) + bbox(3) / 2, bbox(2) + bbox(4) / 2];
end
end
end
% Display the results
disp(['Number of vehicles: ', num2str(vehicle_count)]);
disp(['Vehicle positions: ', num2str(vehicle_positions)]);
The error is:
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Error in traffic_count (line 52)
disp(['Vehicle positions: ', num2str(vehicle_positions)]);

采纳的回答

Jan
Jan 2023-2-7
编辑:Jan 2023-2-7
num2str(x) replies a CHAR matrix, if x contains several rows:
a = num2str(rand(2))
a = 2×19 char array
'0.32683 0.52028' '0.29436 0.023409'
You cannot concatenate a CHAR vector and a CHAR matrix horizontally. Maybe you want:
disp('Vehicle positions:');
for k = 1:height(vehicle_positions)
fprintf('%g ', vehicle_positions(k, :));
fprintf('\n');
end
or:
disp(['Vehicle positions: ', mat2str(vehicle_positions)]);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

标签

产品


版本

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by