0
我正在開發一款智能汽車項目,在檢測到紅色時汽車應該停下來並檢測到綠色,它應該開始運行。我使用Matlab進行顏色檢測,並使用Arduino來運行汽車。但問題是我無法檢測到綠色,代碼只檢測到紅色並停止了車輛。我無法弄清楚問題所在。有關使用Matlab和Arduino檢測紅色和綠色的問題
我的代碼是:
vid = videoinput('winvideo',1 ,'YUY2_320x240');
s=serial('COM9','BAUD',9600);
fopen(s); %open serial port
set(vid, 'FramesPerTrigger', Inf);
set(vid, 'ReturnedColorspace', 'rgb')
vid.FrameGrabInterval = 10;
start(vid)
%set a loop that stop after 100 frames of aquisition
for i=1:100
IMRED = getsnapshot(vid); % get the snapshot of the current frame
diff_im = imsubtract(IMRED(:,:,1), rgb2gray(IMRED)); % subtract red component from the grayscale image to extract the red component in image.
gr=graythresh(diff_im);
diff_im1 = imsubtract(IMRED(:,:,2), rgb2gray(IMRED)); %subtract green component from the grayscale image to extract the green component in image.
gr1=graythresh(diff_im1);
diff_im = medfilt2(diff_im, [3 3]); % median filter to filter the noise.
diff_im1 = medfilt2(diff_im1, [3 3]);
% convert the resulting grayscale image into a binary image.
diff_im = im2bw(diff_im,.18);
diff_im1 = im2bw(diff_im1,.05);
% Remove all those pixels less than 300px
diff_im = bwareaopen(diff_im,300);
diff_im1 = bwareaopen(diff_im1,300);
% Label all the connected components in the image
[bw bw1] = bwlabel(diff_im, 8);
[L bw2] = bwlabel(diff_im1, 8);
if (bw1<=0 && bw2 <=0) % if no color detected run forward
fprintf(s,100);
elseif (bw1>=1) % if red detected stop the car
while (bw1>=1);
fprintf(s,101);
end
while(~(bw2>=1)) % start the car if green detected
fprintf(s,101);
end
fprintf(s,100);
if (bw2>=1)
fprintf(s,100);
else
fprintf(s,101);
end
else
fprintf(s,100);
end
imshow(IMRED)
hold on
hold off
end
stop(vid);
flushdata(vid);
delete(vid);
clear vid;
fclose(s);
clear all;
clc
我得到這樣的輸出:
您是否注意到您的代碼中沒有評論? –
重複將特定顏色隔離出來,而忽略其餘像素。用它來幫助你解決你的問題。 – rayryeng